diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/com/redhat/ceylon/compiler/java/codegen/ExpressionTransformer.java b/src/com/redhat/ceylon/compiler/java/codegen/ExpressionTransformer.java
index 5bb3c7c57..8dc4b1417 100755
--- a/src/com/redhat/ceylon/compiler/java/codegen/ExpressionTransformer.java
+++ b/src/com/redhat/ceylon/compiler/java/codegen/ExpressionTransformer.java
@@ -1,1421 +1,1424 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.codegen;
import java.util.Arrays;
import java.util.LinkedList;
import com.redhat.ceylon.compiler.java.codegen.Operators.AssignmentOperatorTranslation;
import com.redhat.ceylon.compiler.java.codegen.Operators.OperatorTranslation;
import com.redhat.ceylon.compiler.java.codegen.Operators.OptimisationStrategy;
import com.redhat.ceylon.compiler.java.util.Decl;
import com.redhat.ceylon.compiler.java.util.Util;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Getter;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.SpecifierExpression;
import com.sun.tools.javac.code.TypeTags;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCConditional;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import com.sun.tools.javac.tree.JCTree.JCForLoop;
import com.sun.tools.javac.tree.JCTree.JCLiteral;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.JCNewArray;
import com.sun.tools.javac.tree.JCTree.JCNewClass;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCUnary;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Name;
/**
* This transformer deals with expressions only
*/
public class ExpressionTransformer extends AbstractTransformer {
static{
// only there to make sure this class is initialised before the enums defined in it, otherwise we
// get an initialisation error
Operators.init();
}
private boolean inStatement = false;
private boolean needDollarThis = false;
public static ExpressionTransformer getInstance(Context context) {
ExpressionTransformer trans = context.get(ExpressionTransformer.class);
if (trans == null) {
trans = new ExpressionTransformer(context);
context.put(ExpressionTransformer.class, trans);
}
return trans;
}
private ExpressionTransformer(Context context) {
super(context);
}
//
// Statement expressions
public JCStatement transform(Tree.ExpressionStatement tree) {
// ExpressionStatements do not return any value, therefore we don't care about the type of the expressions.
inStatement = true;
JCStatement result = at(tree).Exec(transformExpression(tree.getExpression(), BoxingStrategy.INDIFFERENT, null));
inStatement = false;
return result;
}
public JCStatement transform(Tree.SpecifierStatement op) {
// SpecifierStatement do not return any value, therefore we don't care about the type of the expressions.
inStatement = true;
JCStatement result = at(op).Exec(transformAssignment(op, op.getBaseMemberExpression(), op.getSpecifierExpression().getExpression()));
inStatement = false;
return result;
}
//
// Any sort of expression
JCExpression transformExpression(final Tree.Term expr) {
return transformExpression(expr, BoxingStrategy.BOXED, null);
}
JCExpression transformExpression(final Tree.Term expr, BoxingStrategy boxingStrategy, ProducedType expectedType) {
if (expr == null) {
return null;
}
at(expr);
if (inStatement && boxingStrategy != BoxingStrategy.INDIFFERENT) {
// We're not directly inside the ExpressionStatement anymore
inStatement = false;
}
CeylonVisitor v = new CeylonVisitor(gen());
// FIXME: shouldn't that be in the visitor?
if (expr instanceof Tree.Expression) {
// Cope with things like ((expr))
Tree.Expression expr2 = (Tree.Expression)expr;
while(((Tree.Expression)expr2).getTerm() instanceof Tree.Expression) {
expr2 = (Tree.Expression)expr2.getTerm();
}
expr2.visitChildren(v);
} else {
expr.visit(v);
}
if (!v.hasResult()) {
return make().Erroneous();
}
JCExpression result = v.getSingleResult();
result = applyErasureAndBoxing(result, expr, boxingStrategy, expectedType);
return result;
}
//
// Boxing and erasure of expressions
private JCExpression applyErasureAndBoxing(JCExpression result, Tree.Term expr, BoxingStrategy boxingStrategy, ProducedType expectedType) {
ProducedType exprType = expr.getTypeModel();
boolean exprBoxed = !Util.isUnBoxed(expr);
return applyErasureAndBoxing(result, exprType, exprBoxed, boxingStrategy, expectedType);
}
private JCExpression applyErasureAndBoxing(JCExpression result, ProducedType exprType,
boolean exprBoxed,
BoxingStrategy boxingStrategy, ProducedType expectedType) {
if (expectedType != null
&& !(expectedType.getDeclaration() instanceof TypeParameter)
// don't add cast to an erased type
&& !willEraseToObject(expectedType)
// don't add cast for null
&& !isNothing(exprType)) {
if(willEraseToObject(exprType)){
// Erased types need a type cast
JCExpression targetType = makeJavaType(expectedType, AbstractTransformer.TYPE_ARGUMENT);
exprType = expectedType;
result = make().TypeCast(targetType, result);
}else if(isRawCastNecessaryForVariance(expectedType, exprType)){
// Types with variance types need a type cast
JCExpression targetType = makeJavaType(expectedType, AbstractTransformer.WANT_RAW_TYPE);
// do not change exprType here since this is just a Java workaround
result = make().TypeCast(targetType, result);
}
}
// we must to the boxing after the cast to the proper type
return boxUnboxIfNecessary(result, exprBoxed, exprType, boxingStrategy);
}
private boolean isRawCastNecessaryForVariance(ProducedType expectedType, ProducedType exprType) {
// exactly the same type, doesn't need casting
if(exprType.isExactly(expectedType))
return false;
// if we're not trying to put it into an interface, there's no need
if(!(expectedType.getDeclaration() instanceof Interface))
return false;
// the interface must have type arguments, otherwise we can't use raw types
if(expectedType.getTypeArguments().isEmpty())
return false;
// see if any of those type arguments has variance
boolean hasVariance = false;
for(TypeParameter t : expectedType.getTypeArguments().keySet()){
if(t.isContravariant() || t.isCovariant()){
hasVariance = true;
}
}
if(!hasVariance)
return false;
// see if we're inheriting the interface twice with different type parameters
java.util.List<ProducedType> satisfiedTypes = new LinkedList<ProducedType>();
for(ProducedType superType : exprType.getSupertypes()){
if(superType.getDeclaration() == expectedType.getDeclaration())
satisfiedTypes.add(superType);
}
// we need at least two instantiations
if(satisfiedTypes.size() <= 1)
return false;
// we need at least one that differs
for(ProducedType superType : satisfiedTypes){
if(!exprType.isExactly(superType))
return true;
}
// only inheriting from the same type
return false;
}
//
// Literals
JCExpression ceylonLiteral(String s) {
JCLiteral lit = make().Literal(s);
return lit;
}
public JCExpression transform(Tree.StringLiteral string) {
// FIXME: this is appalling
String value = string
.getText()
.substring(1, string.getText().length() - 1)
.replace("\r\n", "\n")
.replace("\r", "\n")
.replace("\\b", "\b")
.replace("\\t", "\t")
.replace("\\n", "\n")
.replace("\\f", "\f")
.replace("\\r", "\r")
.replace("\\\\", "\\")
.replace("\\\"", "\"")
.replace("\\'", "'")
.replace("\\`", "`");
at(string);
return ceylonLiteral(value);
}
public JCExpression transform(Tree.QuotedLiteral string) {
String value = string
.getText()
.substring(1, string.getText().length() - 1);
JCExpression result = makeSelect(makeIdent(syms().ceylonQuotedType), "instance");
return at(string).Apply(null, result, List.<JCTree.JCExpression>of(make().Literal(value)));
}
public JCExpression transform(Tree.CharLiteral lit) {
// FIXME: go unicode, but how?
JCExpression expr = make().Literal(TypeTags.CHAR, (int) lit.getText().charAt(1));
// XXX make().Literal(lit.value) doesn't work here... something
// broken in javac?
return expr;
}
public JCExpression transform(Tree.FloatLiteral lit) {
JCExpression expr = make().Literal(Double.parseDouble(lit.getText()));
return expr;
}
public JCExpression transform(Tree.NaturalLiteral lit) {
JCExpression expr = make().Literal(Long.parseLong(lit.getText()));
return expr;
}
public JCExpression transformStringExpression(Tree.StringTemplate expr) {
at(expr);
JCExpression builder;
builder = make().NewClass(null, null, makeQualIdentFromString("java.lang.StringBuilder"), List.<JCExpression>nil(), null);
java.util.List<Tree.StringLiteral> literals = expr.getStringLiterals();
java.util.List<Tree.Expression> expressions = expr.getExpressions();
for (int ii = 0; ii < literals.size(); ii += 1) {
Tree.StringLiteral literal = literals.get(ii);
if (!"\"\"".equals(literal.getText())) {// ignore empty string literals
at(literal);
builder = make().Apply(null, makeSelect(builder, "append"), List.<JCExpression>of(transform(literal)));
}
if (ii == expressions.size()) {
// The loop condition includes the last literal, so break out
// after that because we've already exhausted all the expressions
break;
}
Tree.Expression expression = expressions.get(ii);
at(expression);
// Here in both cases we don't need a type cast for erasure
if (isCeylonBasicType(expression.getTypeModel())) {// TODO: Test should be erases to String, long, int, boolean, char, byte, float, double
// If erases to a Java primitive just call append, don't box it just to call format.
builder = make().Apply(null, makeSelect(builder, "append"), List.<JCExpression>of(transformExpression(expression, BoxingStrategy.UNBOXED, null)));
} else {
JCMethodInvocation formatted = make().Apply(null, makeSelect(transformExpression(expression), "toString"), List.<JCExpression>nil());
builder = make().Apply(null, makeSelect(builder, "append"), List.<JCExpression>of(formatted));
}
}
return make().Apply(null, makeSelect(builder, "toString"), List.<JCExpression>nil());
}
public JCExpression transform(Tree.SequenceEnumeration value) {
at(value);
if (value.getExpressionList() == null) {
return makeEmpty();
} else {
java.util.List<Tree.Expression> list = value.getExpressionList().getExpressions();
ProducedType seqElemType = value.getTypeModel().getTypeArgumentList().get(0);
return makeSequence(list, seqElemType);
}
}
public JCTree transform(Tree.This expr) {
at(expr);
if (needDollarThis) {
return makeUnquotedIdent("$this");
} else {
return makeUnquotedIdent("this");
}
}
public JCTree transform(Tree.Super expr) {
at(expr);
return makeUnquotedIdent("super");
}
public JCTree transform(Tree.Outer expr) {
at(expr);
ProducedType outerClass = com.redhat.ceylon.compiler.typechecker.model.Util.getOuterClassOrInterface(expr.getScope());
return makeSelect(makeQuotedIdent(outerClass.getDeclaration().getName()), "this");
}
//
// Unary and Binary operators that can be overridden
//
// Unary operators
public JCExpression transform(Tree.NotOp op) {
// No need for an erasure cast since Term must be Boolean and we never need to erase that
JCExpression term = transformExpression(op.getTerm(), Util.getBoxingStrategy(op), null);
JCUnary jcu = at(op).Unary(JCTree.NOT, term);
return jcu;
}
public JCExpression transform(Tree.IsOp op) {
// we don't need any erasure type cast for an "is" test
JCExpression expression = transformExpression(op.getTerm());
at(op);
return makeTypeTest(expression, op.getType().getTypeModel());
}
public JCTree transform(Tree.Nonempty op) {
// we don't need any erasure type cast for a "nonempty" test
JCExpression expression = transformExpression(op.getTerm());
at(op);
return makeTypeTest(expression, op.getUnit().getSequenceDeclaration().getType());
}
public JCTree transform(Tree.Exists op) {
// we don't need any erasure type cast for an "exists" test
JCExpression expression = transformExpression(op.getTerm());
at(op);
return make().Binary(JCTree.NE, expression, makeNull());
}
public JCExpression transform(Tree.PositiveOp op) {
return transformOverridableUnaryOperator(op, op.getUnit().getInvertableDeclaration());
}
public JCExpression transform(Tree.NegativeOp op) {
return transformOverridableUnaryOperator(op, op.getUnit().getInvertableDeclaration());
}
public JCExpression transform(Tree.UnaryOperatorExpression op) {
return transformOverridableUnaryOperator(op, (ProducedType)null);
}
private JCExpression transformOverridableUnaryOperator(Tree.UnaryOperatorExpression op, Interface compoundType) {
ProducedType leftType = getSupertype(op.getTerm(), compoundType);
return transformOverridableUnaryOperator(op, leftType);
}
private JCExpression transformOverridableUnaryOperator(Tree.UnaryOperatorExpression op, ProducedType expectedType) {
at(op);
Tree.Term term = op.getTerm();
OperatorTranslation operator = Operators.getOperator(op.getClass());
if (operator == null) {
return make().Erroneous();
}
if(operator.getOptimisationStrategy(op, this).useJavaOperator()){
// optimisation for unboxed types
JCExpression expr = transformExpression(term, BoxingStrategy.UNBOXED, expectedType);
// unary + is essentially a NOOP
if(operator == OperatorTranslation.UNARY_POSITIVE)
return expr;
return make().Unary(operator.javacOperator, expr);
}
return make().Apply(null, makeSelect(transformExpression(term, BoxingStrategy.BOXED, expectedType),
Util.getGetterName(operator.ceylonMethod)), List.<JCExpression> nil());
}
//
// Binary operators
public JCExpression transform(Tree.NotEqualOp op) {
OperatorTranslation operator = Operators.OperatorTranslation.BINARY_EQUAL;
OptimisationStrategy optimisationStrategy = operator.getOptimisationStrategy(op, this);
// we want it unboxed only if the operator is optimised
// we don't care about the left erased type, since equals() is on Object
JCExpression left = transformExpression(op.getLeftTerm(), optimisationStrategy.getBoxingStrategy(), null);
// we don't care about the right erased type, since equals() is on Object
JCExpression expr = transformOverridableBinaryOperator(op, operator, optimisationStrategy, left, null);
return at(op).Unary(JCTree.NOT, expr);
}
public JCExpression transform(Tree.RangeOp op) {
// we need to get the range bound type
ProducedType comparableType = getSupertype(op.getLeftTerm(), op.getUnit().getComparableDeclaration());
ProducedType paramType = getTypeArgument(comparableType);
JCExpression lower = transformExpression(op.getLeftTerm(), BoxingStrategy.BOXED, paramType);
JCExpression upper = transformExpression(op.getRightTerm(), BoxingStrategy.BOXED, paramType);
ProducedType rangeType = typeFact().getRangeType(op.getLeftTerm().getTypeModel());
JCExpression typeExpr = makeJavaType(rangeType, CeylonTransformer.CLASS_NEW);
return at(op).NewClass(null, null, typeExpr, List.<JCExpression> of(lower, upper), null);
}
public JCExpression transform(Tree.EntryOp op) {
// no erasure cast needed for both terms
JCExpression key = transformExpression(op.getLeftTerm());
JCExpression elem = transformExpression(op.getRightTerm());
ProducedType entryType = typeFact().getEntryType(op.getLeftTerm().getTypeModel(), op.getRightTerm().getTypeModel());
JCExpression typeExpr = makeJavaType(entryType, CeylonTransformer.CLASS_NEW);
return at(op).NewClass(null, null, typeExpr , List.<JCExpression> of(key, elem), null);
}
public JCTree transform(Tree.DefaultOp op) {
JCExpression left = transformExpression(op.getLeftTerm());
JCExpression right = transformExpression(op.getRightTerm());
String varName = tempName();
JCExpression varIdent = makeUnquotedIdent(varName);
JCExpression test = at(op).Binary(JCTree.NE, varIdent, makeNull());
JCExpression cond = make().Conditional(test , varIdent, right);
JCExpression typeExpr = makeJavaType(op.getTypeModel(), NO_PRIMITIVES);
return makeLetExpr(varName, null, typeExpr, left, cond);
}
public JCTree transform(Tree.ThenOp op) {
JCExpression left = transformExpression(op.getLeftTerm(), Util.getBoxingStrategy(op.getLeftTerm()), typeFact().getBooleanDeclaration().getType());
JCExpression right = transformExpression(op.getRightTerm());
return make().Conditional(left , right, makeNull());
}
public JCTree transform(Tree.InOp op) {
JCExpression left = transformExpression(op.getLeftTerm(), BoxingStrategy.BOXED, typeFact().getEqualityDeclaration().getType());
JCExpression right = transformExpression(op.getRightTerm(), BoxingStrategy.BOXED, typeFact().getCategoryDeclaration().getType());
String varName = tempName();
JCExpression varIdent = makeUnquotedIdent(varName);
JCExpression contains = at(op).Apply(null, makeSelect(right, "contains"), List.<JCExpression> of(varIdent));
JCExpression typeExpr = makeJavaType(op.getLeftTerm().getTypeModel(), NO_PRIMITIVES);
return makeLetExpr(varName, null, typeExpr, left, contains);
}
// Logical operators
public JCExpression transform(Tree.LogicalOp op) {
OperatorTranslation operator = Operators.getOperator(op.getClass());
if(operator == null){
log.error("ceylon", "Not supported yet: "+op.getNodeType());
return at(op).Erroneous(List.<JCTree>nil());
}
// Both terms are Booleans and can't be erased to anything
JCExpression left = transformExpression(op.getLeftTerm(), BoxingStrategy.UNBOXED, null);
return transformLogicalOp(op, operator, left, op.getRightTerm());
}
private JCExpression transformLogicalOp(Node op, OperatorTranslation operator,
JCExpression left, Tree.Term rightTerm) {
// Both terms are Booleans and can't be erased to anything
JCExpression right = transformExpression(rightTerm, BoxingStrategy.UNBOXED, null);
return at(op).Binary(operator.javacOperator, left, right);
}
// Comparison operators
public JCExpression transform(Tree.IdenticalOp op){
// The only thing which might be unboxed is boolean, and we can follow the rules of == for optimising it,
// which are simple and require that both types be booleans to be unboxed, otherwise they must be boxed
OptimisationStrategy optimisationStrategy = OperatorTranslation.BINARY_EQUAL.getOptimisationStrategy(op, this);
JCExpression left = transformExpression(op.getLeftTerm(), optimisationStrategy.getBoxingStrategy(), null);
JCExpression right = transformExpression(op.getRightTerm(), optimisationStrategy.getBoxingStrategy(), null);
return at(op).Binary(JCTree.EQ, left, right);
}
public JCExpression transform(Tree.ComparisonOp op) {
return transformOverridableBinaryOperator(op, op.getUnit().getComparableDeclaration());
}
public JCExpression transform(Tree.CompareOp op) {
return transformOverridableBinaryOperator(op, op.getUnit().getComparableDeclaration());
}
// Arithmetic operators
public JCExpression transform(Tree.ArithmeticOp op) {
return transformOverridableBinaryOperator(op, op.getUnit().getNumericDeclaration());
}
public JCExpression transform(Tree.SumOp op) {
return transformOverridableBinaryOperator(op, op.getUnit().getSummableDeclaration());
}
public JCExpression transform(Tree.RemainderOp op) {
return transformOverridableBinaryOperator(op, op.getUnit().getIntegralDeclaration());
}
// Overridable binary operators
public JCExpression transform(Tree.BinaryOperatorExpression op) {
return transformOverridableBinaryOperator(op, null, null);
}
private JCExpression transformOverridableBinaryOperator(Tree.BinaryOperatorExpression op, Interface compoundType) {
ProducedType leftType = getSupertype(op.getLeftTerm(), compoundType);
ProducedType rightType = getTypeArgument(leftType);
return transformOverridableBinaryOperator(op, leftType, rightType);
}
private JCExpression transformOverridableBinaryOperator(Tree.BinaryOperatorExpression op, ProducedType leftType, ProducedType rightType) {
OperatorTranslation operator = Operators.getOperator(op.getClass());
if (operator == null) {
return make().Erroneous();
}
OptimisationStrategy optimisationStrategy = operator.getOptimisationStrategy(op, this);
JCExpression left = transformExpression(op.getLeftTerm(), optimisationStrategy.getBoxingStrategy(), leftType);
return transformOverridableBinaryOperator(op, operator, optimisationStrategy, left, rightType);
}
private JCExpression transformOverridableBinaryOperator(Tree.BinaryOperatorExpression op,
OperatorTranslation originalOperator, OptimisationStrategy optimisatonStrategy,
JCExpression left, ProducedType rightType) {
JCExpression result = null;
JCExpression right = transformExpression(op.getRightTerm(), optimisatonStrategy.getBoxingStrategy(), rightType);
// optimise if we can
if(optimisatonStrategy.useJavaOperator()){
return make().Binary(originalOperator.javacOperator, left, right);
}
boolean loseComparison =
originalOperator == OperatorTranslation.BINARY_SMALLER
|| originalOperator == OperatorTranslation.BINARY_SMALL_AS
|| originalOperator == OperatorTranslation.BINARY_LARGER
|| originalOperator == OperatorTranslation.BINARY_LARGE_AS;
// for comparisons we need to invoke compare()
OperatorTranslation actualOperator = originalOperator;
if (loseComparison) {
actualOperator = Operators.OperatorTranslation.BINARY_COMPARE;
if (actualOperator == null) {
return make().Erroneous();
}
}
result = at(op).Apply(null, makeSelect(left, actualOperator.ceylonMethod), List.of(right));
if (loseComparison) {
result = at(op).Apply(null, makeSelect(result, originalOperator.ceylonMethod), List.<JCExpression> nil());
}
return result;
}
//
// Operator-Assignment expressions
public JCExpression transform(final Tree.ArithmeticAssignmentOp op){
final AssignmentOperatorTranslation operator = Operators.getAssignmentOperator(op.getClass());
if(operator == null){
log.error("ceylon", "Not supported yet: "+op.getNodeType());
return at(op).Erroneous(List.<JCTree>nil());
}
// see if we can optimise it
if(op.getUnboxed() && Util.isDirectAccessVariable(op.getLeftTerm())){
return optimiseAssignmentOperator(op, operator);
}
// we can use unboxed types if both operands are unboxed
final boolean boxResult = !op.getUnboxed();
// find the proper type
Interface compoundType = op.getUnit().getNumericDeclaration();
if(op instanceof Tree.AddAssignOp){
compoundType = op.getUnit().getSummableDeclaration();
}else if(op instanceof Tree.RemainderAssignOp){
compoundType = op.getUnit().getIntegralDeclaration();
}
final ProducedType leftType = getSupertype(op.getLeftTerm(), compoundType);
final ProducedType rightType = getTypeArgument(leftType, 0);
// we work on boxed types
return transformAssignAndReturnOperation(op, op.getLeftTerm(), boxResult,
leftType, rightType,
new AssignAndReturnOperationFactory(){
@Override
public JCExpression getNewValue(JCExpression previousValue) {
// make this call: previousValue OP RHS
return transformOverridableBinaryOperator(op, operator.binaryOperator,
boxResult ? OptimisationStrategy.NONE : OptimisationStrategy.OPTIMISE,
previousValue, rightType);
}
});
}
public JCExpression transform(Tree.BitwiseAssignmentOp op){
log.error("ceylon", "Not supported yet: "+op.getNodeType());
return at(op).Erroneous(List.<JCTree>nil());
}
public JCExpression transform(final Tree.LogicalAssignmentOp op){
final AssignmentOperatorTranslation operator = Operators.getAssignmentOperator(op.getClass());
if(operator == null){
log.error("ceylon", "Not supported yet: "+op.getNodeType());
return at(op).Erroneous(List.<JCTree>nil());
}
// optimise if we can
if(Util.isDirectAccessVariable(op.getLeftTerm())){
return optimiseAssignmentOperator(op, operator);
}
ProducedType valueType = op.getLeftTerm().getTypeModel();
// we work on unboxed types
return transformAssignAndReturnOperation(op, op.getLeftTerm(), false,
valueType, valueType, new AssignAndReturnOperationFactory(){
@Override
public JCExpression getNewValue(JCExpression previousValue) {
// make this call: previousValue OP RHS
return transformLogicalOp(op, operator.binaryOperator,
previousValue, op.getRightTerm());
}
});
}
private JCExpression optimiseAssignmentOperator(final Tree.AssignmentOp op, final AssignmentOperatorTranslation operator) {
// we don't care about their types since they're unboxed and we know it
JCExpression left = transformExpression(op.getLeftTerm(), BoxingStrategy.UNBOXED, null);
JCExpression right = transformExpression(op.getRightTerm(), BoxingStrategy.UNBOXED, null);
return at(op).Assignop(operator.javacOperator, left, right);
}
// Postfix operator
public JCExpression transform(Tree.PostfixOperatorExpression expr) {
OperatorTranslation operator = Operators.getOperator(expr.getClass());
if(operator == null){
log.error("ceylon", "Not supported yet: "+expr.getNodeType());
return at(expr).Erroneous(List.<JCTree>nil());
}
OptimisationStrategy optimisationStrategy = operator.getOptimisationStrategy(expr, this);
boolean canOptimise = optimisationStrategy.useJavaOperator();
// only fully optimise if we don't have to access the getter/setter
if(canOptimise && Util.isDirectAccessVariable(expr.getTerm())){
JCExpression term = transformExpression(expr.getTerm(), BoxingStrategy.UNBOXED, expr.getTypeModel());
return at(expr).Unary(operator.javacOperator, term);
}
Interface compoundType = expr.getUnit().getOrdinalDeclaration();
ProducedType valueType = getSupertype(expr.getTerm(), compoundType);
ProducedType returnType = getTypeArgument(valueType, 0);
Tree.Term term = expr.getTerm();
List<JCVariableDecl> decls = List.nil();
List<JCStatement> stats = List.nil();
JCExpression result = null;
// we can optimise that case a bit sometimes
boolean boxResult = !canOptimise;
// attr++
// (let $tmp = attr; attr = $tmp.getSuccessor(); $tmp;)
if(term instanceof Tree.BaseMemberExpression){
JCExpression getter = transform((Tree.BaseMemberExpression)term, null);
at(expr);
// Type $tmp = attr
JCExpression exprType = makeJavaType(returnType, boxResult ? NO_PRIMITIVES : 0);
Name varName = names().fromString(tempName("op"));
// make sure we box the results if necessary
getter = applyErasureAndBoxing(getter, term, boxResult ? BoxingStrategy.BOXED : BoxingStrategy.UNBOXED, returnType);
JCVariableDecl tmpVar = make().VarDef(make().Modifiers(0), varName, exprType, getter);
decls = decls.prepend(tmpVar);
// attr = $tmp.getSuccessor()
JCExpression successor;
if(canOptimise){
// use +1/-1 if we can optimise a bit
successor = make().Binary(operator == OperatorTranslation.UNARY_POSTFIX_INCREMENT ? JCTree.PLUS : JCTree.MINUS,
make().Ident(varName), makeInteger(1));
}else{
successor = make().Apply(null,
makeSelect(make().Ident(varName), operator.ceylonMethod),
List.<JCExpression>nil());
// make sure the result is boxed if necessary, the result of successor/predecessor is always boxed
successor = boxUnboxIfNecessary(successor, true, term.getTypeModel(), Util.getBoxingStrategy(term));
}
JCExpression assignment = transformAssignment(expr, term, successor);
stats = stats.prepend(at(expr).Exec(assignment));
// $tmp
result = make().Ident(varName);
}
else if(term instanceof Tree.QualifiedMemberExpression){
// e.attr++
// (let $tmpE = e, $tmpV = $tmpE.attr; $tmpE.attr = $tmpV.getSuccessor(); $tmpV;)
Tree.QualifiedMemberExpression qualified = (Tree.QualifiedMemberExpression) term;
// transform the primary, this will get us a boxed primary
JCExpression e = transformQualifiedMemberPrimary(qualified);
at(expr);
// Type $tmpE = e
JCExpression exprType = makeJavaType(qualified.getTarget().getQualifyingType(), NO_PRIMITIVES);
Name varEName = names().fromString(tempName("opE"));
JCVariableDecl tmpEVar = make().VarDef(make().Modifiers(0), varEName, exprType, e);
// Type $tmpV = $tmpE.attr
JCExpression attrType = makeJavaType(returnType, boxResult ? NO_PRIMITIVES : 0);
Name varVName = names().fromString(tempName("opV"));
JCExpression getter = transformMemberExpression(qualified, make().Ident(varEName), null);
// make sure we box the results if necessary
getter = applyErasureAndBoxing(getter, term, boxResult ? BoxingStrategy.BOXED : BoxingStrategy.UNBOXED, returnType);
JCVariableDecl tmpVVar = make().VarDef(make().Modifiers(0), varVName, attrType, getter);
// define all the variables
decls = decls.prepend(tmpVVar);
decls = decls.prepend(tmpEVar);
// $tmpE.attr = $tmpV.getSuccessor()
JCExpression successor;
if(canOptimise){
// use +1/-1 if we can optimise a bit
successor = make().Binary(operator == OperatorTranslation.UNARY_POSTFIX_INCREMENT ? JCTree.PLUS : JCTree.MINUS,
make().Ident(varVName), makeInteger(1));
}else{
successor = make().Apply(null,
makeSelect(make().Ident(varVName), operator.ceylonMethod),
List.<JCExpression>nil());
// make sure the result is boxed if necessary, the result of successor/predecessor is always boxed
successor = boxUnboxIfNecessary(successor, true, term.getTypeModel(), Util.getBoxingStrategy(term));
}
JCExpression assignment = transformAssignment(expr, term, make().Ident(varEName), successor);
stats = stats.prepend(at(expr).Exec(assignment));
// $tmpV
result = make().Ident(varVName);
}else{
log.error("ceylon", "Not supported yet");
return at(expr).Erroneous(List.<JCTree>nil());
}
// e?.attr++ is probably not legal
// a[i]++ is not for M1 but will be:
// (let $tmpA = a, $tmpI = i, $tmpV = $tmpA.item($tmpI); $tmpA.setItem($tmpI, $tmpV.getSuccessor()); $tmpV;)
// a?[i]++ is probably not legal
// a[i1..i1]++ and a[i1...]++ are probably not legal
// a[].attr++ and a[].e.attr++ are probably not legal
return make().LetExpr(decls, stats, result);
}
// Prefix operator
public JCExpression transform(Tree.PrefixOperatorExpression expr) {
final OperatorTranslation operator = Operators.getOperator(expr.getClass());
if(operator == null){
log.error("ceylon", "Not supported yet: "+expr.getNodeType());
return at(expr).Erroneous(List.<JCTree>nil());
}
OptimisationStrategy optimisationStrategy = operator.getOptimisationStrategy(expr, this);
final boolean canOptimise = optimisationStrategy.useJavaOperator();
// only fully optimise if we don't have to access the getter/setter
if(canOptimise && Util.isDirectAccessVariable(expr.getTerm())){
JCExpression term = transformExpression(expr.getTerm(), BoxingStrategy.UNBOXED, expr.getTypeModel());
return at(expr).Unary(operator.javacOperator, term);
}
Interface compoundType = expr.getUnit().getOrdinalDeclaration();
ProducedType valueType = getSupertype(expr.getTerm(), compoundType);
ProducedType returnType = getTypeArgument(valueType, 0);
// we work on boxed types unless we could have optimised
return transformAssignAndReturnOperation(expr, expr.getTerm(), !canOptimise,
valueType, returnType, new AssignAndReturnOperationFactory(){
@Override
public JCExpression getNewValue(JCExpression previousValue) {
// use +1/-1 if we can optimise a bit
if(canOptimise){
return make().Binary(operator == OperatorTranslation.UNARY_PREFIX_INCREMENT ? JCTree.PLUS : JCTree.MINUS,
previousValue, makeInteger(1));
}
// make this call: previousValue.getSuccessor() or previousValue.getPredecessor()
return make().Apply(null, makeSelect(previousValue, operator.ceylonMethod), List.<JCExpression>nil());
}
});
}
//
// Function to deal with expressions that have side-effects
private interface AssignAndReturnOperationFactory {
JCExpression getNewValue(JCExpression previousValue);
}
private JCExpression transformAssignAndReturnOperation(Node operator, Tree.Term term,
boolean boxResult, ProducedType valueType, ProducedType returnType,
AssignAndReturnOperationFactory factory){
List<JCVariableDecl> decls = List.nil();
List<JCStatement> stats = List.nil();
JCExpression result = null;
// attr
// (let $tmp = OP(attr); attr = $tmp; $tmp)
if(term instanceof Tree.BaseMemberExpression){
JCExpression getter = transform((Tree.BaseMemberExpression)term, null);
at(operator);
// Type $tmp = OP(attr);
JCExpression exprType = makeJavaType(returnType, boxResult ? NO_PRIMITIVES : 0);
Name varName = names().fromString(tempName("op"));
// make sure we box the results if necessary
getter = applyErasureAndBoxing(getter, term, boxResult ? BoxingStrategy.BOXED : BoxingStrategy.UNBOXED, valueType);
JCExpression newValue = factory.getNewValue(getter);
// no need to box/unbox here since newValue and $tmpV share the same boxing type
JCVariableDecl tmpVar = make().VarDef(make().Modifiers(0), varName, exprType, newValue);
decls = decls.prepend(tmpVar);
// attr = $tmp
// make sure the result is unboxed if necessary, $tmp may be boxed
JCExpression value = make().Ident(varName);
value = boxUnboxIfNecessary(value, boxResult, term.getTypeModel(), Util.getBoxingStrategy(term));
JCExpression assignment = transformAssignment(operator, term, value);
stats = stats.prepend(at(operator).Exec(assignment));
// $tmp
// return, with the box type we asked for
result = make().Ident(varName);
}
else if(term instanceof Tree.QualifiedMemberExpression){
// e.attr
// (let $tmpE = e, $tmpV = OP($tmpE.attr); $tmpE.attr = $tmpV; $tmpV;)
Tree.QualifiedMemberExpression qualified = (Tree.QualifiedMemberExpression) term;
// transform the primary, this will get us a boxed primary
JCExpression e = transformQualifiedMemberPrimary(qualified);
at(operator);
// Type $tmpE = e
JCExpression exprType = makeJavaType(qualified.getTarget().getQualifyingType(), NO_PRIMITIVES);
Name varEName = names().fromString(tempName("opE"));
JCVariableDecl tmpEVar = make().VarDef(make().Modifiers(0), varEName, exprType, e);
// Type $tmpV = OP($tmpE.attr)
JCExpression attrType = makeJavaType(returnType, boxResult ? NO_PRIMITIVES : 0);
Name varVName = names().fromString(tempName("opV"));
JCExpression getter = transformMemberExpression(qualified, make().Ident(varEName), null);
// make sure we box the results if necessary
getter = applyErasureAndBoxing(getter, term, boxResult ? BoxingStrategy.BOXED : BoxingStrategy.UNBOXED, valueType);
JCExpression newValue = factory.getNewValue(getter);
// no need to box/unbox here since newValue and $tmpV share the same boxing type
JCVariableDecl tmpVVar = make().VarDef(make().Modifiers(0), varVName, attrType, newValue);
// define all the variables
decls = decls.prepend(tmpVVar);
decls = decls.prepend(tmpEVar);
// $tmpE.attr = $tmpV
// make sure $tmpV is unboxed if necessary
JCExpression value = make().Ident(varVName);
value = boxUnboxIfNecessary(value, boxResult, term.getTypeModel(), Util.getBoxingStrategy(term));
JCExpression assignment = transformAssignment(operator, term, make().Ident(varEName), value);
stats = stats.prepend(at(operator).Exec(assignment));
// $tmpV
// return, with the box type we asked for
result = make().Ident(varVName);
}else{
log.error("ceylon", "Not supported yet");
return at(operator).Erroneous(List.<JCTree>nil());
}
// OP(e?.attr) is probably not legal
// OP(a[i]) is not for M1 but will be:
// (let $tmpA = a, $tmpI = i, $tmpV = OP($tmpA.item($tmpI)); $tmpA.setItem($tmpI, $tmpV); $tmpV;)
// OP(a?[i]) is probably not legal
// OP(a[i1..i1]) and OP(a[i1...]) are probably not legal
// OP(a[].attr) and OP(a[].e.attr) are probably not legal
return make().LetExpr(decls, stats, result);
}
public JCExpression transform(Tree.Parameter param) {
// Transform the expression marking that we're inside a defaulted parameter for $this-handling
needDollarThis = true;
SpecifierExpression spec = param.getDefaultArgument().getSpecifierExpression();
JCExpression expr = expressionGen().transformExpression(spec.getExpression(), Util.getBoxingStrategy(param.getDeclarationModel()), param.getDeclarationModel().getType());
needDollarThis = false;
return expr;
}
//
// Invocations
public JCExpression transform(Tree.InvocationExpression ce) {
return InvocationBuilder.invocation(this, ce).build();
}
// used by ClassDefinitionBuilder too, for super()
public JCExpression transformArg(Tree.Term expr, Parameter parameter, boolean isRaw, java.util.List<ProducedType> typeArgumentModels) {
if (parameter != null) {
ProducedType type = getTypeForParameter(parameter, isRaw, typeArgumentModels);
return transformExpression(expr,
Util.getBoxingStrategy(parameter),
type);
} else {
// Overloaded methods don't have a reference to a parameter
// so we have to treat them differently. Also knowing it's
// overloaded we know we're dealing with Java code so we unbox
ProducedType type = expr.getTypeModel();
return transformExpression(expr,
BoxingStrategy.UNBOXED,
type);
}
}
//
// Member expressions
public interface TermTransformer {
JCExpression transform(JCExpression primaryExpr, String selector);
}
// Qualified members
public JCExpression transform(Tree.QualifiedMemberExpression expr) {
return transform(expr, null);
}
private JCExpression transform(Tree.QualifiedMemberExpression expr, TermTransformer transformer) {
JCExpression result;
if (expr.getMemberOperator() instanceof Tree.SafeMemberOp) {
JCExpression primaryExpr = transformQualifiedMemberPrimary(expr);
String tmpVarName = aliasName("safe");
JCExpression typeExpr = makeJavaType(expr.getTarget().getQualifyingType(), NO_PRIMITIVES);
JCExpression transExpr = transformMemberExpression(expr, makeUnquotedIdent(tmpVarName), transformer);
transExpr = boxUnboxIfNecessary(transExpr, expr, expr.getTarget().getType(), BoxingStrategy.BOXED);
JCExpression testExpr = make().Binary(JCTree.NE, makeUnquotedIdent(tmpVarName), makeNull());
JCExpression condExpr = make().Conditional(testExpr, transExpr, makeNull());
result = makeLetExpr(tmpVarName, null, typeExpr, primaryExpr, condExpr);
} else if (expr.getMemberOperator() instanceof Tree.SpreadOp) {
result = transformSpreadOperator(expr, transformer);
} else {
JCExpression primaryExpr = transformQualifiedMemberPrimary(expr);
result = transformMemberExpression(expr, primaryExpr, transformer);
}
return result;
}
private JCExpression transformSpreadOperator(Tree.QualifiedMemberExpression expr, TermTransformer transformer) {
at(expr);
String varBaseName = aliasName("spread");
// sequence
String srcSequenceName = varBaseName+"$0";
ProducedType srcSequenceType = typeFact().getNonemptySequenceType(expr.getPrimary().getTypeModel());
ProducedType srcElementType = typeFact().getElementType(srcSequenceType);
JCExpression srcSequenceTypeExpr = makeJavaType(srcSequenceType, NO_PRIMITIVES);
JCExpression srcSequenceExpr = transformExpression(expr.getPrimary(), BoxingStrategy.BOXED, srcSequenceType);
// reset back here after transformExpression
at(expr);
// size, getSize() always unboxed, but we need to cast to int for Java array access
String sizeName = varBaseName+"$2";
JCExpression sizeType = make().TypeIdent(TypeTags.INT);
JCExpression sizeExpr = make().TypeCast(syms().intType, make().Apply(null,
make().Select(makeUnquotedIdent(srcSequenceName), names().fromString("getSize")),
List.<JCTree.JCExpression>nil()));
// new array
String newArrayName = varBaseName+"$4";
JCExpression arrayElementType = makeJavaType(expr.getTarget().getType(), NO_PRIMITIVES);
JCExpression newArrayType = make().TypeArray(arrayElementType);
JCNewArray newArrayExpr = make().NewArray(arrayElementType, List.of(makeUnquotedIdent(sizeName)), null);
// return the new array
JCExpression returnArrayType = makeJavaType(expr.getTarget().getType(), SATISFIES);
JCExpression returnArrayIdent = make().QualIdent(syms().ceylonArraySequenceType.tsym);
JCExpression returnArrayTypeExpr;
// avoid putting type parameters such as j.l.Object
if(returnArrayType != null)
returnArrayTypeExpr = make().TypeApply(returnArrayIdent, List.of(returnArrayType));
else // go raw
returnArrayTypeExpr = returnArrayIdent;
JCNewClass returnArray = make().NewClass(null, null,
returnArrayTypeExpr,
List.of(makeUnquotedIdent(newArrayName)), null);
// for loop
Name indexVarName = names().fromString(aliasName("index"));
// int index = 0
JCStatement initVarDef = make().VarDef(make().Modifiers(0), indexVarName, make().TypeIdent(TypeTags.INT), makeInteger(0));
List<JCStatement> init = List.of(initVarDef);
// index < size
JCExpression cond = make().Binary(JCTree.LT, make().Ident(indexVarName), makeUnquotedIdent(sizeName));
// index++
JCExpression stepExpr = make().Unary(JCTree.POSTINC, make().Ident(indexVarName));
List<JCExpressionStatement> step = List.of(make().Exec(stepExpr));
// newArray[index]
JCExpression dstArrayExpr = make().Indexed(makeUnquotedIdent(newArrayName), make().Ident(indexVarName));
// srcSequence.item(box(index))
// index is always boxed
JCExpression boxedIndex = boxType(make().Ident(indexVarName), typeFact().getIntegerDeclaration().getType());
JCExpression sequenceItemExpr = make().Apply(null,
make().Select(makeUnquotedIdent(srcSequenceName), names().fromString("item")),
List.<JCExpression>of(boxedIndex));
// item.member
sequenceItemExpr = applyErasureAndBoxing(sequenceItemExpr, srcElementType, true, BoxingStrategy.BOXED,
expr.getTarget().getQualifyingType());
JCExpression appliedExpr = transformMemberExpression(expr, sequenceItemExpr, transformer);
// reset back here after transformMemberExpression
at(expr);
// we always need to box to put in array
appliedExpr = boxUnboxIfNecessary(appliedExpr, expr,
expr.getTarget().getType(), BoxingStrategy.BOXED);
// newArray[index] = box(srcSequence.item(box(index)).member)
JCStatement body = make().Exec(make().Assign(dstArrayExpr, appliedExpr));
// for
JCForLoop forStmt = make().ForLoop(init, cond , step , body);
// build the whole thing
return makeLetExpr(varBaseName,
List.<JCStatement>of(forStmt),
srcSequenceTypeExpr, srcSequenceExpr,
sizeType, sizeExpr,
newArrayType, newArrayExpr,
returnArray);
}
private JCExpression transformQualifiedMemberPrimary(Tree.QualifiedMemberOrTypeExpression expr) {
if(expr.getTarget() == null)
return at(expr).Erroneous(List.<JCTree>nil());
return transformExpression(expr.getPrimary(), BoxingStrategy.BOXED,
expr.getTarget().getQualifyingType());
}
// Base members
public JCExpression transform(Tree.BaseMemberExpression expr) {
return transform(expr, null);
}
private JCExpression transform(Tree.BaseMemberOrTypeExpression expr, TermTransformer transformer) {
return transformMemberExpression(expr, null, transformer);
}
// Type members
public JCExpression transform(Tree.QualifiedTypeExpression expr) {
return transform(expr, null);
}
private JCExpression transform(Tree.QualifiedTypeExpression expr, TermTransformer transformer) {
JCExpression primaryExpr = transformQualifiedMemberPrimary(expr);
return transformMemberExpression(expr, primaryExpr, transformer);
}
// Generic code for all primaries
public JCExpression transformPrimary(Tree.Primary primary, TermTransformer transformer) {
if (primary instanceof Tree.QualifiedMemberExpression) {
return transform((Tree.QualifiedMemberExpression)primary, transformer);
} else if (primary instanceof Tree.BaseMemberExpression) {
return transform((Tree.BaseMemberExpression)primary, transformer);
} else if (primary instanceof Tree.BaseTypeExpression) {
return transform((Tree.BaseTypeExpression)primary, transformer);
} else if (primary instanceof Tree.QualifiedTypeExpression) {
return transform((Tree.QualifiedTypeExpression)primary, transformer);
} else {
return makeQuotedIdent(((Tree.MemberOrTypeExpression)primary).getDeclaration().getName());
}
}
private JCExpression transformMemberExpression(Tree.StaticMemberOrTypeExpression expr, JCExpression primaryExpr, TermTransformer transformer) {
JCExpression result = null;
// do not throw, an error will already have been reported
Declaration decl = expr.getDeclaration();
if (decl == null) {
return make().Erroneous(List.<JCTree>nil());
}
// Explanation: primaryExpr and qualExpr both specify what is to come before the selector
// but the important difference is that primaryExpr is used for those situations where
// the result comes from the actual Ceylon code while qualExpr is used for those situations
// where we need to refer to synthetic objects (like wrapper classes for toplevel methods)
JCExpression qualExpr = null;
String selector = null;
if (decl instanceof Getter) {
// invoke the getter
if (decl.isToplevel()) {
primaryExpr = null;
qualExpr = makeQualIdent(makeFQIdent(decl.getContainer().getQualifiedNameString()), Util.quoteIfJavaKeyword(decl.getName()), Util.getGetterName(decl.getName()));
selector = null;
} else if (decl.isClassMember()) {
selector = Util.getGetterName(decl.getName());
} else {
// method local attr
if (!isRecursiveReference(expr)) {
primaryExpr = makeQualIdent(primaryExpr, decl.getName() + "$getter");
}
selector = Util.getGetterName(decl.getName());
}
} else if (decl instanceof Value) {
if (decl.isToplevel()) {
// ERASURE
if ("null".equals(decl.getName())) {
// FIXME this is a pretty brain-dead way to go about erase I think
result = makeNull();
} else if (isBooleanTrue(decl)) {
result = makeBoolean(true);
} else if (isBooleanFalse(decl)) {
result = makeBoolean(false);
} else {
// it's a toplevel attribute
primaryExpr = makeQualIdent(makeFQIdent(Util.quoteJavaKeywords(decl.getContainer().getQualifiedNameString())), Util.quoteIfJavaKeyword(decl.getName()));
selector = Util.getGetterName(decl.getName());
}
} else if (Decl.isClassAttribute(decl)) {
if(Decl.isJavaField(decl)){
selector = decl.getName();
}else{
// invoke the getter, using the Java interop form of Util.getGetterName because this is the only case
// (Value inside a Class) where we might refer to JavaBean properties
selector = Util.getGetterName(decl);
}
} else if (decl.isCaptured() || decl.isShared()) {
// invoke the qualified getter
primaryExpr = makeQualIdent(primaryExpr, decl.getName());
selector = Util.getGetterName(decl.getName());
}
} else if (decl instanceof Method) {
if (Decl.isLocal(decl)) {
java.util.List<String> path = new LinkedList<String>();
if (!isRecursiveReference(expr)) {
path.add(decl.getName());
}
path.add(decl.getName());
primaryExpr = null;
qualExpr = makeQuotedQualIdent(path);
selector = null;
} else if (decl.isToplevel()) {
java.util.List<String> path = new LinkedList<String>();
// FQN must start with empty ident (see https://github.com/ceylon/ceylon-compiler/issues/148)
if (!decl.getContainer().getQualifiedNameString().isEmpty()) {
path.add("");
path.addAll(Arrays.asList(decl.getContainer().getQualifiedNameString().split("\\.")));
} else {
path.add("");
}
// class
path.add(decl.getName());
// method
path.add(decl.getName());
primaryExpr = null;
qualExpr = makeQuotedQualIdent(path);
selector = null;
} else {
// not toplevel, not within method, must be a class member
selector = Util.quoteMethodName(Util.quoteMethodNameIfProperty((Method) decl, typeFact()));
}
}
if (result == null) {
boolean useGetter = !(decl instanceof Method) && !(Decl.isJavaField(decl));
if (qualExpr == null && selector == null) {
useGetter = decl.isClassOrInterfaceMember() && Util.isErasedAttribute(decl.getName());
if (useGetter) {
selector = Util.quoteMethodName(decl.getName());
} else {
selector = substitute(decl.getName());
}
}
if (qualExpr == null) {
qualExpr = primaryExpr;
}
if (qualExpr == null && needDollarThis && decl.isClassOrInterfaceMember() && expr.getScope() != decl.getContainer()) {
qualExpr = makeUnquotedIdent("$this");
}
+ if (qualExpr == null && decl.isStaticallyImportable()) {
+ qualExpr = makeQualIdentFromString(decl.getContainer().getQualifiedNameString());
+ }
if (transformer != null) {
result = transformer.transform(qualExpr, selector);
} else {
result = makeQualIdent(qualExpr, selector);
if (useGetter) {
result = make().Apply(List.<JCTree.JCExpression>nil(),
result,
List.<JCTree.JCExpression>nil());
}
}
}
return result;
}
//
// Array access
public JCTree transform(Tree.IndexExpression access) {
boolean safe = access.getIndexOperator() instanceof Tree.SafeIndexOp;
// depends on the operator
Tree.ElementOrRange elementOrRange = access.getElementOrRange();
if(elementOrRange instanceof Tree.Element){
Tree.Element element = (Tree.Element) elementOrRange;
// let's see what types there are
ProducedType leftType = access.getPrimary().getTypeModel();
if(safe)
leftType = access.getUnit().getDefiniteType(leftType);
ProducedType leftCorrespondenceType = leftType.getSupertype(access.getUnit().getCorrespondenceDeclaration());
ProducedType rightType = getTypeArgument(leftCorrespondenceType, 0);
// do the index
JCExpression index = transformExpression(element.getExpression(), BoxingStrategy.BOXED, rightType);
// look at the lhs
JCExpression lhs = transformExpression(access.getPrimary(), BoxingStrategy.BOXED, leftCorrespondenceType);
if(!safe)
// make a "lhs.item(index)" call
return at(access).Apply(List.<JCTree.JCExpression>nil(),
make().Select(lhs, names().fromString("item")), List.of(index));
// make a (let ArrayElem tmp = lhs in (tmp != null ? tmp.item(index) : null)) call
JCExpression arrayType = makeJavaType(leftCorrespondenceType);
Name varName = names().fromString(tempName("safeaccess"));
// tmpVar.item(index)
JCExpression safeAccess = make().Apply(List.<JCTree.JCExpression>nil(),
make().Select(make().Ident(varName), names().fromString("item")), List.of(index));
at(access.getPrimary());
// (tmpVar != null ? safeAccess : null)
JCConditional conditional = make().Conditional(make().Binary(JCTree.NE, make().Ident(varName), makeNull()),
safeAccess, makeNull());
// ArrayElem tmp = lhs
JCVariableDecl tmpVar = make().VarDef(make().Modifiers(0), varName, arrayType, lhs);
// (let tmpVar in conditional)
return make().LetExpr(tmpVar, conditional);
}else{
// find the types
ProducedType leftType = access.getPrimary().getTypeModel();
ProducedType leftRangedType = leftType.getSupertype(access.getUnit().getRangedDeclaration());
ProducedType rightType = getTypeArgument(leftRangedType, 0);
// look at the lhs
JCExpression lhs = transformExpression(access.getPrimary(), BoxingStrategy.BOXED, leftRangedType);
// do the indices
Tree.ElementRange range = (Tree.ElementRange) elementOrRange;
JCExpression start = transformExpression(range.getLowerBound(), BoxingStrategy.BOXED, rightType);
JCExpression end;
if(range.getUpperBound() != null)
end = transformExpression(range.getUpperBound(), BoxingStrategy.BOXED, rightType);
else
end = makeNull();
// make a "lhs.span(start, end)" call
return at(access).Apply(List.<JCTree.JCExpression>nil(),
make().Select(lhs, names().fromString("span")), List.of(start, end));
}
}
//
// Assignment
public JCExpression transform(Tree.AssignOp op) {
return transformAssignment(op, op.getLeftTerm(), op.getRightTerm());
}
private JCExpression transformAssignment(Node op, Tree.Term leftTerm, Tree.Term rightTerm) {
// FIXME: can this be anything else than a Tree.MemberOrTypeExpression?
TypedDeclaration decl = (TypedDeclaration) ((Tree.MemberOrTypeExpression)leftTerm).getDeclaration();
// Remember and disable inStatement for RHS
boolean tmpInStatement = inStatement;
inStatement = false;
// right side
final JCExpression rhs = transformExpression(rightTerm, Util.getBoxingStrategy(decl), decl.getType());
if (tmpInStatement) {
return transformAssignment(op, leftTerm, rhs);
} else {
ProducedType valueType = leftTerm.getTypeModel();
return transformAssignAndReturnOperation(op, leftTerm, Util.getBoxingStrategy(decl) == BoxingStrategy.BOXED,
valueType, valueType, new AssignAndReturnOperationFactory(){
@Override
public JCExpression getNewValue(JCExpression previousValue) {
return rhs;
}
});
}
}
private JCExpression transformAssignment(final Node op, Tree.Term leftTerm, JCExpression rhs) {
// left hand side can be either BaseMemberExpression, QualifiedMemberExpression or array access (M2)
// TODO: array access (M2)
JCExpression expr = null;
if(leftTerm instanceof Tree.BaseMemberExpression)
expr = null;
else if(leftTerm instanceof Tree.QualifiedMemberExpression){
Tree.QualifiedMemberExpression qualified = ((Tree.QualifiedMemberExpression)leftTerm);
expr = transformExpression(qualified.getPrimary(), BoxingStrategy.BOXED, qualified.getTarget().getQualifyingType());
}else{
log.error("ceylon", "Not supported yet: "+op.getNodeType());
return at(op).Erroneous(List.<JCTree>nil());
}
return transformAssignment(op, leftTerm, expr, rhs);
}
private JCExpression transformAssignment(Node op, Tree.Term leftTerm, JCExpression lhs, JCExpression rhs) {
JCExpression result = null;
// FIXME: can this be anything else than a Tree.MemberOrTypeExpression?
TypedDeclaration decl = (TypedDeclaration) ((Tree.MemberOrTypeExpression)leftTerm).getDeclaration();
boolean variable = decl.isVariable();
at(op);
String selector = Util.getSetterName(decl);
if (decl.isToplevel()) {
// must use top level setter
lhs = makeQualIdent(makeFQIdent(Util.quoteJavaKeywords(decl.getContainer().getQualifiedNameString())), Util.quoteIfJavaKeyword(decl.getName()));
} else if ((decl instanceof Getter)) {
// must use the setter
if (Decl.isLocal(decl)) {
lhs = makeQualIdent(lhs, decl.getName() + "$setter");
}
} else if (variable && (Decl.isClassAttribute(decl))) {
// must use the setter, nothing to do, unless it's a java field
if(Decl.isJavaField(decl))
result = at(op).Assign(makeQualIdent(lhs, decl.getName()), rhs);
} else if (variable && (decl.isCaptured() || decl.isShared())) {
// must use the qualified setter
lhs = makeQualIdent(lhs, decl.getName());
} else if (!variable && Decl.withinMethod(decl) && decl.isCaptured()) {
// this only happens for SpecifierStatement, when assigning a value to a final
// variable after it has been declared
result = at(op).Assign(makeSelect(decl.getName(), "value"), rhs);
} else {
result = at(op).Assign(makeQualIdent(lhs, decl.getName()), rhs);
}
if (result == null) {
result = make().Apply(List.<JCTree.JCExpression>nil(),
makeQualIdent(lhs, selector),
List.<JCTree.JCExpression>of(rhs));
}
return result;
}
//
// Type helper functions
private ProducedType getSupertype(Tree.Term term, Interface compoundType){
return term.getTypeModel().getSupertype(compoundType);
}
private ProducedType getTypeArgument(ProducedType leftType) {
if (leftType!=null && leftType.getTypeArguments().size()==1) {
return leftType.getTypeArgumentList().get(0);
}
return null;
}
private ProducedType getTypeArgument(ProducedType leftType, int i) {
if (leftType!=null && leftType.getTypeArguments().size() > i) {
return leftType.getTypeArgumentList().get(i);
}
return null;
}
//
// Helper functions
private boolean isRecursiveReference(Tree.StaticMemberOrTypeExpression expr) {
Declaration decl = expr.getDeclaration();
Scope s = expr.getScope();
while (!(s instanceof Declaration) && (s.getContainer() != s)) {
s = s.getContainer();
}
return (s instanceof Declaration) && (s == decl);
}
}
| true | true | private JCExpression transformMemberExpression(Tree.StaticMemberOrTypeExpression expr, JCExpression primaryExpr, TermTransformer transformer) {
JCExpression result = null;
// do not throw, an error will already have been reported
Declaration decl = expr.getDeclaration();
if (decl == null) {
return make().Erroneous(List.<JCTree>nil());
}
// Explanation: primaryExpr and qualExpr both specify what is to come before the selector
// but the important difference is that primaryExpr is used for those situations where
// the result comes from the actual Ceylon code while qualExpr is used for those situations
// where we need to refer to synthetic objects (like wrapper classes for toplevel methods)
JCExpression qualExpr = null;
String selector = null;
if (decl instanceof Getter) {
// invoke the getter
if (decl.isToplevel()) {
primaryExpr = null;
qualExpr = makeQualIdent(makeFQIdent(decl.getContainer().getQualifiedNameString()), Util.quoteIfJavaKeyword(decl.getName()), Util.getGetterName(decl.getName()));
selector = null;
} else if (decl.isClassMember()) {
selector = Util.getGetterName(decl.getName());
} else {
// method local attr
if (!isRecursiveReference(expr)) {
primaryExpr = makeQualIdent(primaryExpr, decl.getName() + "$getter");
}
selector = Util.getGetterName(decl.getName());
}
} else if (decl instanceof Value) {
if (decl.isToplevel()) {
// ERASURE
if ("null".equals(decl.getName())) {
// FIXME this is a pretty brain-dead way to go about erase I think
result = makeNull();
} else if (isBooleanTrue(decl)) {
result = makeBoolean(true);
} else if (isBooleanFalse(decl)) {
result = makeBoolean(false);
} else {
// it's a toplevel attribute
primaryExpr = makeQualIdent(makeFQIdent(Util.quoteJavaKeywords(decl.getContainer().getQualifiedNameString())), Util.quoteIfJavaKeyword(decl.getName()));
selector = Util.getGetterName(decl.getName());
}
} else if (Decl.isClassAttribute(decl)) {
if(Decl.isJavaField(decl)){
selector = decl.getName();
}else{
// invoke the getter, using the Java interop form of Util.getGetterName because this is the only case
// (Value inside a Class) where we might refer to JavaBean properties
selector = Util.getGetterName(decl);
}
} else if (decl.isCaptured() || decl.isShared()) {
// invoke the qualified getter
primaryExpr = makeQualIdent(primaryExpr, decl.getName());
selector = Util.getGetterName(decl.getName());
}
} else if (decl instanceof Method) {
if (Decl.isLocal(decl)) {
java.util.List<String> path = new LinkedList<String>();
if (!isRecursiveReference(expr)) {
path.add(decl.getName());
}
path.add(decl.getName());
primaryExpr = null;
qualExpr = makeQuotedQualIdent(path);
selector = null;
} else if (decl.isToplevel()) {
java.util.List<String> path = new LinkedList<String>();
// FQN must start with empty ident (see https://github.com/ceylon/ceylon-compiler/issues/148)
if (!decl.getContainer().getQualifiedNameString().isEmpty()) {
path.add("");
path.addAll(Arrays.asList(decl.getContainer().getQualifiedNameString().split("\\.")));
} else {
path.add("");
}
// class
path.add(decl.getName());
// method
path.add(decl.getName());
primaryExpr = null;
qualExpr = makeQuotedQualIdent(path);
selector = null;
} else {
// not toplevel, not within method, must be a class member
selector = Util.quoteMethodName(Util.quoteMethodNameIfProperty((Method) decl, typeFact()));
}
}
if (result == null) {
boolean useGetter = !(decl instanceof Method) && !(Decl.isJavaField(decl));
if (qualExpr == null && selector == null) {
useGetter = decl.isClassOrInterfaceMember() && Util.isErasedAttribute(decl.getName());
if (useGetter) {
selector = Util.quoteMethodName(decl.getName());
} else {
selector = substitute(decl.getName());
}
}
if (qualExpr == null) {
qualExpr = primaryExpr;
}
if (qualExpr == null && needDollarThis && decl.isClassOrInterfaceMember() && expr.getScope() != decl.getContainer()) {
qualExpr = makeUnquotedIdent("$this");
}
if (transformer != null) {
result = transformer.transform(qualExpr, selector);
} else {
result = makeQualIdent(qualExpr, selector);
if (useGetter) {
result = make().Apply(List.<JCTree.JCExpression>nil(),
result,
List.<JCTree.JCExpression>nil());
}
}
}
return result;
}
| private JCExpression transformMemberExpression(Tree.StaticMemberOrTypeExpression expr, JCExpression primaryExpr, TermTransformer transformer) {
JCExpression result = null;
// do not throw, an error will already have been reported
Declaration decl = expr.getDeclaration();
if (decl == null) {
return make().Erroneous(List.<JCTree>nil());
}
// Explanation: primaryExpr and qualExpr both specify what is to come before the selector
// but the important difference is that primaryExpr is used for those situations where
// the result comes from the actual Ceylon code while qualExpr is used for those situations
// where we need to refer to synthetic objects (like wrapper classes for toplevel methods)
JCExpression qualExpr = null;
String selector = null;
if (decl instanceof Getter) {
// invoke the getter
if (decl.isToplevel()) {
primaryExpr = null;
qualExpr = makeQualIdent(makeFQIdent(decl.getContainer().getQualifiedNameString()), Util.quoteIfJavaKeyword(decl.getName()), Util.getGetterName(decl.getName()));
selector = null;
} else if (decl.isClassMember()) {
selector = Util.getGetterName(decl.getName());
} else {
// method local attr
if (!isRecursiveReference(expr)) {
primaryExpr = makeQualIdent(primaryExpr, decl.getName() + "$getter");
}
selector = Util.getGetterName(decl.getName());
}
} else if (decl instanceof Value) {
if (decl.isToplevel()) {
// ERASURE
if ("null".equals(decl.getName())) {
// FIXME this is a pretty brain-dead way to go about erase I think
result = makeNull();
} else if (isBooleanTrue(decl)) {
result = makeBoolean(true);
} else if (isBooleanFalse(decl)) {
result = makeBoolean(false);
} else {
// it's a toplevel attribute
primaryExpr = makeQualIdent(makeFQIdent(Util.quoteJavaKeywords(decl.getContainer().getQualifiedNameString())), Util.quoteIfJavaKeyword(decl.getName()));
selector = Util.getGetterName(decl.getName());
}
} else if (Decl.isClassAttribute(decl)) {
if(Decl.isJavaField(decl)){
selector = decl.getName();
}else{
// invoke the getter, using the Java interop form of Util.getGetterName because this is the only case
// (Value inside a Class) where we might refer to JavaBean properties
selector = Util.getGetterName(decl);
}
} else if (decl.isCaptured() || decl.isShared()) {
// invoke the qualified getter
primaryExpr = makeQualIdent(primaryExpr, decl.getName());
selector = Util.getGetterName(decl.getName());
}
} else if (decl instanceof Method) {
if (Decl.isLocal(decl)) {
java.util.List<String> path = new LinkedList<String>();
if (!isRecursiveReference(expr)) {
path.add(decl.getName());
}
path.add(decl.getName());
primaryExpr = null;
qualExpr = makeQuotedQualIdent(path);
selector = null;
} else if (decl.isToplevel()) {
java.util.List<String> path = new LinkedList<String>();
// FQN must start with empty ident (see https://github.com/ceylon/ceylon-compiler/issues/148)
if (!decl.getContainer().getQualifiedNameString().isEmpty()) {
path.add("");
path.addAll(Arrays.asList(decl.getContainer().getQualifiedNameString().split("\\.")));
} else {
path.add("");
}
// class
path.add(decl.getName());
// method
path.add(decl.getName());
primaryExpr = null;
qualExpr = makeQuotedQualIdent(path);
selector = null;
} else {
// not toplevel, not within method, must be a class member
selector = Util.quoteMethodName(Util.quoteMethodNameIfProperty((Method) decl, typeFact()));
}
}
if (result == null) {
boolean useGetter = !(decl instanceof Method) && !(Decl.isJavaField(decl));
if (qualExpr == null && selector == null) {
useGetter = decl.isClassOrInterfaceMember() && Util.isErasedAttribute(decl.getName());
if (useGetter) {
selector = Util.quoteMethodName(decl.getName());
} else {
selector = substitute(decl.getName());
}
}
if (qualExpr == null) {
qualExpr = primaryExpr;
}
if (qualExpr == null && needDollarThis && decl.isClassOrInterfaceMember() && expr.getScope() != decl.getContainer()) {
qualExpr = makeUnquotedIdent("$this");
}
if (qualExpr == null && decl.isStaticallyImportable()) {
qualExpr = makeQualIdentFromString(decl.getContainer().getQualifiedNameString());
}
if (transformer != null) {
result = transformer.transform(qualExpr, selector);
} else {
result = makeQualIdent(qualExpr, selector);
if (useGetter) {
result = make().Apply(List.<JCTree.JCExpression>nil(),
result,
List.<JCTree.JCExpression>nil());
}
}
}
return result;
}
|
diff --git a/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/validation/TypeInfoValidator.java b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/validation/TypeInfoValidator.java
index 61bd0a86..994d3dff 100644
--- a/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/validation/TypeInfoValidator.java
+++ b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/validation/TypeInfoValidator.java
@@ -1,2016 +1,2016 @@
/*******************************************************************************
* Copyright (c) 2010 xored software, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* xored software, Inc. - initial API and Implementation (Alex Panchenko)
*******************************************************************************/
package org.eclipse.dltk.internal.javascript.validation;
import static org.eclipse.dltk.internal.javascript.ti.IReferenceAttributes.PHANTOM;
import static org.eclipse.dltk.internal.javascript.ti.IReferenceAttributes.R_METHOD;
import static org.eclipse.dltk.internal.javascript.validation.JavaScriptValidations.typeOf;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.dltk.ast.ASTNode;
import org.eclipse.dltk.compiler.problem.IProblemIdentifier;
import org.eclipse.dltk.core.builder.IBuildContext;
import org.eclipse.dltk.core.builder.IBuildParticipant;
import org.eclipse.dltk.internal.javascript.parser.JSDocValidatorFactory.TypeChecker;
import org.eclipse.dltk.internal.javascript.ti.ConstantValue;
import org.eclipse.dltk.internal.javascript.ti.ElementValue;
import org.eclipse.dltk.internal.javascript.ti.IReferenceAttributes;
import org.eclipse.dltk.internal.javascript.ti.ITypeInferenceContext;
import org.eclipse.dltk.internal.javascript.ti.TypeInferencer2;
import org.eclipse.dltk.internal.javascript.ti.TypeInferencerVisitor;
import org.eclipse.dltk.javascript.ast.Argument;
import org.eclipse.dltk.javascript.ast.BinaryOperation;
import org.eclipse.dltk.javascript.ast.CallExpression;
import org.eclipse.dltk.javascript.ast.Expression;
import org.eclipse.dltk.javascript.ast.FunctionStatement;
import org.eclipse.dltk.javascript.ast.GetArrayItemExpression;
import org.eclipse.dltk.javascript.ast.Identifier;
import org.eclipse.dltk.javascript.ast.IfStatement;
import org.eclipse.dltk.javascript.ast.NewExpression;
import org.eclipse.dltk.javascript.ast.PropertyExpression;
import org.eclipse.dltk.javascript.ast.ReturnStatement;
import org.eclipse.dltk.javascript.ast.Script;
import org.eclipse.dltk.javascript.ast.ThisExpression;
import org.eclipse.dltk.javascript.ast.ThrowStatement;
import org.eclipse.dltk.javascript.ast.VariableDeclaration;
import org.eclipse.dltk.javascript.core.JavaScriptProblems;
import org.eclipse.dltk.javascript.parser.ISuppressWarningsState;
import org.eclipse.dltk.javascript.parser.JSParser;
import org.eclipse.dltk.javascript.parser.JSProblemReporter;
import org.eclipse.dltk.javascript.parser.PropertyExpressionUtils;
import org.eclipse.dltk.javascript.typeinference.IAssignProtection;
import org.eclipse.dltk.javascript.typeinference.IValueCollection;
import org.eclipse.dltk.javascript.typeinference.IValueReference;
import org.eclipse.dltk.javascript.typeinference.PhantomValueReference;
import org.eclipse.dltk.javascript.typeinference.ReferenceKind;
import org.eclipse.dltk.javascript.typeinference.ReferenceLocation;
import org.eclipse.dltk.javascript.typeinference.ValueReferenceUtil;
import org.eclipse.dltk.javascript.typeinfo.IModelBuilder.IVariable;
import org.eclipse.dltk.javascript.typeinfo.IRAnyType;
import org.eclipse.dltk.javascript.typeinfo.IRClassType;
import org.eclipse.dltk.javascript.typeinfo.IRMember;
import org.eclipse.dltk.javascript.typeinfo.IRMethod;
import org.eclipse.dltk.javascript.typeinfo.IRParameter;
import org.eclipse.dltk.javascript.typeinfo.IRRecordMember;
import org.eclipse.dltk.javascript.typeinfo.IRRecordType;
import org.eclipse.dltk.javascript.typeinfo.IRSimpleType;
import org.eclipse.dltk.javascript.typeinfo.IRType;
import org.eclipse.dltk.javascript.typeinfo.IRVariable;
import org.eclipse.dltk.javascript.typeinfo.ITypeNames;
import org.eclipse.dltk.javascript.typeinfo.JSTypeSet;
import org.eclipse.dltk.javascript.typeinfo.MemberPredicate;
import org.eclipse.dltk.javascript.typeinfo.RModelBuilder;
import org.eclipse.dltk.javascript.typeinfo.TypeCompatibility;
import org.eclipse.dltk.javascript.typeinfo.TypeUtil;
import org.eclipse.dltk.javascript.typeinfo.model.Element;
import org.eclipse.dltk.javascript.typeinfo.model.GenericMethod;
import org.eclipse.dltk.javascript.typeinfo.model.Member;
import org.eclipse.dltk.javascript.typeinfo.model.Method;
import org.eclipse.dltk.javascript.typeinfo.model.Parameter;
import org.eclipse.dltk.javascript.typeinfo.model.ParameterKind;
import org.eclipse.dltk.javascript.typeinfo.model.Property;
import org.eclipse.dltk.javascript.typeinfo.model.RecordMember;
import org.eclipse.dltk.javascript.typeinfo.model.RecordType;
import org.eclipse.dltk.javascript.typeinfo.model.Type;
import org.eclipse.dltk.javascript.typeinfo.model.TypeInfoModelLoader;
import org.eclipse.dltk.javascript.typeinfo.model.TypeKind;
import org.eclipse.emf.common.util.EList;
import org.eclipse.osgi.util.NLS;
public class TypeInfoValidator implements IBuildParticipant {
public void build(IBuildContext context) throws CoreException {
final Script script = JavaScriptValidations.parse(context);
if (script == null) {
return;
}
final TypeInferencer2 inferencer = createTypeInferencer();
inferencer.setModelElement(context.getSourceModule());
final JSProblemReporter reporter = JavaScriptValidations
.createReporter(context);
final ValidationVisitor visitor = new ValidationVisitor(inferencer,
reporter);
inferencer.setVisitor(visitor);
final TypeChecker typeChecker = new TypeChecker(inferencer, reporter);
visitor.setTypeChecker(typeChecker);
inferencer.doInferencing(script);
typeChecker.validate();
}
protected TypeInferencer2 createTypeInferencer() {
return new TypeInferencer2();
}
private static enum VisitorMode {
NORMAL, CALL
}
private static abstract class ExpressionValidator {
abstract void call();
public ExpressionValidator() {
}
private ISuppressWarningsState suppressed;
public ISuppressWarningsState getSuppressed() {
return suppressed;
}
public void setSuppressed(ISuppressWarningsState suppressed) {
this.suppressed = suppressed;
}
}
private static class CallExpressionValidator extends ExpressionValidator {
private final FunctionScope scope;
private final CallExpression node;
private final IValueReference reference;
private final ValidationVisitor visitor;
private final IValueReference[] arguments;
private final List<Method> methods;
public CallExpressionValidator(FunctionScope scope,
CallExpression node, IValueReference reference,
IValueReference[] arguments, List<Method> methods,
ValidationVisitor visitor) {
this.scope = scope;
this.node = node;
this.reference = reference;
this.arguments = arguments;
this.methods = methods;
this.visitor = visitor;
}
public void call() {
visitor.validateCallExpression(scope, node, reference, arguments,
methods);
}
}
private static class ReturnNode {
final ReturnStatement node;
final IValueReference returnValueReference;
public ReturnNode(ReturnStatement node,
IValueReference returnValueReference) {
this.node = node;
this.returnValueReference = returnValueReference;
}
@Override
public String toString() {
return String.valueOf(node).trim() + " -> " + returnValueReference;
}
}
private static class TestReturnStatement extends ExpressionValidator {
private final List<ReturnNode> lst;
private final ValidationVisitor visitor;
private final IRMethod jsMethod;
public TestReturnStatement(IRMethod jsMethod, List<ReturnNode> lst,
ValidationVisitor visitor) {
this.jsMethod = jsMethod;
this.lst = lst;
this.visitor = visitor;
}
public void call() {
IRType firstType = null;
for (ReturnNode element : lst) {
if (element.returnValueReference == null)
continue;
IRType methodType = jsMethod.getType();
if (methodType != null && methodType instanceof IRRecordType) {
String failedPropertyTypeString = visitor
.testObjectPropertyType(
element.returnValueReference,
(IRRecordType) methodType);
if (failedPropertyTypeString != null) {
visitor.getProblemReporter()
.reportProblem(
JavaScriptProblems.DECLARATION_MISMATCH_ACTUAL_RETURN_TYPE,
NLS.bind(
ValidationMessages.DeclarationMismatchWithActualReturnType,
new String[] {
jsMethod.getName(),
TypeUtil.getName(methodType),
failedPropertyTypeString }),
element.node.sourceStart(),
element.node.sourceEnd());
}
return;
}
IRType type = JavaScriptValidations
.typeOf(element.returnValueReference);
if (type != null && methodType != null) {
final TypeCompatibility compatibility = methodType
.isAssignableFrom(type);
if (compatibility != TypeCompatibility.TRUE) {
final ReturnStatement node = element.node;
visitor.getProblemReporter()
.reportProblem(
compatibility == TypeCompatibility.FALSE ? JavaScriptProblems.DECLARATION_MISMATCH_ACTUAL_RETURN_TYPE
: JavaScriptProblems.DECLARATION_MISMATCH_ACTUAL_RETURN_TYPE_PARAMETERIZATION,
NLS.bind(
ValidationMessages.DeclarationMismatchWithActualReturnType,
new String[] {
jsMethod.getName(),
TypeUtil.getName(methodType),
TypeUtil.getName(type) }),
node.sourceStart(), node.sourceEnd());
}
}
if (firstType == null && type != null) {
firstType = type;
}
}
if (firstType != null) {
for (int i = 1; i < lst.size(); i++) {
ReturnNode next = lst.get(i);
IRType nextType = JavaScriptValidations
.typeOf(next.returnValueReference);
if (nextType != null
&& (!nextType.isAssignableFrom(firstType).ok() && !firstType
.isAssignableFrom(nextType).ok())) {
visitor.getProblemReporter()
.reportProblem(
JavaScriptProblems.RETURN_INCONSISTENT,
NLS.bind(
ValidationMessages.ReturnTypeInconsistentWithPreviousReturn,
new String[] {
TypeUtil.getName(nextType),
TypeUtil.getName(firstType) }),
next.node.sourceStart(),
next.node.sourceEnd());
}
}
}
}
}
private static class NotExistingIdentiferValidator extends
ExpressionValidator {
private final FunctionScope scope;
private final Expression identifer;
private final IValueReference reference;
private final ValidationVisitor visitor;
public NotExistingIdentiferValidator(FunctionScope scope,
Expression identifer, IValueReference reference,
ValidationVisitor visitor) {
this.scope = scope;
this.identifer = identifer;
this.reference = reference;
this.visitor = visitor;
}
public void call() {
visitor.validate(scope, identifer, reference);
}
}
private static class NewExpressionValidator extends ExpressionValidator {
private final FunctionScope scope;
private final NewExpression node;
private final IValueReference reference;
final IValueCollection collection;
private final ValidationVisitor validator;
public NewExpressionValidator(FunctionScope scope, NewExpression node,
IValueReference reference, IValueCollection collection,
ValidationVisitor validator) {
this.scope = scope;
this.node = node;
this.reference = reference;
this.collection = collection;
this.validator = validator;
}
public void call() {
validator.checkExpressionType(scope, collection,
node.getObjectClass(), reference);
}
}
private static class PropertyExpressionHolder extends ExpressionValidator {
private final FunctionScope scope;
private final PropertyExpression node;
private final IValueReference reference;
private final ValidationVisitor visitor;
private final boolean exists;
public PropertyExpressionHolder(FunctionScope scope,
PropertyExpression node, IValueReference reference,
ValidationVisitor visitor, boolean exists) {
this.scope = scope;
this.node = node;
this.reference = reference;
this.visitor = visitor;
this.exists = exists;
}
public void call() {
visitor.validateProperty(scope, node, reference, exists);
}
}
static class FunctionScope {
// Set<Expression or IValueReference>
final Set<Object> reported = new HashSet<Object>();
final List<ReturnNode> returnNodes = new ArrayList<ReturnNode>();
boolean throwsException;
void add(Path path) {
if (path != null) {
reported.add(path.start);
reported.add(path.references[0]);
}
}
boolean contains(Path path) {
if (path != null) {
if (reported.contains(path.start)) {
return true;
}
for (IValueReference reference : path.references) {
if (reported.contains(reference)) {
return true;
}
}
}
return false;
}
}
static class Path {
final Expression start;
final IValueReference[] references;
public Path(Expression start, IValueReference[] references) {
this.start = start;
this.references = references;
}
}
public static class ValidationVisitor extends TypeInferencerVisitor {
private final List<ExpressionValidator> expressionValidators = new ArrayList<ExpressionValidator>();
public ValidationVisitor(ITypeInferenceContext context,
JSProblemReporter reporter) {
super(context);
this.reporter = reporter;
}
private final Map<ASTNode, VisitorMode> modes = new IdentityHashMap<ASTNode, VisitorMode>();
private final Stack<ASTNode> visitStack = new Stack<ASTNode>();
@Override
public IValueReference visit(ASTNode node) {
visitStack.push(node);
try {
return super.visit(node);
} finally {
visitStack.pop();
}
}
@Override
public void initialize() {
super.initialize();
modes.clear();
visitStack.clear();
expressionValidators.clear();
variables.clear();
functionScopes.clear();
functionScopes.add(new FunctionScope());
}
@Override
public void done() {
super.done();
for (ExpressionValidator call : expressionValidators
.toArray(new ExpressionValidator[expressionValidators
.size()])) {
final ISuppressWarningsState suppressWarnings = reporter
.getSuppressWarnings();
try {
reporter.restoreSuppressWarnings(call.getSuppressed());
call.call();
} finally {
reporter.restoreSuppressWarnings(suppressWarnings);
}
}
for (IValueReference variable : variables) {
if (variable.getAttribute(IReferenceAttributes.ACCESS) == null) {
final IRVariable jsVariable = (IRVariable) variable
.getAttribute(IReferenceAttributes.R_VARIABLE);
if (jsVariable != null
&& jsVariable
.isSuppressed(JavaScriptProblems.UNUSED_VARIABLE))
continue;
final ReferenceLocation location = variable.getLocation();
reporter.reportProblem(
JavaScriptProblems.UNUSED_VARIABLE,
NLS.bind("Variable {0} is never used",
variable.getName()),
location.getNameStart(), location.getNameEnd());
}
}
}
private VisitorMode currentMode() {
final VisitorMode mode = modes.get(visitStack.peek());
return mode != null ? mode : VisitorMode.NORMAL;
}
@Override
public IValueReference visitNewExpression(NewExpression node) {
IValueReference reference = super.visitNewExpression(node);
pushExpressionValidator(new NewExpressionValidator(
peekFunctionScope(), node, reference, peekContext(), this));
return reference;
}
private final Stack<FunctionScope> functionScopes = new Stack<FunctionScope>();
private static Path path(Expression expression,
IValueReference reference) {
final List<IValueReference> refs = new ArrayList<IValueReference>(8);
for (;;) {
if (expression instanceof PropertyExpression) {
expression = ((PropertyExpression) expression).getObject();
} else if (expression instanceof CallExpression) {
expression = ((CallExpression) expression).getExpression();
} else {
break;
}
refs.add(reference);
reference = reference.getParent();
if (reference == null) {
return null;
}
}
refs.add(reference);
return new Path(expression, refs.toArray(new IValueReference[refs
.size()]));
}
protected final FunctionScope peekFunctionScope() {
return functionScopes.peek();
}
public void enterFunctionScope() {
functionScopes.push(new FunctionScope());
}
public void leaveFunctionScope(IRMethod method) {
final FunctionScope scope = functionScopes.pop();
if (method != null) {
if (!scope.returnNodes.isEmpty()) {
// method.setType(context.resolveTypeRef(method.getType()));
pushExpressionValidator(new TestReturnStatement(method,
scope.returnNodes, this));
} else if (!scope.throwsException && method.getType() != null) {
final ReferenceLocation location = method.getLocation();
reporter.reportProblem(
JavaScriptProblems.DECLARATION_MISMATCH_ACTUAL_RETURN_TYPE,
NLS.bind(
ValidationMessages.DeclarationMismatchNoReturnType,
new String[] { method.getName(),
TypeUtil.getName(method.getType()) }),
location.getNameStart(), location.getNameEnd());
}
}
}
@Override
public IValueReference visitFunctionStatement(FunctionStatement node) {
validateHidesByFunction(node);
enterFunctionScope();
IValueReference reference = super.visitFunctionStatement(node);
final IRMethod method = (IRMethod) reference.getAttribute(R_METHOD);
leaveFunctionScope(method);
return reference;
}
private void validateHidesByFunction(FunctionStatement node) {
List<Argument> args = node.getArguments();
IValueCollection peekContext = peekContext();
for (Argument argument : args) {
IValueReference child = peekContext.getChild(argument
.getArgumentName());
if (child.exists()) {
if (child.getKind() == ReferenceKind.PROPERTY) {
Property property = (Property) child
.getAttribute(IReferenceAttributes.ELEMENT);
if (!property.isHideAllowed()) {
if (property.getDeclaringType() != null) {
reporter.reportProblem(
JavaScriptProblems.PARAMETER_HIDES_VARIABLE,
NLS.bind(
ValidationMessages.ParameterHidesPropertyOfType,
new String[] {
argument.getArgumentName(),
property.getDeclaringType()
.getName() }),
argument.sourceStart(), argument
.sourceEnd());
} else {
reporter.reportProblem(
JavaScriptProblems.PARAMETER_HIDES_VARIABLE,
NLS.bind(
ValidationMessages.ParameterHidesProperty,
argument.getArgumentName()),
argument.sourceStart(), argument
.sourceEnd());
}
}
} else if (!Boolean.TRUE.equals(child
.getAttribute(IReferenceAttributes.HIDE_ALLOWED))) {
if (child.getKind() == ReferenceKind.FUNCTION) {
reporter.reportProblem(
JavaScriptProblems.PARAMETER_HIDES_FUNCTION,
NLS.bind(
ValidationMessages.ParameterHidesFunction,
argument.getArgumentName()),
argument.sourceStart(), argument
.sourceEnd());
} else {
reporter.reportProblem(
JavaScriptProblems.PARAMETER_HIDES_VARIABLE,
NLS.bind(
ValidationMessages.ParameterHidesVariable,
argument.getArgumentName()),
argument.sourceStart(), argument
.sourceEnd());
}
}
}
}
if (node.isDeclaration()) {
final IValueReference child;
final IValueCollection parentScope = getParentScope(peekContext);
if (parentScope == null) {
child = peekContext.getChild(node.getName().getName());
if (getSource().equals(child.getLocation().getSource())) {
return;
}
} else {
child = parentScope.getChild(node.getName().getName());
}
if (child.exists()) {
if (child.getKind() == ReferenceKind.PROPERTY) {
Property property = (Property) child
.getAttribute(IReferenceAttributes.ELEMENT);
if (!property.isHideAllowed()) {
if (property.getDeclaringType() != null) {
reporter.reportProblem(
JavaScriptProblems.FUNCTION_HIDES_VARIABLE,
NLS.bind(
ValidationMessages.FunctionHidesPropertyOfType,
new String[] {
node.getName()
.getName(),
property.getDeclaringType()
.getName() }),
node.getName().sourceStart(), node
.getName().sourceEnd());
} else {
reporter.reportProblem(
JavaScriptProblems.FUNCTION_HIDES_VARIABLE,
NLS.bind(
ValidationMessages.FunctionHidesProperty,
node.getName().getName()), node
.getName().sourceStart(), node
.getName().sourceEnd());
}
}
} else if (!Boolean.TRUE.equals(child
.getAttribute(IReferenceAttributes.HIDE_ALLOWED))) {
if (child.getKind() == ReferenceKind.FUNCTION) {
reporter.reportProblem(
JavaScriptProblems.FUNCTION_HIDES_FUNCTION,
NLS.bind(
ValidationMessages.FunctionHidesFunction,
node.getName().getName()), node
.getName().sourceStart(), node
.getName().sourceEnd());
} else {
reporter.reportProblem(
JavaScriptProblems.FUNCTION_HIDES_VARIABLE,
NLS.bind(
ValidationMessages.FunctionHidesVariable,
node.getName().getName()), node
.getName().sourceStart(), node
.getName().sourceEnd());
}
}
}
}
}
@Override
public IValueReference visitReturnStatement(ReturnStatement node) {
IValueReference returnValueReference = super
.visitReturnStatement(node);
if (node.getValue() != null) {
peekFunctionScope().returnNodes.add(new ReturnNode(node,
returnValueReference));
}
return returnValueReference;
}
@Override
public IValueReference visitThrowStatement(ThrowStatement node) {
peekFunctionScope().throwsException = true;
return super.visitThrowStatement(node);
}
private final IRType functionTypeRef = JSTypeSet
.ref(TypeInfoModelLoader.getInstance().getType(
ITypeNames.FUNCTION));
@Override
public IValueReference visitCallExpression(CallExpression node) {
final Expression expression = node.getExpression();
modes.put(expression, VisitorMode.CALL);
final IValueReference reference = visit(expression);
modes.remove(expression);
if (reference == null) {
visitList(node.getArguments());
return null;
}
if (reference.getAttribute(PHANTOM, true) != null) {
visitList(node.getArguments());
return PhantomValueReference.REFERENCE;
}
if (isUntyped(reference)) {
visitList(node.getArguments());
return null;
}
if (reference.getKind() == ReferenceKind.ARGUMENT) {
if (reference.getDeclaredTypes().contains(functionTypeRef)) {
for (ASTNode argument : node.getArguments()) {
visit(argument);
}
// don't validate function pointer
return null;
}
}
final List<ASTNode> args = node.getArguments();
final IValueReference[] arguments = new IValueReference[args.size()];
for (int i = 0, size = args.size(); i < size; ++i) {
arguments[i] = visit(args.get(i));
}
final List<Method> methods = JavaScriptValidations.extractElements(
reference, Method.class);
if (methods != null && methods.size() == 1
&& methods.get(0) instanceof GenericMethod) {
final GenericMethod method = (GenericMethod) methods.get(0);
if (!validateParameterCount(method, args)) {
final Expression methodNode = expression instanceof PropertyExpression ? ((PropertyExpression) expression)
.getProperty() : expression;
reportMethodParameterError(methodNode, arguments, method);
return null;
}
final JSTypeSet result = evaluateGenericCall(method, arguments);
return result != null ? new ConstantValue(result) : null;
} else {
pushExpressionValidator(new CallExpressionValidator(
peekFunctionScope(), node, reference, arguments,
methods, this));
return reference.getChild(IValueReference.FUNCTION_OP);
}
}
private void pushExpressionValidator(
ExpressionValidator expressionValidator) {
expressionValidator.setSuppressed(reporter.getSuppressWarnings());
expressionValidators.add(expressionValidator);
}
/**
* @param node
* @param reference
* @param methods
* @return
*/
protected void validateCallExpression(FunctionScope scope,
CallExpression node, final IValueReference reference,
IValueReference[] arguments, List<Method> methods) {
final Expression expression = node.getExpression();
final Path path = path(expression, reference);
if (scope.contains(path)) {
return;
}
final Expression methodNode;
if (expression instanceof PropertyExpression) {
methodNode = ((PropertyExpression) expression).getProperty();
} else {
methodNode = expression;
}
if (methods == null || methods.size() == 0)
methods = JavaScriptValidations.extractElements(reference,
Method.class);
if (methods != null) {
Method method = JavaScriptValidations.selectMethod(
getContext(), methods, arguments);
if (method == null) {
final IRType type = JavaScriptValidations.typeOf(reference
.getParent());
if (type != null) {
if (TypeUtil.kind(type) == TypeKind.JAVA) {
reporter.reportProblem(
JavaScriptProblems.WRONG_JAVA_PARAMETERS,
NLS.bind(
ValidationMessages.MethodNotSelected,
new String[] { reference.getName(),
type.getName(),
describeArgTypes(arguments) }),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else {
// TODO also a JS error (that should be
// configurable)
}
}
return;
}
if (method.isDeprecated()) {
reportDeprecatedMethod(methodNode, reference, method);
}
if (!validateParameterCount(method, node.getArguments())) {
reportMethodParameterError(methodNode, arguments, method);
return;
}
if (JavaScriptValidations.isStatic(reference.getParent())
&& !method.isStatic()) {
IRType type = JavaScriptValidations.typeOf(reference
.getParent());
reporter.reportProblem(
JavaScriptProblems.INSTANCE_METHOD,
NLS.bind(
ValidationMessages.StaticReferenceToNoneStaticMethod,
reference.getName(), TypeUtil.getName(type)),
methodNode.sourceStart(), methodNode.sourceEnd());
} else if (reference.getParent() != null
&& !JavaScriptValidations.isStatic(reference
.getParent()) && method.isStatic()) {
IRType type = JavaScriptValidations.typeOf(reference
.getParent());
reporter.reportProblem(JavaScriptProblems.STATIC_METHOD,
NLS.bind(
ValidationMessages.ReferenceToStaticMethod,
reference.getName(), type.getName()),
methodNode.sourceStart(), methodNode.sourceEnd());
}
final List<IRParameter> parameters = RModelBuilder.convert(
getContext(), method.getParameters());
final TypeCompatibility compatibility = validateParameters(
parameters, arguments);
if (compatibility != TypeCompatibility.TRUE) {
String name = method.getName();
if (name == null) {
Identifier identifier = PropertyExpressionUtils
.getIdentifier(methodNode);
if (identifier != null)
name = identifier.getName();
}
reporter.reportProblem(
compatibility == TypeCompatibility.FALSE ? JavaScriptProblems.WRONG_PARAMETERS
: JavaScriptProblems.WRONG_PARAMETERS_PARAMETERIZATION,
NLS.bind(
ValidationMessages.MethodNotApplicableInScript,
new String[] {
name,
describeParamTypes(parameters),
describeArgTypes(arguments,
parameters) }), methodNode
.sourceStart(), methodNode.sourceEnd());
}
} else {
Object attribute = reference.getAttribute(R_METHOD, true);
if (attribute instanceof IRMethod) {
IRMethod method = (IRMethod) attribute;
if (method.isDeprecated()) {
reporter.reportProblem(
JavaScriptProblems.DEPRECATED_FUNCTION,
NLS.bind(ValidationMessages.DeprecatedFunction,
reference.getName()), methodNode
.sourceStart(), methodNode.sourceEnd());
}
if (testVisibility(expression, reference, method)) {
reporter.reportProblem(
JavaScriptProblems.PRIVATE_FUNCTION, NLS.bind(
ValidationMessages.PrivateFunction,
reference.getName()), methodNode
.sourceStart(), methodNode.sourceEnd());
}
List<IRParameter> parameters = method.getParameters();
final TypeCompatibility compatibility = validateParameters(
parameters, arguments);
if (compatibility != TypeCompatibility.TRUE) {
String name = method.getName();
if (name == null) {
Identifier identifier = PropertyExpressionUtils
.getIdentifier(methodNode);
if (identifier != null)
name = identifier.getName();
}
final IProblemIdentifier problemId;
if (method.isTyped()) {
if (compatibility == TypeCompatibility.FALSE) {
problemId = JavaScriptProblems.WRONG_PARAMETERS;
} else {
problemId = JavaScriptProblems.WRONG_PARAMETERS_PARAMETERIZATION;
}
} else {
problemId = JavaScriptProblems.WRONG_PARAMETERS_UNTYPED;
}
reporter.reportProblem(
problemId,
NLS.bind(
ValidationMessages.MethodNotApplicableInScript,
new String[] {
name,
describeParamTypes(parameters),
describeArgTypes(arguments,
parameters) }),
methodNode.sourceStart(), methodNode
.sourceEnd());
}
} else if (!isArrayLookup(expression)
&& !isUntypedParameter(reference)) {
scope.add(path);
final IRType type = JavaScriptValidations.typeOf(reference
.getParent());
if (type != null) {
if (TypeUtil.kind(type) == TypeKind.JAVA) {
reporter.reportProblem(
JavaScriptProblems.UNDEFINED_JAVA_METHOD,
NLS.bind(
ValidationMessages.UndefinedMethod,
reference.getName(), type.getName()),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else if (JavaScriptValidations.isStatic(reference
.getParent())
&& hasInstanceMethod(type, reference.getName())) {
reporter.reportProblem(
JavaScriptProblems.INSTANCE_METHOD,
NLS.bind(
ValidationMessages.StaticReferenceToNoneStaticMethod,
reference.getName(), type.getName()),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else if (!reference.exists()) {
if (reference.getParent() == null
&& isIdentifier(expression)
&& !reference.exists()) {
reporter.reportProblem(
- JavaScriptProblems.UNDEFINED_METHOD,
+ JavaScriptProblems.UNDEFINED_METHOD_IN_SCRIPT,
NLS.bind(
ValidationMessages.UndefinedMethodInScript,
reference.getName()),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else {
reporter.reportProblem(
- JavaScriptProblems.UNDEFINED_METHOD_IN_SCRIPT,
+ JavaScriptProblems.UNDEFINED_METHOD,
NLS.bind(
ValidationMessages.UndefinedMethodOnObject,
reference.getName(), reference
.getParent().getName()),
methodNode.sourceStart(), methodNode
.sourceEnd());
}
}
} else {
IRType referenceType = JavaScriptValidations
.typeOf(reference);
if (functionTypeRef.isAssignableFrom(referenceType) == TypeCompatibility.TRUE) {
return;
}
if (expression instanceof NewExpression) {
if (reference.getKind() == ReferenceKind.TYPE) {
return;
}
IRType newType = JavaScriptValidations
.typeOf(reference);
if (newType != null) {
return;
}
}
IValueReference parent = reference;
while (parent != null) {
if (parent.getName() == IValueReference.ARRAY_OP) {
// ignore array lookup function calls
// like: array[1](),
// those are dynamic.
return;
}
parent = parent.getParent();
}
if (expression instanceof NewExpression) {
reporter.reportProblem(
JavaScriptProblems.WRONG_TYPE_EXPRESSION,
NLS.bind(
ValidationMessages.UndefinedJavascriptType,
((NewExpression) expression)
.getObjectClass()
.toSourceString("")),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else {
if (reference.getParent() == null
&& isIdentifier(expression)
&& !reference.exists()) {
reporter.reportProblem(
- JavaScriptProblems.UNDEFINED_METHOD,
+ JavaScriptProblems.UNDEFINED_METHOD_IN_SCRIPT,
NLS.bind(
ValidationMessages.UndefinedMethodInScript,
reference.getName()),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else {
reporter.reportProblem(
- JavaScriptProblems.UNDEFINED_METHOD_IN_SCRIPT,
+ JavaScriptProblems.UNDEFINED_METHOD,
NLS.bind(
ValidationMessages.UndefinedMethodOnObject,
reference.getName(), reference
.getParent().getName()),
methodNode
.sourceStart(), methodNode
.sourceEnd());
}
}
}
}
}
return;
}
/**
* Checks if the passed reference is an untyped parameter. This method
* helps to identify the common case of callbacks.
*
* @param reference
* @return
*/
private boolean isUntypedParameter(IValueReference reference) {
return reference.getKind() == ReferenceKind.ARGUMENT
&& reference.getDeclaredType() == null;
}
public static boolean isUntyped(IValueReference reference) {
while (reference != null) {
final ReferenceKind kind = reference.getKind();
if (kind == ReferenceKind.ARGUMENT) {
final IRType type = reference.getDeclaredType();
if (type == null || type instanceof IRAnyType) {
return true;
}
} else if (kind == ReferenceKind.THIS
&& reference.getDeclaredType() == null
&& reference.getDirectChildren().isEmpty()) {
return true;
} else if (kind == ReferenceKind.PROPERTY
&& reference.getDeclaredType() == null) {
return true;
}
reference = reference.getParent();
}
return false;
}
private boolean isThisCall(Expression expression) {
return expression instanceof PropertyExpression
&& ((PropertyExpression) expression).getObject() instanceof ThisExpression
&& ((PropertyExpression) expression).getProperty() instanceof Identifier;
}
private boolean hasInstanceMethod(IRType type, String name) {
return ElementValue.findMember(getContext(), type, name,
MemberPredicate.NON_STATIC) != null;
}
private boolean isArrayLookup(ASTNode expression) {
if (expression instanceof GetArrayItemExpression)
return true;
if (expression instanceof PropertyExpression) {
return isArrayLookup(((PropertyExpression) expression)
.getObject());
}
return false;
}
private void reportDeprecatedMethod(ASTNode methodNode,
IValueReference reference, Method method) {
if (method.getDeclaringType() != null) {
reporter.reportProblem(
JavaScriptProblems.DEPRECATED_METHOD,
NLS.bind(ValidationMessages.DeprecatedMethod, reference
.getName(), method.getDeclaringType().getName()),
methodNode.sourceStart(), methodNode.sourceEnd());
} else {
reporter.reportProblem(JavaScriptProblems.DEPRECATED_METHOD,
NLS.bind(ValidationMessages.DeprecatedTopLevelMethod,
reference.getName()), methodNode.sourceStart(),
methodNode.sourceEnd());
}
}
private void reportMethodParameterError(ASTNode methodNode,
IValueReference[] arguments, Method method) {
if (method.getDeclaringType() != null) {
IProblemIdentifier problemId = JavaScriptProblems.WRONG_PARAMETERS;
if (method.getDeclaringType().getKind() == TypeKind.JAVA) {
problemId = JavaScriptProblems.WRONG_JAVA_PARAMETERS;
}
reporter.reportProblem(problemId, NLS.bind(
ValidationMessages.MethodNotApplicable,
new String[] { method.getName(),
describeParamTypes(method.getParameters()),
method.getDeclaringType().getName(),
describeArgTypes(arguments) }), methodNode
.sourceStart(), methodNode.sourceEnd());
} else {
reporter.reportProblem(JavaScriptProblems.WRONG_PARAMETERS, NLS
.bind(ValidationMessages.TopLevelMethodNotApplicable,
new String[] {
method.getName(),
describeParamTypes(method
.getParameters()),
describeArgTypes(arguments) }),
methodNode.sourceStart(), methodNode.sourceEnd());
}
}
private TypeCompatibility validateParameters(
List<IRParameter> parameters, IValueReference[] arguments) {
if (arguments.length > parameters.size()
&& !(parameters.size() > 0 && parameters.get(
parameters.size() - 1).getKind() == ParameterKind.VARARGS))
return TypeCompatibility.FALSE;
int testTypesSize = parameters.size();
if (parameters.size() > arguments.length) {
for (int i = arguments.length; i < parameters.size(); i++) {
final IRParameter p = parameters.get(i);
if (!p.isOptional() && !p.isVarargs())
return TypeCompatibility.FALSE;
}
testTypesSize = arguments.length;
} else if (parameters.size() < arguments.length) {
// is var args..
testTypesSize = parameters.size() - 1;
}
TypeCompatibility result = TypeCompatibility.TRUE;
for (int i = 0; i < testTypesSize; i++) {
IValueReference argument = arguments[i];
IRParameter parameter = parameters.get(i);
if (parameter.getType() instanceof IRRecordType
&& argument != null
&& !(argument.getDeclaredType() instanceof IRRecordType)) {
boolean oneHit = false;
Set<String> argumentsChildren = argument
.getDirectChildren();
for (IRRecordMember member : ((IRRecordType) parameter
.getType()).getMembers()) {
if (argumentsChildren.contains(member.getName())) {
oneHit = true;
if (member.getType() != null) {
IValueReference child = argument
.getChild(member.getName());
final TypeCompatibility pResult = testArgumentType(
member.getType(), child);
if (pResult.after(result)) {
if (pResult == TypeCompatibility.FALSE) {
return pResult;
}
result = pResult;
}
}
} else if (!member.isOptional()) {
return TypeCompatibility.FALSE;
}
}
if (!oneHit)
return TypeCompatibility.FALSE;
} else {
final TypeCompatibility pResult = testArgumentType(
parameter.getType(), argument);
if (pResult.after(result)) {
if (pResult == TypeCompatibility.FALSE) {
return pResult;
}
result = pResult;
}
}
}
// test var args
if (parameters.size() < arguments.length) {
int varargsParameter = parameters.size() - 1;
IRType paramType = parameters.get(varargsParameter).getType();
for (int i = varargsParameter; i < arguments.length; i++) {
IValueReference argument = arguments[i];
final TypeCompatibility pResult = testArgumentType(
paramType, argument);
if (pResult.after(result)) {
if (pResult == TypeCompatibility.FALSE) {
return pResult;
}
result = pResult;
}
}
}
return result;
}
/**
* @param paramType
* @param argument
* @return
*/
private TypeCompatibility testArgumentType(IRType paramType,
IValueReference argument) {
if (argument != null && paramType != null) {
if (paramType instanceof IRRecordType) {
return TypeCompatibility.valueOf(testObjectPropertyType(
argument, (IRRecordType) paramType) == null);
}
IRType argumentType = argument.getDeclaredType();
if (argumentType == null && !argument.getTypes().isEmpty()) {
argumentType = argument.getTypes().getFirst();
}
if (argumentType != null) {
return paramType.isAssignableFrom(argumentType);
}
}
return TypeCompatibility.TRUE;
}
/**
* @param element
* @param type
*/
protected String testObjectPropertyType(IValueReference reference,
IRRecordType type) {
for (IRRecordMember member : type.getMembers()) {
IValueReference child = reference.getChild(member.getName());
IRType referenceType = JavaScriptValidations.typeOf(child);
if (!child.exists()
|| (referenceType != null && member.getType() != null && !member
.getType().isAssignableFrom(referenceType).ok())) {
Set<String> children = reference.getDirectChildren();
if (children.size() == 0)
return "{}";
StringBuilder typeString = new StringBuilder();
typeString.append('{');
for (String childName : children) {
typeString.append(childName);
typeString.append(':');
IRType childType = JavaScriptValidations
.typeOf(reference.getChild(childName));
String typeName = TypeUtil.getName(childType);
typeString.append(typeName == null ? "Object"
: typeName);
typeString.append(',');
}
typeString.setLength(typeString.length() - 1);
typeString.append('}');
return typeString.toString();
}
}
return null;
}
/**
* @param parameters
* @return
*/
private String describeParamTypes(EList<Parameter> parameters) {
StringBuilder sb = new StringBuilder();
for (Parameter parameter : parameters) {
if (sb.length() != 0) {
sb.append(',');
}
if (parameter.getKind() == ParameterKind.OPTIONAL)
sb.append('[');
if (parameter.getType() != null) {
sb.append(parameter.getType().getName());
} else {
sb.append('?');
}
if (parameter.getKind() == ParameterKind.OPTIONAL)
sb.append(']');
if (parameter.getKind() == ParameterKind.VARARGS) {
sb.append("...");
}
}
return sb.toString();
}
private String describeParamTypes(List<IRParameter> parameters) {
StringBuilder sb = new StringBuilder();
for (IRParameter parameter : parameters) {
if (sb.length() != 0) {
sb.append(',');
}
if (parameter.getType() instanceof RecordType) {
sb.append('{');
for (Member member : ((RecordType) parameter.getType())
.getMembers()) {
if (sb.length() > 1)
sb.append(", ");
final boolean optional = member instanceof RecordMember
&& ((RecordMember) member).isOptional();
if (optional)
sb.append('[');
sb.append(member.getName());
if (member.getType() != null) {
sb.append(':');
sb.append(member.getType().getName());
}
if (optional)
sb.append(']');
}
sb.append('}');
} else if (parameter.getType() != null) {
if (parameter.getKind() == ParameterKind.OPTIONAL)
sb.append("[");
if (parameter.getKind() == ParameterKind.VARARGS)
sb.append("...");
sb.append(parameter.getType().getName());
if (parameter.getKind() == ParameterKind.OPTIONAL)
sb.append("]");
} else {
sb.append('?');
}
}
return sb.toString();
}
/**
* @param arguments
* @return
*/
private String describeArgTypes(IValueReference[] arguments) {
return describeArgTypes(arguments,
Collections.<IRParameter> emptyList());
}
/**
* @param arguments
* @param parameters
* @return
*/
private String describeArgTypes(IValueReference[] arguments,
List<IRParameter> parameters) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arguments.length; i++) {
IValueReference argument = arguments[i];
IRParameter parameter = parameters.size() > i ? parameters
.get(i) : null;
if (sb.length() != 0) {
sb.append(',');
}
if (argument == null) {
sb.append("null");
} else if (parameter != null
&& parameter.getType() instanceof IRRecordType) {
describeRecordType(sb, argument,
(IRRecordType) parameter.getType());
} else if (argument.getDeclaredType() != null) {
sb.append(argument.getDeclaredType().getName());
} else {
final JSTypeSet types = argument.getTypes();
if (types.size() == 1) {
sb.append(types.getFirst().getName());
} else {
sb.append('?');
}
}
}
return sb.toString();
}
private void describeRecordType(StringBuilder sb,
IValueReference argument, IRRecordType paramType) {
Set<String> directChildren = argument.getDirectChildren();
sb.append('{');
boolean appendComma = false;
for (String childName : directChildren) {
if (appendComma)
sb.append(", ");
appendComma = true;
sb.append(childName);
IRType memberType = null;
if (paramType != null) {
for (IRRecordMember member : paramType.getMembers()) {
if (member.getName().equals(childName)) {
memberType = member.getType();
break;
}
}
}
if (memberType instanceof IRRecordType) {
sb.append(": ");
describeRecordType(sb, argument.getChild(childName),
(IRRecordType) memberType);
} else {
IValueReference child = argument.getChild(childName);
IRType type = JavaScriptValidations.typeOf(child);
if (type != null) {
if (paramType != null
&& type.getName().equals(ITypeNames.OBJECT)
&& !child.getDirectChildren().isEmpty()) {
sb.append(": ");
describeRecordType(sb, child, null);
} else {
sb.append(':');
sb.append(type.getName());
}
}
}
}
sb.append('}');
}
private <E extends Member> E extractElement(IValueReference reference,
Class<E> elementType, Boolean staticModifierValue) {
final List<E> elements = JavaScriptValidations.extractElements(
reference, elementType);
if (staticModifierValue != null && elements != null
&& elements.size() > 1) {
for (E e : elements) {
if (e.isStatic() == staticModifierValue.booleanValue())
return e;
}
}
return elements != null ? elements.get(0) : null;
}
/**
* Validates the parameter count, returns <code>true</code> if correct.
*
* @param method
* @param callArgs
*
* @return
*/
private boolean validateParameterCount(Method method, List<?> callArgs) {
final EList<Parameter> params = method.getParameters();
if (params.size() == callArgs.size()) {
return true;
}
if (params.size() < callArgs.size()
&& !params.isEmpty()
&& params.get(params.size() - 1).getKind() == ParameterKind.VARARGS) {
return true;
}
if (params.size() > callArgs.size()
&& (params.get(callArgs.size()).getKind() == ParameterKind.OPTIONAL || params
.get(callArgs.size()).getKind() == ParameterKind.VARARGS)) {
return true;
}
return false;
}
@Override
public IValueReference visitPropertyExpression(PropertyExpression node) {
final IValueReference result = super.visitPropertyExpression(node);
if (result == null || result.getAttribute(PHANTOM, true) != null
|| isUntyped(result)) {
return result;
}
if (currentMode() != VisitorMode.CALL) {
pushExpressionValidator(new PropertyExpressionHolder(
peekFunctionScope(), node, result, this,
result.exists()));
}
return result;
}
@Override
protected IValueReference visitAssign(IValueReference left,
IValueReference right, BinaryOperation node) {
if (left != null) {
checkAssign(left, node);
validate(peekFunctionScope(), node.getLeftExpression(), left);
}
return super.visitAssign(left, right, node);
}
protected boolean validate(FunctionScope scope, Expression expr,
IValueReference reference) {
final IValueReference parent = reference.getParent();
if (parent == null) {
// top level
if (expr instanceof Identifier && !reference.exists()) {
scope.add(path(expr, reference));
reporter.reportProblem(
JavaScriptProblems.UNDECLARED_VARIABLE, NLS.bind(
ValidationMessages.UndeclaredVariable,
reference.getName()), expr.sourceStart(),
expr.sourceEnd());
return false;
} else
testPrivate(expr, reference);
} else if (expr instanceof PropertyExpression
&& validate(scope, ((PropertyExpression) expr).getObject(),
parent)) {
final IRType type = JavaScriptValidations.typeOf(parent);
if (type != null && TypeUtil.kind(type) == TypeKind.JAVA
&& !reference.exists()) {
reporter.reportProblem(
JavaScriptProblems.UNDEFINED_JAVA_PROPERTY,
NLS.bind(ValidationMessages.UndefinedProperty,
reference.getName(), type.getName()), expr
.sourceStart(), expr.sourceEnd());
return false;
}
} else if (expr instanceof GetArrayItemExpression
&& !validate(scope,
((GetArrayItemExpression) expr).getArray(), parent)) {
return false;
}
return true;
}
/**
* @param expr
* @param reference
*/
public void testPrivate(Expression expr, IValueReference reference) {
if (reference.getAttribute(IReferenceAttributes.PRIVATE) == Boolean.TRUE) {
Object attribute = reference
.getAttribute(IReferenceAttributes.R_VARIABLE);
if (attribute instanceof IRVariable) {
final IRVariable variable = (IRVariable) attribute;
reporter.reportProblem(JavaScriptProblems.PRIVATE_VARIABLE,
NLS.bind(ValidationMessages.PrivateVariable,
variable.getName()), expr.sourceStart(),
expr.sourceEnd());
} else {
attribute = reference.getAttribute(R_METHOD);
if (attribute instanceof IRMethod) {
IRMethod method = (IRMethod) attribute;
reporter.reportProblem(
JavaScriptProblems.PRIVATE_FUNCTION, NLS.bind(
ValidationMessages.PrivateFunction,
method.getName()), expr.sourceStart(),
expr.sourceEnd());
}
}
}
}
private static boolean isVarOrFunction(IValueReference reference) {
final ReferenceKind kind = reference.getKind();
return kind.isVariable() || kind == ReferenceKind.FUNCTION;
}
@Override
public IValueReference visitIdentifier(Identifier node) {
final IValueReference result = super.visitIdentifier(node);
if (!(node.getParent() instanceof BinaryOperation && ((BinaryOperation) node
.getParent()).isAssignmentTo(node))
&& isVarOrFunction(result)
&& getSource().equals(result.getLocation().getSource())) {
if (result.getAttribute(IReferenceAttributes.ACCESS) == null) {
result.setAttribute(IReferenceAttributes.ACCESS,
Boolean.TRUE);
}
}
final Property property = extractElement(result, Property.class,
null);
if (property != null && property.isDeprecated()) {
reportDeprecatedProperty(property, null, node);
} else {
if (!result.exists()
&& !(node.getParent() instanceof CallExpression && ((CallExpression) node
.getParent()).getExpression() == node)) {
pushExpressionValidator(new NotExistingIdentiferValidator(
peekFunctionScope(), node, result, this));
} else {
testPrivate(node, result);
if (result.exists()
&& node.getParent() instanceof BinaryOperation
&& ((BinaryOperation) node.getParent())
.getOperation() == JSParser.INSTANCEOF
&& ((BinaryOperation) node.getParent())
.getRightExpression() == node) {
checkTypeReference(node,
JavaScriptValidations.typeOf(result),
peekContext());
}
}
}
return result;
}
private static IValueCollection getParentScope(
final IValueCollection collection) {
IValueCollection c = collection;
while (c != null && !c.isScope()) {
c = c.getParent();
}
if (c != null) {
c = c.getParent();
if (c != null) {
return c;
}
}
return null;
}
private final Set<IValueReference> variables = new HashSet<IValueReference>();
@Override
protected IValueReference createVariable(IValueCollection context,
VariableDeclaration declaration) {
validateHidesByVariable(context, declaration);
final IValueReference variable = super.createVariable(context,
declaration);
variables.add(variable);
return variable;
}
private void checkAssign(IValueReference reference, ASTNode node) {
final Object value = reference
.getAttribute(IAssignProtection.ATTRIBUTE);
if (value != null) {
final IAssignProtection assign = value instanceof IAssignProtection ? (IAssignProtection) value
: PROTECT_CONST;
reporter.reportProblem(assign.problemId(),
assign.problemMessage(), node.sourceStart(),
node.sourceEnd());
}
}
@Override
protected void initializeVariable(IValueReference reference,
VariableDeclaration declaration, IVariable variable) {
if (declaration.getInitializer() != null) {
checkAssign(reference, declaration);
}
super.initializeVariable(reference, declaration, variable);
}
private void validateHidesByVariable(IValueCollection context,
VariableDeclaration declaration) {
final IValueReference child;
final Identifier identifier = declaration.getIdentifier();
final IValueCollection parentScope = getParentScope(context);
if (parentScope == null) {
child = context.getChild(identifier.getName());
if (getSource().equals(child.getLocation().getSource())) {
return;
}
} else {
child = parentScope.getChild(identifier.getName());
}
if (child.exists()) {
if (child.getKind() == ReferenceKind.ARGUMENT) {
reporter.reportProblem(
JavaScriptProblems.VAR_HIDES_PARAMETER, NLS.bind(
ValidationMessages.VariableHidesParameter,
declaration.getVariableName()), identifier
.sourceStart(), identifier.sourceEnd());
} else if (child.getKind() == ReferenceKind.FUNCTION) {
reporter.reportProblem(
JavaScriptProblems.VAR_HIDES_FUNCTION, NLS.bind(
ValidationMessages.VariableHidesFunction,
declaration.getVariableName()), identifier
.sourceStart(), identifier.sourceEnd());
} else if (child.getKind() == ReferenceKind.PROPERTY) {
Property property = (Property) child
.getAttribute(IReferenceAttributes.ELEMENT);
if (property != null && property.getDeclaringType() != null) {
reporter.reportProblem(
JavaScriptProblems.VAR_HIDES_PROPERTY,
NLS.bind(
ValidationMessages.VariableHidesPropertyOfType,
declaration.getVariableName(), property
.getDeclaringType().getName()),
identifier.sourceStart(), identifier
.sourceEnd());
} else {
reporter.reportProblem(
JavaScriptProblems.VAR_HIDES_PROPERTY,
NLS.bind(
ValidationMessages.VariableHidesProperty,
declaration.getVariableName()),
identifier.sourceStart(), identifier
.sourceEnd());
}
} else if (child.getKind() == ReferenceKind.METHOD) {
Method method = (Method) child
.getAttribute(IReferenceAttributes.ELEMENT);
if (method != null && method.getDeclaringType() != null) {
reporter.reportProblem(
JavaScriptProblems.VAR_HIDES_METHOD,
NLS.bind(
ValidationMessages.VariableHidesMethodOfType,
declaration.getVariableName(), method
.getDeclaringType().getName()),
identifier.sourceStart(), identifier
.sourceEnd());
} else {
reporter.reportProblem(
JavaScriptProblems.VAR_HIDES_METHOD, NLS.bind(
ValidationMessages.VariableHidesMethod,
declaration.getVariableName()),
identifier.sourceStart(), identifier
.sourceEnd());
}
} else {
reporter.reportProblem(
JavaScriptProblems.DUPLICATE_VAR_DECLARATION,
NLS.bind(ValidationMessages.VariableHidesVariable,
declaration.getVariableName()), identifier
.sourceStart(), identifier.sourceEnd());
}
}
}
protected void validateProperty(final FunctionScope scope,
PropertyExpression propertyExpression, IValueReference result,
boolean exists) {
final Path path = path(propertyExpression, result);
if (scope.contains(path)) {
return;
}
final Expression propName = propertyExpression.getProperty();
final Member member = extractElement(result, Member.class,
JavaScriptValidations.isStatic(result.getParent()));
if (member != null) {
if (member.isDeprecated()) {
final Property parentProperty = extractElement(
result.getParent(), Property.class, null);
if (parentProperty != null
&& parentProperty.getDeclaringType() == null) {
if (member instanceof Property)
reportDeprecatedProperty((Property) member,
parentProperty, propName);
else if (member instanceof Method)
reportDeprecatedMethod(propName, result,
(Method) member);
} else {
if (member instanceof Property)
reportDeprecatedProperty((Property) member,
member.getDeclaringType(), propName);
else if (member instanceof Method)
reportDeprecatedMethod(propName, result,
(Method) member);
}
} else if (!member.isVisible()) {
final Property parentProperty = extractElement(
result.getParent(), Property.class, null);
if (parentProperty != null
&& parentProperty.getDeclaringType() == null) {
if (member instanceof Property)
reportHiddenProperty((Property) member,
parentProperty, propName);
// else if (member instanceof Method)
// reportDeprecatedMethod(propName, result,
// (Method) member);
} else if (member instanceof Property) {
reportHiddenProperty((Property) member,
member.getDeclaringType(), propName);
}
} else if (JavaScriptValidations.isStatic(result.getParent())
&& !member.isStatic()) {
IRType type = JavaScriptValidations.typeOf(result
.getParent());
reporter.reportProblem(
JavaScriptProblems.INSTANCE_PROPERTY,
NLS.bind(
ValidationMessages.StaticReferenceToNoneStaticProperty,
result.getName(), TypeUtil.getName(type)),
propName.sourceStart(), propName.sourceEnd());
} else if (!JavaScriptValidations.isStatic(result.getParent())
&& member.isStatic()) {
IRType type = JavaScriptValidations.typeOf(result
.getParent());
reporter.reportProblem(
JavaScriptProblems.STATIC_PROPERTY,
NLS.bind(
ValidationMessages.ReferenceToStaticProperty,
result.getName(), type.getName()), propName
.sourceStart(), propName.sourceEnd());
}
} else if ((!exists && !result.exists())
&& !isArrayLookup(propertyExpression)) {
scope.add(path);
final IRType type = typeOf(result.getParent());
final TypeKind kind = TypeUtil.kind(type);
if (type != null && kind == TypeKind.JAVA) {
reporter.reportProblem(
JavaScriptProblems.UNDEFINED_JAVA_PROPERTY, NLS
.bind(ValidationMessages.UndefinedProperty,
result.getName(), type.getName()),
propName.sourceStart(), propName.sourceEnd());
} else if (type != null
&& shouldBeDefined(propertyExpression)
&& (kind == TypeKind.JAVASCRIPT || kind == TypeKind.PREDEFINED)) {
reporter.reportProblem(
JavaScriptProblems.UNDEFINED_PROPERTY,
NLS.bind(
ValidationMessages.UndefinedPropertyInScriptType,
result.getName(), type.getName()), propName
.sourceStart(), propName.sourceEnd());
} else if (shouldBeDefined(propertyExpression)) {
final String parentPath = PropertyExpressionUtils
.getPath(propertyExpression.getObject());
reporter.reportProblem(
JavaScriptProblems.UNDEFINED_PROPERTY,
NLS.bind(
ValidationMessages.UndefinedPropertyInScript,
result.getName(),
parentPath != null ? parentPath
: "javascript"), propName
.sourceStart(), propName.sourceEnd());
}
} else {
IRVariable variable = (IRVariable) result
.getAttribute(IReferenceAttributes.R_VARIABLE);
if (variable != null) {
if (variable.isDeprecated()) {
reporter.reportProblem(
JavaScriptProblems.DEPRECATED_VARIABLE,
NLS.bind(ValidationMessages.DeprecatedVariable,
variable.getName()), propName
.sourceStart(), propName.sourceEnd());
}
if (testVisibility(propertyExpression, result, variable)) {
reporter.reportProblem(
JavaScriptProblems.PRIVATE_VARIABLE, NLS.bind(
ValidationMessages.PrivateVariable,
variable.getName()), propName
.sourceStart(), propName.sourceEnd());
}
return;
} else {
IRMethod method = (IRMethod) result.getAttribute(R_METHOD);
if (method != null) {
if (method.isDeprecated()) {
reporter.reportProblem(
JavaScriptProblems.DEPRECATED_FUNCTION,
NLS.bind(
ValidationMessages.DeprecatedFunction,
method.getName()), propName
.sourceStart(), propName
.sourceEnd());
}
if (testVisibility(propertyExpression, result, method)) {
reporter.reportProblem(
JavaScriptProblems.PRIVATE_FUNCTION,
NLS.bind(
ValidationMessages.PrivateFunction,
method.getName()), propName
.sourceStart(), propName
.sourceEnd());
}
return;
}
}
}
}
/**
* @param expression
* @param result
* @param method
* @return
*/
public boolean testVisibility(Expression expression,
IValueReference result, IRMember method) {
return (method.isPrivate() || (method.isProtected()
&& result.getParent() != null && result.getParent()
.getAttribute(IReferenceAttributes.SUPER_SCOPE) == null))
&& (result.getParent() != null || result
.getAttribute(IReferenceAttributes.PRIVATE) == Boolean.TRUE)
&& !isThisCall(expression);
}
private boolean shouldBeDefined(PropertyExpression propertyExpression) {
if (propertyExpression.getParent() instanceof BinaryOperation) {
final BinaryOperation bo = (BinaryOperation) propertyExpression
.getParent();
return bo.getOperation() != JSParser.LAND
&& bo.getOperation() != JSParser.LOR;
}
return true;
}
private void reportDeprecatedProperty(Property property, Element owner,
ASTNode node) {
final String msg;
if (owner instanceof Type) {
msg = NLS.bind(ValidationMessages.DeprecatedProperty,
property.getName(), owner.getName());
} else if (owner instanceof Property) {
msg = NLS.bind(ValidationMessages.DeprecatedPropertyOfInstance,
property.getName(), owner.getName());
} else {
msg = NLS.bind(ValidationMessages.DeprecatedPropertyNoType,
property.getName());
}
reporter.reportProblem(JavaScriptProblems.DEPRECATED_PROPERTY, msg,
node.sourceStart(), node.sourceEnd());
}
private void reportHiddenProperty(Property property, Element owner,
ASTNode node) {
final String msg;
if (owner instanceof Type) {
msg = NLS.bind(ValidationMessages.HiddenProperty,
property.getName(), owner.getName());
} else if (owner instanceof Property) {
msg = NLS.bind(ValidationMessages.HiddenPropertyOfInstance,
property.getName(), owner.getName());
} else {
msg = NLS.bind(ValidationMessages.HiddenPropertyNoType,
property.getName());
}
reporter.reportProblem(JavaScriptProblems.HIDDEN_PROPERTY, msg,
node.sourceStart(), node.sourceEnd());
}
private static boolean isIdentifier(Expression node) {
return node instanceof Identifier || node instanceof CallExpression
&& isIdentifier(((CallExpression) node).getExpression());
}
private static Identifier getIdentifier(Expression node) {
if (node instanceof Identifier) {
return (Identifier) node;
} else if (node instanceof CallExpression) {
return getIdentifier(((CallExpression) node).getExpression());
} else {
return null;
}
}
protected void checkExpressionType(FunctionScope scope,
IValueCollection collection, Expression node,
IValueReference reference) {
if (reference.getParent() == null && isIdentifier(node)
&& !reference.exists()) {
scope.add(path(node, reference));
final Identifier identifier = getIdentifier(node);
reportUnknownType(JavaScriptProblems.UNDECLARED_VARIABLE,
identifier != null ? identifier : node,
identifier != null ? identifier.getName() : "?");
return;
}
JSTypeSet types = reference.getTypes();
if (types.size() > 0) {
checkTypeReference(node, types.getFirst(), collection);
} else if (reference.getDeclaredType() != null) {
checkTypeReference(node, reference.getDeclaredType(),
collection);
} else {
final String lazyName = ValueReferenceUtil
.getLazyName(reference);
if (lazyName != null) {
reportUnknownType(JavaScriptProblems.WRONG_TYPE_EXPRESSION,
ValidationMessages.UndefinedJavascriptType, node,
lazyName);
}
}
}
/**
* @param node
* @param type
*/
protected void checkTypeReference(ASTNode node, IRType type,
IValueCollection collection) {
if (type == null) {
return;
}
if (type instanceof IRSimpleType) {
final Type t = ((IRSimpleType) type).getTarget();
if (t.getKind() != TypeKind.UNKNOWN) {
if (t.isDeprecated()) {
reporter.reportProblem(
JavaScriptProblems.DEPRECATED_TYPE, NLS.bind(
ValidationMessages.DeprecatedType,
TypeUtil.getName(type)), node
.sourceStart(), node.sourceEnd());
}
}
} else if (type instanceof IRClassType) {
final Type t = ((IRClassType) type).getTarget();
if (t != null && t.getKind() != TypeKind.UNKNOWN) {
if (t.isDeprecated()) {
reporter.reportProblem(
JavaScriptProblems.DEPRECATED_TYPE, NLS.bind(
ValidationMessages.DeprecatedType,
TypeUtil.getName(type)), node
.sourceStart(), node.sourceEnd());
}
}
}
}
public void reportUnknownType(IProblemIdentifier identifier,
String message, ASTNode node, String name) {
reporter.reportProblem(identifier, NLS.bind(message, name),
node.sourceStart(), node.sourceEnd());
}
public void reportUnknownType(IProblemIdentifier identifier,
ASTNode node, String name) {
reportUnknownType(identifier, ValidationMessages.UnknownType, node,
name);
}
private boolean stronglyTyped(IValueReference reference) {
final IRType parentType = typeOf(reference.getParent());
if (parentType != null) {
if (parentType instanceof IRRecordType) {
return true;
}
return TypeUtil.kind(parentType) == TypeKind.JAVA;
}
return false;
}
@Override
public IValueReference visitIfStatement(IfStatement node) {
final IValueReference condition = visit(node.getCondition());
if (condition != null && !condition.exists()
&& node.getCondition() instanceof PropertyExpression
&& !stronglyTyped(condition)) {
if (DEBUG) {
System.out.println("visitIfStatement("
+ node.getCondition() + ") doesn't exist "
+ condition + " - create it");
}
condition.setValue(PhantomValueReference.REFERENCE);
}
visitIfStatements(node);
return null;
}
}
static final boolean DEBUG = false;
}
| false | true | protected void validateCallExpression(FunctionScope scope,
CallExpression node, final IValueReference reference,
IValueReference[] arguments, List<Method> methods) {
final Expression expression = node.getExpression();
final Path path = path(expression, reference);
if (scope.contains(path)) {
return;
}
final Expression methodNode;
if (expression instanceof PropertyExpression) {
methodNode = ((PropertyExpression) expression).getProperty();
} else {
methodNode = expression;
}
if (methods == null || methods.size() == 0)
methods = JavaScriptValidations.extractElements(reference,
Method.class);
if (methods != null) {
Method method = JavaScriptValidations.selectMethod(
getContext(), methods, arguments);
if (method == null) {
final IRType type = JavaScriptValidations.typeOf(reference
.getParent());
if (type != null) {
if (TypeUtil.kind(type) == TypeKind.JAVA) {
reporter.reportProblem(
JavaScriptProblems.WRONG_JAVA_PARAMETERS,
NLS.bind(
ValidationMessages.MethodNotSelected,
new String[] { reference.getName(),
type.getName(),
describeArgTypes(arguments) }),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else {
// TODO also a JS error (that should be
// configurable)
}
}
return;
}
if (method.isDeprecated()) {
reportDeprecatedMethod(methodNode, reference, method);
}
if (!validateParameterCount(method, node.getArguments())) {
reportMethodParameterError(methodNode, arguments, method);
return;
}
if (JavaScriptValidations.isStatic(reference.getParent())
&& !method.isStatic()) {
IRType type = JavaScriptValidations.typeOf(reference
.getParent());
reporter.reportProblem(
JavaScriptProblems.INSTANCE_METHOD,
NLS.bind(
ValidationMessages.StaticReferenceToNoneStaticMethod,
reference.getName(), TypeUtil.getName(type)),
methodNode.sourceStart(), methodNode.sourceEnd());
} else if (reference.getParent() != null
&& !JavaScriptValidations.isStatic(reference
.getParent()) && method.isStatic()) {
IRType type = JavaScriptValidations.typeOf(reference
.getParent());
reporter.reportProblem(JavaScriptProblems.STATIC_METHOD,
NLS.bind(
ValidationMessages.ReferenceToStaticMethod,
reference.getName(), type.getName()),
methodNode.sourceStart(), methodNode.sourceEnd());
}
final List<IRParameter> parameters = RModelBuilder.convert(
getContext(), method.getParameters());
final TypeCompatibility compatibility = validateParameters(
parameters, arguments);
if (compatibility != TypeCompatibility.TRUE) {
String name = method.getName();
if (name == null) {
Identifier identifier = PropertyExpressionUtils
.getIdentifier(methodNode);
if (identifier != null)
name = identifier.getName();
}
reporter.reportProblem(
compatibility == TypeCompatibility.FALSE ? JavaScriptProblems.WRONG_PARAMETERS
: JavaScriptProblems.WRONG_PARAMETERS_PARAMETERIZATION,
NLS.bind(
ValidationMessages.MethodNotApplicableInScript,
new String[] {
name,
describeParamTypes(parameters),
describeArgTypes(arguments,
parameters) }), methodNode
.sourceStart(), methodNode.sourceEnd());
}
} else {
Object attribute = reference.getAttribute(R_METHOD, true);
if (attribute instanceof IRMethod) {
IRMethod method = (IRMethod) attribute;
if (method.isDeprecated()) {
reporter.reportProblem(
JavaScriptProblems.DEPRECATED_FUNCTION,
NLS.bind(ValidationMessages.DeprecatedFunction,
reference.getName()), methodNode
.sourceStart(), methodNode.sourceEnd());
}
if (testVisibility(expression, reference, method)) {
reporter.reportProblem(
JavaScriptProblems.PRIVATE_FUNCTION, NLS.bind(
ValidationMessages.PrivateFunction,
reference.getName()), methodNode
.sourceStart(), methodNode.sourceEnd());
}
List<IRParameter> parameters = method.getParameters();
final TypeCompatibility compatibility = validateParameters(
parameters, arguments);
if (compatibility != TypeCompatibility.TRUE) {
String name = method.getName();
if (name == null) {
Identifier identifier = PropertyExpressionUtils
.getIdentifier(methodNode);
if (identifier != null)
name = identifier.getName();
}
final IProblemIdentifier problemId;
if (method.isTyped()) {
if (compatibility == TypeCompatibility.FALSE) {
problemId = JavaScriptProblems.WRONG_PARAMETERS;
} else {
problemId = JavaScriptProblems.WRONG_PARAMETERS_PARAMETERIZATION;
}
} else {
problemId = JavaScriptProblems.WRONG_PARAMETERS_UNTYPED;
}
reporter.reportProblem(
problemId,
NLS.bind(
ValidationMessages.MethodNotApplicableInScript,
new String[] {
name,
describeParamTypes(parameters),
describeArgTypes(arguments,
parameters) }),
methodNode.sourceStart(), methodNode
.sourceEnd());
}
} else if (!isArrayLookup(expression)
&& !isUntypedParameter(reference)) {
scope.add(path);
final IRType type = JavaScriptValidations.typeOf(reference
.getParent());
if (type != null) {
if (TypeUtil.kind(type) == TypeKind.JAVA) {
reporter.reportProblem(
JavaScriptProblems.UNDEFINED_JAVA_METHOD,
NLS.bind(
ValidationMessages.UndefinedMethod,
reference.getName(), type.getName()),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else if (JavaScriptValidations.isStatic(reference
.getParent())
&& hasInstanceMethod(type, reference.getName())) {
reporter.reportProblem(
JavaScriptProblems.INSTANCE_METHOD,
NLS.bind(
ValidationMessages.StaticReferenceToNoneStaticMethod,
reference.getName(), type.getName()),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else if (!reference.exists()) {
if (reference.getParent() == null
&& isIdentifier(expression)
&& !reference.exists()) {
reporter.reportProblem(
JavaScriptProblems.UNDEFINED_METHOD,
NLS.bind(
ValidationMessages.UndefinedMethodInScript,
reference.getName()),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else {
reporter.reportProblem(
JavaScriptProblems.UNDEFINED_METHOD_IN_SCRIPT,
NLS.bind(
ValidationMessages.UndefinedMethodOnObject,
reference.getName(), reference
.getParent().getName()),
methodNode.sourceStart(), methodNode
.sourceEnd());
}
}
} else {
IRType referenceType = JavaScriptValidations
.typeOf(reference);
if (functionTypeRef.isAssignableFrom(referenceType) == TypeCompatibility.TRUE) {
return;
}
if (expression instanceof NewExpression) {
if (reference.getKind() == ReferenceKind.TYPE) {
return;
}
IRType newType = JavaScriptValidations
.typeOf(reference);
if (newType != null) {
return;
}
}
IValueReference parent = reference;
while (parent != null) {
if (parent.getName() == IValueReference.ARRAY_OP) {
// ignore array lookup function calls
// like: array[1](),
// those are dynamic.
return;
}
parent = parent.getParent();
}
if (expression instanceof NewExpression) {
reporter.reportProblem(
JavaScriptProblems.WRONG_TYPE_EXPRESSION,
NLS.bind(
ValidationMessages.UndefinedJavascriptType,
((NewExpression) expression)
.getObjectClass()
.toSourceString("")),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else {
if (reference.getParent() == null
&& isIdentifier(expression)
&& !reference.exists()) {
reporter.reportProblem(
JavaScriptProblems.UNDEFINED_METHOD,
NLS.bind(
ValidationMessages.UndefinedMethodInScript,
reference.getName()),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else {
reporter.reportProblem(
JavaScriptProblems.UNDEFINED_METHOD_IN_SCRIPT,
NLS.bind(
ValidationMessages.UndefinedMethodOnObject,
reference.getName(), reference
.getParent().getName()),
methodNode
.sourceStart(), methodNode
.sourceEnd());
}
}
}
}
}
return;
}
| protected void validateCallExpression(FunctionScope scope,
CallExpression node, final IValueReference reference,
IValueReference[] arguments, List<Method> methods) {
final Expression expression = node.getExpression();
final Path path = path(expression, reference);
if (scope.contains(path)) {
return;
}
final Expression methodNode;
if (expression instanceof PropertyExpression) {
methodNode = ((PropertyExpression) expression).getProperty();
} else {
methodNode = expression;
}
if (methods == null || methods.size() == 0)
methods = JavaScriptValidations.extractElements(reference,
Method.class);
if (methods != null) {
Method method = JavaScriptValidations.selectMethod(
getContext(), methods, arguments);
if (method == null) {
final IRType type = JavaScriptValidations.typeOf(reference
.getParent());
if (type != null) {
if (TypeUtil.kind(type) == TypeKind.JAVA) {
reporter.reportProblem(
JavaScriptProblems.WRONG_JAVA_PARAMETERS,
NLS.bind(
ValidationMessages.MethodNotSelected,
new String[] { reference.getName(),
type.getName(),
describeArgTypes(arguments) }),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else {
// TODO also a JS error (that should be
// configurable)
}
}
return;
}
if (method.isDeprecated()) {
reportDeprecatedMethod(methodNode, reference, method);
}
if (!validateParameterCount(method, node.getArguments())) {
reportMethodParameterError(methodNode, arguments, method);
return;
}
if (JavaScriptValidations.isStatic(reference.getParent())
&& !method.isStatic()) {
IRType type = JavaScriptValidations.typeOf(reference
.getParent());
reporter.reportProblem(
JavaScriptProblems.INSTANCE_METHOD,
NLS.bind(
ValidationMessages.StaticReferenceToNoneStaticMethod,
reference.getName(), TypeUtil.getName(type)),
methodNode.sourceStart(), methodNode.sourceEnd());
} else if (reference.getParent() != null
&& !JavaScriptValidations.isStatic(reference
.getParent()) && method.isStatic()) {
IRType type = JavaScriptValidations.typeOf(reference
.getParent());
reporter.reportProblem(JavaScriptProblems.STATIC_METHOD,
NLS.bind(
ValidationMessages.ReferenceToStaticMethod,
reference.getName(), type.getName()),
methodNode.sourceStart(), methodNode.sourceEnd());
}
final List<IRParameter> parameters = RModelBuilder.convert(
getContext(), method.getParameters());
final TypeCompatibility compatibility = validateParameters(
parameters, arguments);
if (compatibility != TypeCompatibility.TRUE) {
String name = method.getName();
if (name == null) {
Identifier identifier = PropertyExpressionUtils
.getIdentifier(methodNode);
if (identifier != null)
name = identifier.getName();
}
reporter.reportProblem(
compatibility == TypeCompatibility.FALSE ? JavaScriptProblems.WRONG_PARAMETERS
: JavaScriptProblems.WRONG_PARAMETERS_PARAMETERIZATION,
NLS.bind(
ValidationMessages.MethodNotApplicableInScript,
new String[] {
name,
describeParamTypes(parameters),
describeArgTypes(arguments,
parameters) }), methodNode
.sourceStart(), methodNode.sourceEnd());
}
} else {
Object attribute = reference.getAttribute(R_METHOD, true);
if (attribute instanceof IRMethod) {
IRMethod method = (IRMethod) attribute;
if (method.isDeprecated()) {
reporter.reportProblem(
JavaScriptProblems.DEPRECATED_FUNCTION,
NLS.bind(ValidationMessages.DeprecatedFunction,
reference.getName()), methodNode
.sourceStart(), methodNode.sourceEnd());
}
if (testVisibility(expression, reference, method)) {
reporter.reportProblem(
JavaScriptProblems.PRIVATE_FUNCTION, NLS.bind(
ValidationMessages.PrivateFunction,
reference.getName()), methodNode
.sourceStart(), methodNode.sourceEnd());
}
List<IRParameter> parameters = method.getParameters();
final TypeCompatibility compatibility = validateParameters(
parameters, arguments);
if (compatibility != TypeCompatibility.TRUE) {
String name = method.getName();
if (name == null) {
Identifier identifier = PropertyExpressionUtils
.getIdentifier(methodNode);
if (identifier != null)
name = identifier.getName();
}
final IProblemIdentifier problemId;
if (method.isTyped()) {
if (compatibility == TypeCompatibility.FALSE) {
problemId = JavaScriptProblems.WRONG_PARAMETERS;
} else {
problemId = JavaScriptProblems.WRONG_PARAMETERS_PARAMETERIZATION;
}
} else {
problemId = JavaScriptProblems.WRONG_PARAMETERS_UNTYPED;
}
reporter.reportProblem(
problemId,
NLS.bind(
ValidationMessages.MethodNotApplicableInScript,
new String[] {
name,
describeParamTypes(parameters),
describeArgTypes(arguments,
parameters) }),
methodNode.sourceStart(), methodNode
.sourceEnd());
}
} else if (!isArrayLookup(expression)
&& !isUntypedParameter(reference)) {
scope.add(path);
final IRType type = JavaScriptValidations.typeOf(reference
.getParent());
if (type != null) {
if (TypeUtil.kind(type) == TypeKind.JAVA) {
reporter.reportProblem(
JavaScriptProblems.UNDEFINED_JAVA_METHOD,
NLS.bind(
ValidationMessages.UndefinedMethod,
reference.getName(), type.getName()),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else if (JavaScriptValidations.isStatic(reference
.getParent())
&& hasInstanceMethod(type, reference.getName())) {
reporter.reportProblem(
JavaScriptProblems.INSTANCE_METHOD,
NLS.bind(
ValidationMessages.StaticReferenceToNoneStaticMethod,
reference.getName(), type.getName()),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else if (!reference.exists()) {
if (reference.getParent() == null
&& isIdentifier(expression)
&& !reference.exists()) {
reporter.reportProblem(
JavaScriptProblems.UNDEFINED_METHOD_IN_SCRIPT,
NLS.bind(
ValidationMessages.UndefinedMethodInScript,
reference.getName()),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else {
reporter.reportProblem(
JavaScriptProblems.UNDEFINED_METHOD,
NLS.bind(
ValidationMessages.UndefinedMethodOnObject,
reference.getName(), reference
.getParent().getName()),
methodNode.sourceStart(), methodNode
.sourceEnd());
}
}
} else {
IRType referenceType = JavaScriptValidations
.typeOf(reference);
if (functionTypeRef.isAssignableFrom(referenceType) == TypeCompatibility.TRUE) {
return;
}
if (expression instanceof NewExpression) {
if (reference.getKind() == ReferenceKind.TYPE) {
return;
}
IRType newType = JavaScriptValidations
.typeOf(reference);
if (newType != null) {
return;
}
}
IValueReference parent = reference;
while (parent != null) {
if (parent.getName() == IValueReference.ARRAY_OP) {
// ignore array lookup function calls
// like: array[1](),
// those are dynamic.
return;
}
parent = parent.getParent();
}
if (expression instanceof NewExpression) {
reporter.reportProblem(
JavaScriptProblems.WRONG_TYPE_EXPRESSION,
NLS.bind(
ValidationMessages.UndefinedJavascriptType,
((NewExpression) expression)
.getObjectClass()
.toSourceString("")),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else {
if (reference.getParent() == null
&& isIdentifier(expression)
&& !reference.exists()) {
reporter.reportProblem(
JavaScriptProblems.UNDEFINED_METHOD_IN_SCRIPT,
NLS.bind(
ValidationMessages.UndefinedMethodInScript,
reference.getName()),
methodNode.sourceStart(), methodNode
.sourceEnd());
} else {
reporter.reportProblem(
JavaScriptProblems.UNDEFINED_METHOD,
NLS.bind(
ValidationMessages.UndefinedMethodOnObject,
reference.getName(), reference
.getParent().getName()),
methodNode
.sourceStart(), methodNode
.sourceEnd());
}
}
}
}
}
return;
}
|
diff --git a/src/edu/fit/cs/sno/snes/cpu/hwregs/DMAChannel.java b/src/edu/fit/cs/sno/snes/cpu/hwregs/DMAChannel.java
index 5fcb0fa..cc1eb62 100644
--- a/src/edu/fit/cs/sno/snes/cpu/hwregs/DMAChannel.java
+++ b/src/edu/fit/cs/sno/snes/cpu/hwregs/DMAChannel.java
@@ -1,215 +1,216 @@
package edu.fit.cs.sno.snes.cpu.hwregs;
import edu.fit.cs.sno.snes.Core;
import edu.fit.cs.sno.snes.common.Size;
import edu.fit.cs.sno.snes.cpu.Timing;
import edu.fit.cs.sno.util.Log;
import edu.fit.cs.sno.util.Util;
public class DMAChannel {
boolean hdmaEnabled;
boolean doTransfer = false; // Custom variable for whether hdma is enabled for this or not
boolean direction = true; // True = Read PPU, false = Write PPU
boolean addressMode = true; // HDMA only(true=indirect, false=direct)
boolean addressIncrement = true; // True=decrement, False=increment
boolean fixedTransfer = true; // Do we allow addressIncrement to have an effect?
int transferMode = 0x7; // TransferMode
int srcAddress = 0xFFFF;
int srcBank = 0xFF;
int dstRegister = 0x21FF;
int indirectBank = 0xFF;
int transferSize = 0xFFFF; // Also known as indirect address
// Updated at the beginning of a frame(copied from 42x2/3)
int tableAddr = 0xFFFF;
int rlc = 0xFF; // repeat/line counter
boolean frameDisabled=true;//is hdma disabled for this frame?
private boolean isRepeat() {
return (rlc & 0x80) == 0x80;
}
private int getLineCounter() {
return rlc & 0x7F;
}
public void start() {
if (transferSize == 0x0000) {
transferSize = 0x10000;
}
int cycleCount = transferSize *8 + 24; // 8 cyles per byte + 24overhead
if (direction == false) dmaWritePPU();
else dmaReadPPU();
Timing.cycle(cycleCount);
};
/**
* Happens every frame(on scanline 0)
*/
public void initHDMA() {
if (!hdmaEnabled) return;
// Copy AAddress into TableAddress
// Load repeat/line counter from table
// load indirect address
// set enable transfer
tableAddr = srcAddress;
rlc = Core.mem.get(Size.BYTE, srcBank, tableAddr);
tableAddr++;
if (rlc==0) {
frameDisabled = true;
doTransfer = false;
return;
}
if (addressMode == true) { // Indirect
transferSize = Core.mem.get(Size.SHORT, srcBank, tableAddr);
tableAddr += 2;
}
frameDisabled = false;
doTransfer = true;
}
public void doHDMA() {
if (frameDisabled || !hdmaEnabled) return;
if (doTransfer) {
if (direction == false) hdmaWritePPU();
else hdmaReadPPU();
}
rlc = Util.limit(Size.BYTE, rlc-1);
doTransfer = isRepeat();
if (getLineCounter() == 0) {
rlc = Core.mem.get(Size.BYTE, srcBank, tableAddr);
tableAddr++;
if (addressMode == true) { // Indirect
transferSize = Core.mem.get(Size.SHORT, srcBank, tableAddr);
tableAddr += 2;
}
// Handle special case if rlc == 0(rlc is $43xA)
// SEE: http://wiki.superfamicom.org/snes/show/DMA+%26+HDMA
if (rlc == 0) {
frameDisabled = true;
}
doTransfer = true;
}
}
private void hdmaReadPPU() {
System.out.println("HDMA Read: Not implemented");
}
private void dmaReadPPU() {
while(transferSize>0) {
int size = dmaTransferPPUOnce(0, dstRegister, srcBank, srcAddress);
adjustSrcAddress(size);
transferSize -= size;
}
}
private void hdmaWritePPU() {
if (addressMode) { // Indirect address
int size = dmaTransferPPUOnce(indirectBank, transferSize, 0, dstRegister);
transferSize += size;
} else {
int size = dmaTransferPPUOnce(srcBank, tableAddr, 0, dstRegister);
tableAddr += size;
}
}
private void dmaWritePPU() {
while(transferSize>0) {
int size = dmaTransferPPUOnce(srcBank, srcAddress, 0, dstRegister);
adjustSrcAddress(size);
transferSize -= size;
}
}
private int dmaTransferPPUOnce(int fromBank, int fromAddress, int toBank, int toAddress) {
// TODO: for normal dma transfers, only write to at most $transferSize registers, even if we are supposed to write to multiple ones this call
// TODO: i.e. break out of the statement if transfersize == 0 at any point
int size = 0;
int tmp = 0;
if (transferMode == 0x0) { // 1 register, write once(1byte)
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
size = 1;
} else if (transferMode == 0x01) { // 2 Register write once(2bytes)
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+0);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
- tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
+ // Don't fetch the next byte if it is a fixed transfer
+ if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
Core.mem.set(Size.BYTE, toBank, toAddress+1, tmp);
size = 2;
} else if (transferMode == 0x02 || transferMode == 0x06) { // 1 Register Write Twice(2bytes)
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+0);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
- tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
+ if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
size = 2;
} else if (transferMode == 0x03 || transferMode == 0x07) { // 2 Register Write Twice(4bytes)
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+0);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
- tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
+ if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
- tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+2);
+ if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+2);
Core.mem.set(Size.BYTE, toBank, toAddress+1, tmp);
- tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+3);
+ if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+3);
Core.mem.set(Size.BYTE, toBank, toAddress+1, tmp);
size = 4;
} else if (transferMode == 0x04) { // 4 Registers Write once(4bytes)
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+0);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
- tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
+ if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
Core.mem.set(Size.BYTE, toBank, toAddress+1, tmp);
- tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+2);
+ if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+2);
Core.mem.set(Size.BYTE, toBank, toAddress+2, tmp);
- tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+3);
+ if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+3);
Core.mem.set(Size.BYTE, toBank, toAddress+3, tmp);
size = 4;
} else {
System.out.println("Unknown transfer mode");
return 0;
}
return size;
}
private void adjustSrcAddress(int size) {
if (!fixedTransfer) {
if (addressIncrement) // Decrease srcAddress
srcAddress-=size;
else
srcAddress+=size; // Increase srcAddress
}
}
@Override
public String toString() {
String r = "DMA Settings: \n";
r += " Direction: " + (direction?"Read PPU":"Write PPU") + "\n";
r += " HDMA Address Mode: " + (addressMode?"table=pointer":"table=data") + "\n";
r += " Address Increment: " + (addressIncrement?"Decrement":"Increment") + "\n";
r += " Fixed Transfer: " + fixedTransfer + "\n";
r += " Transfer Mode: 0b" + Integer.toBinaryString(transferMode)+"\n";
r += String.format(" Source Address: %02X:%04X\n",srcBank, srcAddress);
r += String.format(" Destination Reg: %04X\n", dstRegister);
r += String.format(" Size/IndirectAddr: %04X\n", transferSize);
r += String.format(" Indirect Bank: %02X\n", indirectBank);
return r;
}
}
| false | true | private int dmaTransferPPUOnce(int fromBank, int fromAddress, int toBank, int toAddress) {
// TODO: for normal dma transfers, only write to at most $transferSize registers, even if we are supposed to write to multiple ones this call
// TODO: i.e. break out of the statement if transfersize == 0 at any point
int size = 0;
int tmp = 0;
if (transferMode == 0x0) { // 1 register, write once(1byte)
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
size = 1;
} else if (transferMode == 0x01) { // 2 Register write once(2bytes)
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+0);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
Core.mem.set(Size.BYTE, toBank, toAddress+1, tmp);
size = 2;
} else if (transferMode == 0x02 || transferMode == 0x06) { // 1 Register Write Twice(2bytes)
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+0);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
size = 2;
} else if (transferMode == 0x03 || transferMode == 0x07) { // 2 Register Write Twice(4bytes)
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+0);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+2);
Core.mem.set(Size.BYTE, toBank, toAddress+1, tmp);
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+3);
Core.mem.set(Size.BYTE, toBank, toAddress+1, tmp);
size = 4;
} else if (transferMode == 0x04) { // 4 Registers Write once(4bytes)
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+0);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
Core.mem.set(Size.BYTE, toBank, toAddress+1, tmp);
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+2);
Core.mem.set(Size.BYTE, toBank, toAddress+2, tmp);
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+3);
Core.mem.set(Size.BYTE, toBank, toAddress+3, tmp);
size = 4;
} else {
System.out.println("Unknown transfer mode");
return 0;
}
return size;
}
| private int dmaTransferPPUOnce(int fromBank, int fromAddress, int toBank, int toAddress) {
// TODO: for normal dma transfers, only write to at most $transferSize registers, even if we are supposed to write to multiple ones this call
// TODO: i.e. break out of the statement if transfersize == 0 at any point
int size = 0;
int tmp = 0;
if (transferMode == 0x0) { // 1 register, write once(1byte)
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
size = 1;
} else if (transferMode == 0x01) { // 2 Register write once(2bytes)
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+0);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
// Don't fetch the next byte if it is a fixed transfer
if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
Core.mem.set(Size.BYTE, toBank, toAddress+1, tmp);
size = 2;
} else if (transferMode == 0x02 || transferMode == 0x06) { // 1 Register Write Twice(2bytes)
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+0);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
size = 2;
} else if (transferMode == 0x03 || transferMode == 0x07) { // 2 Register Write Twice(4bytes)
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+0);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+2);
Core.mem.set(Size.BYTE, toBank, toAddress+1, tmp);
if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+3);
Core.mem.set(Size.BYTE, toBank, toAddress+1, tmp);
size = 4;
} else if (transferMode == 0x04) { // 4 Registers Write once(4bytes)
tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+0);
Core.mem.set(Size.BYTE, toBank, toAddress, tmp);
if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+1);
Core.mem.set(Size.BYTE, toBank, toAddress+1, tmp);
if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+2);
Core.mem.set(Size.BYTE, toBank, toAddress+2, tmp);
if (!fixedTransfer) tmp = Core.mem.get(Size.BYTE, fromBank, fromAddress+3);
Core.mem.set(Size.BYTE, toBank, toAddress+3, tmp);
size = 4;
} else {
System.out.println("Unknown transfer mode");
return 0;
}
return size;
}
|
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/datehistogram/DateHistogramFacetProcessor.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/datehistogram/DateHistogramFacetProcessor.java
index 50da9ea96e4..7f4f5473ba1 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/datehistogram/DateHistogramFacetProcessor.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/datehistogram/DateHistogramFacetProcessor.java
@@ -1,248 +1,248 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.facet.datehistogram;
import org.elasticsearch.common.collect.ImmutableMap;
import org.elasticsearch.common.collect.MapBuilder;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.joda.time.Chronology;
import org.elasticsearch.common.joda.time.DateTimeField;
import org.elasticsearch.common.joda.time.DateTimeZone;
import org.elasticsearch.common.joda.time.MutableDateTime;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.trove.impl.Constants;
import org.elasticsearch.common.trove.map.hash.TObjectIntHashMap;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.field.data.FieldDataType;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.search.facet.Facet;
import org.elasticsearch.search.facet.FacetCollector;
import org.elasticsearch.search.facet.FacetPhaseExecutionException;
import org.elasticsearch.search.facet.FacetProcessor;
import org.elasticsearch.search.internal.SearchContext;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* @author kimchy (shay.banon)
*/
public class DateHistogramFacetProcessor extends AbstractComponent implements FacetProcessor {
private final ImmutableMap<String, DateFieldParser> dateFieldParsers;
private final TObjectIntHashMap<String> rounding = new TObjectIntHashMap<String>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, -1);
@Inject public DateHistogramFacetProcessor(Settings settings) {
super(settings);
InternalDateHistogramFacet.registerStreams();
dateFieldParsers = MapBuilder.<String, DateFieldParser>newMapBuilder()
.put("year", new DateFieldParser.YearOfCentury())
.put("1y", new DateFieldParser.YearOfCentury())
.put("month", new DateFieldParser.MonthOfYear())
.put("1m", new DateFieldParser.MonthOfYear())
.put("day", new DateFieldParser.DayOfMonth())
.put("1d", new DateFieldParser.DayOfMonth())
.put("hour", new DateFieldParser.HourOfDay())
.put("1h", new DateFieldParser.HourOfDay())
.put("minute", new DateFieldParser.MinuteOfHour())
.put("1m", new DateFieldParser.MinuteOfHour())
.put("second", new DateFieldParser.SecondOfMinute())
.put("1s", new DateFieldParser.SecondOfMinute())
.immutableMap();
rounding.put("floor", MutableDateTime.ROUND_FLOOR);
rounding.put("ceiling", MutableDateTime.ROUND_CEILING);
rounding.put("half_even", MutableDateTime.ROUND_HALF_EVEN);
rounding.put("halfEven", MutableDateTime.ROUND_HALF_EVEN);
rounding.put("half_floor", MutableDateTime.ROUND_HALF_FLOOR);
rounding.put("halfFloor", MutableDateTime.ROUND_HALF_FLOOR);
rounding.put("half_ceiling", MutableDateTime.ROUND_HALF_CEILING);
rounding.put("halfCeiling", MutableDateTime.ROUND_HALF_CEILING);
}
@Override public String[] types() {
return new String[]{DateHistogramFacet.TYPE, "dateHistogram"};
}
@Override public FacetCollector parse(String facetName, XContentParser parser, SearchContext context) throws IOException {
String keyField = null;
String valueField = null;
String valueScript = null;
String scriptLang = null;
Map<String, Object> params = null;
boolean intervalSet = false;
long interval = 1;
String sInterval = null;
MutableDateTime dateTime = new MutableDateTime(DateTimeZone.UTC);
DateHistogramFacet.ComparatorType comparatorType = DateHistogramFacet.ComparatorType.TIME;
XContentParser.Token token;
String fieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
fieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("params".equals(fieldName)) {
params = parser.map();
}
} else if (token.isValue()) {
if ("field".equals(fieldName)) {
keyField = parser.text();
} else if ("key_field".equals(fieldName) || "keyField".equals(fieldName)) {
keyField = parser.text();
} else if ("value_field".equals(fieldName) || "valueField".equals(fieldName)) {
valueField = parser.text();
} else if ("interval".equals(fieldName)) {
intervalSet = true;
if (token == XContentParser.Token.VALUE_NUMBER) {
interval = parser.longValue();
} else {
sInterval = parser.text();
}
} else if ("time_zone".equals(fieldName) || "timeZone".equals(fieldName)) {
if (token == XContentParser.Token.VALUE_NUMBER) {
dateTime.setZone(DateTimeZone.forOffsetHours(parser.intValue()));
} else {
String text = parser.text();
int index = text.indexOf(':');
if (index != -1) {
// format like -02:30
dateTime.setZone(DateTimeZone.forOffsetHoursMinutes(
Integer.parseInt(text.substring(0, index)),
Integer.parseInt(text.substring(index + 1))
));
} else {
// id, listed here: http://joda-time.sourceforge.net/timezones.html
dateTime.setZone(DateTimeZone.forID(text));
}
}
} else if ("value_script".equals(fieldName) || "valueScript".equals(fieldName)) {
valueScript = parser.text();
} else if ("order".equals(fieldName) || "comparator".equals(fieldName)) {
comparatorType = DateHistogramFacet.ComparatorType.fromString(parser.text());
} else if ("lang".equals(fieldName)) {
scriptLang = parser.text();
}
}
}
if (keyField == null) {
throw new FacetPhaseExecutionException(facetName, "key field is required to be set for histogram facet, either using [field] or using [key_field]");
}
FieldMapper mapper = context.mapperService().smartNameFieldMapper(keyField);
if (mapper.fieldDataType() != FieldDataType.DefaultTypes.LONG) {
throw new FacetPhaseExecutionException(facetName, "(key) field [" + keyField + "] is not of type date");
}
if (!intervalSet) {
throw new FacetPhaseExecutionException(facetName, "[interval] is required to be set for histogram facet");
}
// we set the rounding after we set the zone, for it to take affect
if (sInterval != null) {
int index = sInterval.indexOf(':');
if (index != -1) {
// set with rounding
DateFieldParser fieldParser = dateFieldParsers.get(sInterval.substring(0, index));
if (fieldParser == null) {
throw new FacetPhaseExecutionException(facetName, "failed to parse interval [" + sInterval + "] with custom rounding using built in intervals (year/month/...)");
}
DateTimeField field = fieldParser.parse(dateTime.getChronology());
int rounding = this.rounding.get(sInterval.substring(index + 1));
if (rounding == -1) {
throw new FacetPhaseExecutionException(facetName, "failed to parse interval [" + sInterval + "], rounding type [" + (sInterval.substring(index + 1)) + "] not found");
}
dateTime.setRounding(field, rounding);
} else {
DateFieldParser fieldParser = dateFieldParsers.get(sInterval);
if (fieldParser != null) {
DateTimeField field = fieldParser.parse(dateTime.getChronology());
dateTime.setRounding(field, MutableDateTime.ROUND_FLOOR);
} else {
// time interval
try {
- interval = TimeValue.parseTimeValue(parser.text(), null).millis();
+ interval = TimeValue.parseTimeValue(sInterval, null).millis();
} catch (Exception e) {
throw new FacetPhaseExecutionException(facetName, "failed to parse interval [" + sInterval + "], tried both as built in intervals (year/month/...) and as a time format");
}
}
}
}
if (valueScript != null) {
return new ValueScriptDateHistogramFacetCollector(facetName, keyField, scriptLang, valueScript, params, dateTime, interval, comparatorType, context);
} else if (valueField == null) {
return new CountDateHistogramFacetCollector(facetName, keyField, dateTime, interval, comparatorType, context);
} else {
return new ValueDateHistogramFacetCollector(facetName, keyField, valueField, dateTime, interval, comparatorType, context);
}
}
@Override public Facet reduce(String name, List<Facet> facets) {
InternalDateHistogramFacet first = (InternalDateHistogramFacet) facets.get(0);
return first.reduce(name, facets);
}
static interface DateFieldParser {
DateTimeField parse(Chronology chronology);
static class YearOfCentury implements DateFieldParser {
@Override public DateTimeField parse(Chronology chronology) {
return chronology.yearOfCentury();
}
}
static class MonthOfYear implements DateFieldParser {
@Override public DateTimeField parse(Chronology chronology) {
return chronology.monthOfYear();
}
}
static class DayOfMonth implements DateFieldParser {
@Override public DateTimeField parse(Chronology chronology) {
return chronology.dayOfMonth();
}
}
static class HourOfDay implements DateFieldParser {
@Override public DateTimeField parse(Chronology chronology) {
return chronology.hourOfDay();
}
}
static class MinuteOfHour implements DateFieldParser {
@Override public DateTimeField parse(Chronology chronology) {
return chronology.minuteOfHour();
}
}
static class SecondOfMinute implements DateFieldParser {
@Override public DateTimeField parse(Chronology chronology) {
return chronology.secondOfMinute();
}
}
}
}
| true | true | @Override public FacetCollector parse(String facetName, XContentParser parser, SearchContext context) throws IOException {
String keyField = null;
String valueField = null;
String valueScript = null;
String scriptLang = null;
Map<String, Object> params = null;
boolean intervalSet = false;
long interval = 1;
String sInterval = null;
MutableDateTime dateTime = new MutableDateTime(DateTimeZone.UTC);
DateHistogramFacet.ComparatorType comparatorType = DateHistogramFacet.ComparatorType.TIME;
XContentParser.Token token;
String fieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
fieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("params".equals(fieldName)) {
params = parser.map();
}
} else if (token.isValue()) {
if ("field".equals(fieldName)) {
keyField = parser.text();
} else if ("key_field".equals(fieldName) || "keyField".equals(fieldName)) {
keyField = parser.text();
} else if ("value_field".equals(fieldName) || "valueField".equals(fieldName)) {
valueField = parser.text();
} else if ("interval".equals(fieldName)) {
intervalSet = true;
if (token == XContentParser.Token.VALUE_NUMBER) {
interval = parser.longValue();
} else {
sInterval = parser.text();
}
} else if ("time_zone".equals(fieldName) || "timeZone".equals(fieldName)) {
if (token == XContentParser.Token.VALUE_NUMBER) {
dateTime.setZone(DateTimeZone.forOffsetHours(parser.intValue()));
} else {
String text = parser.text();
int index = text.indexOf(':');
if (index != -1) {
// format like -02:30
dateTime.setZone(DateTimeZone.forOffsetHoursMinutes(
Integer.parseInt(text.substring(0, index)),
Integer.parseInt(text.substring(index + 1))
));
} else {
// id, listed here: http://joda-time.sourceforge.net/timezones.html
dateTime.setZone(DateTimeZone.forID(text));
}
}
} else if ("value_script".equals(fieldName) || "valueScript".equals(fieldName)) {
valueScript = parser.text();
} else if ("order".equals(fieldName) || "comparator".equals(fieldName)) {
comparatorType = DateHistogramFacet.ComparatorType.fromString(parser.text());
} else if ("lang".equals(fieldName)) {
scriptLang = parser.text();
}
}
}
if (keyField == null) {
throw new FacetPhaseExecutionException(facetName, "key field is required to be set for histogram facet, either using [field] or using [key_field]");
}
FieldMapper mapper = context.mapperService().smartNameFieldMapper(keyField);
if (mapper.fieldDataType() != FieldDataType.DefaultTypes.LONG) {
throw new FacetPhaseExecutionException(facetName, "(key) field [" + keyField + "] is not of type date");
}
if (!intervalSet) {
throw new FacetPhaseExecutionException(facetName, "[interval] is required to be set for histogram facet");
}
// we set the rounding after we set the zone, for it to take affect
if (sInterval != null) {
int index = sInterval.indexOf(':');
if (index != -1) {
// set with rounding
DateFieldParser fieldParser = dateFieldParsers.get(sInterval.substring(0, index));
if (fieldParser == null) {
throw new FacetPhaseExecutionException(facetName, "failed to parse interval [" + sInterval + "] with custom rounding using built in intervals (year/month/...)");
}
DateTimeField field = fieldParser.parse(dateTime.getChronology());
int rounding = this.rounding.get(sInterval.substring(index + 1));
if (rounding == -1) {
throw new FacetPhaseExecutionException(facetName, "failed to parse interval [" + sInterval + "], rounding type [" + (sInterval.substring(index + 1)) + "] not found");
}
dateTime.setRounding(field, rounding);
} else {
DateFieldParser fieldParser = dateFieldParsers.get(sInterval);
if (fieldParser != null) {
DateTimeField field = fieldParser.parse(dateTime.getChronology());
dateTime.setRounding(field, MutableDateTime.ROUND_FLOOR);
} else {
// time interval
try {
interval = TimeValue.parseTimeValue(parser.text(), null).millis();
} catch (Exception e) {
throw new FacetPhaseExecutionException(facetName, "failed to parse interval [" + sInterval + "], tried both as built in intervals (year/month/...) and as a time format");
}
}
}
}
if (valueScript != null) {
return new ValueScriptDateHistogramFacetCollector(facetName, keyField, scriptLang, valueScript, params, dateTime, interval, comparatorType, context);
} else if (valueField == null) {
return new CountDateHistogramFacetCollector(facetName, keyField, dateTime, interval, comparatorType, context);
} else {
return new ValueDateHistogramFacetCollector(facetName, keyField, valueField, dateTime, interval, comparatorType, context);
}
}
| @Override public FacetCollector parse(String facetName, XContentParser parser, SearchContext context) throws IOException {
String keyField = null;
String valueField = null;
String valueScript = null;
String scriptLang = null;
Map<String, Object> params = null;
boolean intervalSet = false;
long interval = 1;
String sInterval = null;
MutableDateTime dateTime = new MutableDateTime(DateTimeZone.UTC);
DateHistogramFacet.ComparatorType comparatorType = DateHistogramFacet.ComparatorType.TIME;
XContentParser.Token token;
String fieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
fieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("params".equals(fieldName)) {
params = parser.map();
}
} else if (token.isValue()) {
if ("field".equals(fieldName)) {
keyField = parser.text();
} else if ("key_field".equals(fieldName) || "keyField".equals(fieldName)) {
keyField = parser.text();
} else if ("value_field".equals(fieldName) || "valueField".equals(fieldName)) {
valueField = parser.text();
} else if ("interval".equals(fieldName)) {
intervalSet = true;
if (token == XContentParser.Token.VALUE_NUMBER) {
interval = parser.longValue();
} else {
sInterval = parser.text();
}
} else if ("time_zone".equals(fieldName) || "timeZone".equals(fieldName)) {
if (token == XContentParser.Token.VALUE_NUMBER) {
dateTime.setZone(DateTimeZone.forOffsetHours(parser.intValue()));
} else {
String text = parser.text();
int index = text.indexOf(':');
if (index != -1) {
// format like -02:30
dateTime.setZone(DateTimeZone.forOffsetHoursMinutes(
Integer.parseInt(text.substring(0, index)),
Integer.parseInt(text.substring(index + 1))
));
} else {
// id, listed here: http://joda-time.sourceforge.net/timezones.html
dateTime.setZone(DateTimeZone.forID(text));
}
}
} else if ("value_script".equals(fieldName) || "valueScript".equals(fieldName)) {
valueScript = parser.text();
} else if ("order".equals(fieldName) || "comparator".equals(fieldName)) {
comparatorType = DateHistogramFacet.ComparatorType.fromString(parser.text());
} else if ("lang".equals(fieldName)) {
scriptLang = parser.text();
}
}
}
if (keyField == null) {
throw new FacetPhaseExecutionException(facetName, "key field is required to be set for histogram facet, either using [field] or using [key_field]");
}
FieldMapper mapper = context.mapperService().smartNameFieldMapper(keyField);
if (mapper.fieldDataType() != FieldDataType.DefaultTypes.LONG) {
throw new FacetPhaseExecutionException(facetName, "(key) field [" + keyField + "] is not of type date");
}
if (!intervalSet) {
throw new FacetPhaseExecutionException(facetName, "[interval] is required to be set for histogram facet");
}
// we set the rounding after we set the zone, for it to take affect
if (sInterval != null) {
int index = sInterval.indexOf(':');
if (index != -1) {
// set with rounding
DateFieldParser fieldParser = dateFieldParsers.get(sInterval.substring(0, index));
if (fieldParser == null) {
throw new FacetPhaseExecutionException(facetName, "failed to parse interval [" + sInterval + "] with custom rounding using built in intervals (year/month/...)");
}
DateTimeField field = fieldParser.parse(dateTime.getChronology());
int rounding = this.rounding.get(sInterval.substring(index + 1));
if (rounding == -1) {
throw new FacetPhaseExecutionException(facetName, "failed to parse interval [" + sInterval + "], rounding type [" + (sInterval.substring(index + 1)) + "] not found");
}
dateTime.setRounding(field, rounding);
} else {
DateFieldParser fieldParser = dateFieldParsers.get(sInterval);
if (fieldParser != null) {
DateTimeField field = fieldParser.parse(dateTime.getChronology());
dateTime.setRounding(field, MutableDateTime.ROUND_FLOOR);
} else {
// time interval
try {
interval = TimeValue.parseTimeValue(sInterval, null).millis();
} catch (Exception e) {
throw new FacetPhaseExecutionException(facetName, "failed to parse interval [" + sInterval + "], tried both as built in intervals (year/month/...) and as a time format");
}
}
}
}
if (valueScript != null) {
return new ValueScriptDateHistogramFacetCollector(facetName, keyField, scriptLang, valueScript, params, dateTime, interval, comparatorType, context);
} else if (valueField == null) {
return new CountDateHistogramFacetCollector(facetName, keyField, dateTime, interval, comparatorType, context);
} else {
return new ValueDateHistogramFacetCollector(facetName, keyField, valueField, dateTime, interval, comparatorType, context);
}
}
|
diff --git a/src/be/ibridge/kettle/pan/Pan.java b/src/be/ibridge/kettle/pan/Pan.java
index c59fae48..e52b9dd2 100644
--- a/src/be/ibridge/kettle/pan/Pan.java
+++ b/src/be/ibridge/kettle/pan/Pan.java
@@ -1,353 +1,358 @@
/**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
/**
* Kettle was (re-)started in March 2003
*/
package be.ibridge.kettle.pan;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.util.EnvUtil;
import be.ibridge.kettle.repository.RepositoriesMeta;
import be.ibridge.kettle.repository.Repository;
import be.ibridge.kettle.repository.RepositoryDirectory;
import be.ibridge.kettle.repository.RepositoryMeta;
import be.ibridge.kettle.repository.UserInfo;
import be.ibridge.kettle.trans.StepLoader;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransMeta;
public class Pan
{
public static void main(String[] a) throws KettleException
{
EnvUtil.environmentInit();
ArrayList args = new ArrayList();
for (int i=0;i<a.length;i++)
{
if (a[i].length()>0)
{
args.add(a[i]);
}
}
RepositoryMeta repinfo = null;
UserInfo userinfo = null;
Trans trans = null;
// The options:
StringBuffer optionRepname, optionUsername, optionPassword, optionTransname, optionDirname, optionFilename, optionLoglevel;
StringBuffer optionLogfile, optionListdir, optionListtrans, optionListrep, optionExprep, optionNorep, optionSafemode;
CommandLineOption options[] = new CommandLineOption[]
{
new CommandLineOption("rep", "Repository name", optionRepname=new StringBuffer()),
new CommandLineOption("user", "Repository username", optionUsername=new StringBuffer()),
new CommandLineOption("pass", "Repository password", optionPassword=new StringBuffer()),
new CommandLineOption("trans", "The name of the transformation to launch", optionTransname=new StringBuffer()),
new CommandLineOption("dir", "The directory (don't forget the leading /)", optionDirname=new StringBuffer()),
new CommandLineOption("file", "The filename (Transformation in XML) to launch", optionFilename=new StringBuffer()),
new CommandLineOption("level", "The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)", optionLoglevel=new StringBuffer()),
new CommandLineOption("logfile", "The logging file to write to", optionLogfile=new StringBuffer()),
new CommandLineOption("log", "The logging file to write to (deprecated)", optionLogfile=new StringBuffer(), false, true),
new CommandLineOption("listdir", "List the directories in the repository", optionListdir=new StringBuffer(), true, false),
new CommandLineOption("listtrans", "List the transformations in the specified directory", optionListtrans=new StringBuffer(), true, false),
new CommandLineOption("listrep", "List the available repositories", optionListrep=new StringBuffer(), true, false),
new CommandLineOption("exprep", "Export all repository objects to one XML file", optionExprep=new StringBuffer(), true, false),
new CommandLineOption("norep", "Do not log into the repository", optionNorep=new StringBuffer(), true, false),
new CommandLineOption("safemode", "Run in safe mode: with extra checking enabled", optionSafemode=new StringBuffer(), true, false),
};
if (args.size()==0 )
{
CommandLineOption.printUsage(options);
System.exit(9);
}
// Parse the options...
CommandLineOption.parseArguments(args, options);
String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null);
String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null);
String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null);
if (kettleRepname !=null && kettleRepname .length()>0) optionRepname = new StringBuffer(kettleRepname);
if (kettleUsername!=null && kettleUsername.length()>0) optionUsername = new StringBuffer(kettleUsername);
if (kettlePassword!=null && kettlePassword.length()>0) optionPassword = new StringBuffer(kettlePassword);
LogWriter log;
if (Const.isEmpty(optionLogfile))
{
log=LogWriter.getInstance( LogWriter.LOG_LEVEL_BASIC );
}
else
{
log=LogWriter.getInstance( optionLogfile.toString(), true, LogWriter.LOG_LEVEL_BASIC );
}
if (!Const.isEmpty(optionLoglevel))
{
log.setLogLevel(optionLoglevel.toString());
log.logMinimal("Pan", "Logging is at level : "+log.getLogLevelDesc());
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// This is where the action starts.
// Print the options before we start processing when running in Debug or Rowlevel
//
if (log.isDebug())
{
System.out.println("Arguments:");
for (int i=0;i<options.length;i++)
{
if (!options[i].isHiddenOption()) System.out.println(Const.rightPad(options[i].getOption(),12)+" : "+options[i].getArgument());
}
System.out.println("");
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
log.logMinimal("Pan", "Start of run.");
/* Load the plugins etc.*/
StepLoader steploader = StepLoader.getInstance();
if (!steploader.read())
{
log.logError("Spoon", "Error loading steps... halting Pan!");
System.exit(8);
}
Date start, stop;
Calendar cal;
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
cal=Calendar.getInstance();
start=cal.getTime();
log.logDebug("Pan", "Allocate new transformation.");
TransMeta transMeta = new TransMeta();
try
{
log.logDebug("Pan", "Starting to look at options...");
// Read kettle transformation specified on command-line?
if (!Const.isEmpty(optionRepname) || !Const.isEmpty(optionFilename))
{
log.logDebug("Pan", "Parsing command line options.");
if (!Const.isEmpty(optionRepname) && !"Y".equalsIgnoreCase(optionNorep.toString()))
{
log.logDebug("Pan", "Loading available repositories.");
RepositoriesMeta repsinfo = new RepositoriesMeta(log);
if (repsinfo.readData())
{
log.logDebug("Pan", "Finding repository ["+optionRepname+"]");
repinfo = repsinfo.findRepository(optionRepname.toString());
if (repinfo!=null)
{
// Define and connect to the repository...
log.logDebug("Pan", "Allocate & connect to repository.");
Repository rep = new Repository(log, repinfo, userinfo);
if (rep.connect("Pan commandline"))
{
RepositoryDirectory directory = rep.getDirectoryTree(); // Default = root
// Find the directory name if one is specified...
if (!Const.isEmpty(optionDirname))
{
directory = rep.getDirectoryTree().findDirectory(optionDirname.toString());
}
if (directory!=null)
{
// Check username, password
log.logDebug("Pan", "Check supplied username and password.");
userinfo = new UserInfo(rep, optionUsername.toString(), optionPassword.toString());
if (userinfo.getID()>0)
{
// Load a transformation
if (!Const.isEmpty(optionTransname))
{
log.logDebug("Pan", "Load the transformation info...");
transMeta = new TransMeta(rep, optionTransname.toString(), directory);
log.logDebug("Pan", "Allocate transformation...");
trans = new Trans(log, transMeta);
}
else
// List the transformations in the repository
if ("Y".equalsIgnoreCase(optionListtrans.toString()))
{
log.logDebug("Pan", "Getting list of transformations in directory: "+directory);
String transnames[] = rep.getTransformationNames(directory.getID());
for (int i=0;i<transnames.length;i++)
{
System.out.println(transnames[i]);
}
}
else
// List the directories in the repository
if ("Y".equalsIgnoreCase(optionListdir.toString()))
{
String dirnames[] = rep.getDirectoryNames(directory.getID());
for (int i=0;i<dirnames.length;i++)
{
System.out.println(dirnames[i]);
}
}
else
// Export the repository
if (!Const.isEmpty(optionExprep))
{
System.out.println("Exporting all objects in the repository to file ["+optionExprep+"]");
rep.exportAllObjects(null, optionExprep.toString());
System.out.println("Finished exporting all objects in the repository to file ["+optionExprep+"]");
}
else
{
System.out.println("ERROR: No transformation name supplied: which one should be run?");
}
}
else
{
System.out.println("ERROR: Can't verify username and password.");
userinfo=null;
repinfo=null;
}
}
else
{
System.out.println("ERROR: Can't find the specified directory ["+optionDirname+"]");
userinfo=null;
repinfo=null;
}
rep.disconnect();
}
else
{
System.out.println("ERROR: Can't connect to the repository.");
}
}
else
{
System.out.println("ERROR: No repository provided, can't load transformation.");
}
}
else
{
System.out.println("ERROR: No repositories defined on this system.");
}
}
// Try to load the transformation from file, even if it failed to load from the repository
// You could implement some failover mechanism this way.
//
if (trans==null && !Const.isEmpty(optionFilename))
{
log.logDetailed("Pan", "Loading transformation from XML file ["+optionFilename+"]");
transMeta = new TransMeta(optionFilename.toString());
trans = new Trans(log, transMeta);
}
}
if ("Y".equalsIgnoreCase(optionListrep.toString()))
{
log.logDebug("Pan", "Getting the list of repositories...");
RepositoriesMeta ri = new RepositoriesMeta(log);
if (ri.readData())
{
System.out.println("List of repositories:");
for (int i=0;i<ri.nrRepositories();i++)
{
RepositoryMeta rinfo = ri.getRepository(i);
System.out.println("#"+(i+1)+" : "+rinfo.getName()+" ["+rinfo.getDescription()+"] ");
}
}
else
{
System.out.println("ERROR: Unable to read/parse the repositories XML file.");
}
}
}
catch(KettleException e)
{
trans=null;
transMeta=null;
System.out.println("Processing has stopped because of an error: "+e.getMessage());
}
if (trans==null)
{
if (!"Y".equalsIgnoreCase(optionListtrans.toString()) &&
!"Y".equalsIgnoreCase(optionListdir.toString()) &&
!"Y".equalsIgnoreCase(optionListrep.toString()) &&
Const.isEmpty(optionExprep)
)
{
System.out.println("ERROR: Pan can't continue because the transformation couldn't be loaded.");
}
System.exit(7);
}
try
{
// See if we want to run in safe mode:
if ("Y".equalsIgnoreCase(optionSafemode.toString()))
{
trans.setSafeModeEnabled(true);
}
// allocate & run the required sub-threads
boolean ok = trans.execute((String[])args.toArray(new String[args.size()]));
+ if (!ok)
+ {
+ System.out.println("Unable to prepare and initialize this transformation");
+ System.exit(3);
+ }
trans.waitUntilFinished();
trans.endProcessing("end");
log.logMinimal("Pan", "Finished!");
cal=Calendar.getInstance();
stop=cal.getTime();
String begin=df.format(start).toString();
String end =df.format(stop).toString();
log.logMinimal("Pan", "Start="+begin+", Stop="+end);
long millis=stop.getTime()-start.getTime();
log.logMinimal("Pan", "Processing ended after "+(millis/1000)+" seconds.");
- if (ok)
+ if (trans.getResult().getNrErrors()==0)
{
trans.printStats((int)millis/1000);
System.exit(0);
}
else
{
System.exit(1);
}
}
catch(KettleException ke)
{
System.out.println("ERROR occurred: "+ke.getMessage());
log.logError("Pan", "Unexpected error occurred: "+ke.getMessage());
System.exit(2);
}
}
}
| false | true | public static void main(String[] a) throws KettleException
{
EnvUtil.environmentInit();
ArrayList args = new ArrayList();
for (int i=0;i<a.length;i++)
{
if (a[i].length()>0)
{
args.add(a[i]);
}
}
RepositoryMeta repinfo = null;
UserInfo userinfo = null;
Trans trans = null;
// The options:
StringBuffer optionRepname, optionUsername, optionPassword, optionTransname, optionDirname, optionFilename, optionLoglevel;
StringBuffer optionLogfile, optionListdir, optionListtrans, optionListrep, optionExprep, optionNorep, optionSafemode;
CommandLineOption options[] = new CommandLineOption[]
{
new CommandLineOption("rep", "Repository name", optionRepname=new StringBuffer()),
new CommandLineOption("user", "Repository username", optionUsername=new StringBuffer()),
new CommandLineOption("pass", "Repository password", optionPassword=new StringBuffer()),
new CommandLineOption("trans", "The name of the transformation to launch", optionTransname=new StringBuffer()),
new CommandLineOption("dir", "The directory (don't forget the leading /)", optionDirname=new StringBuffer()),
new CommandLineOption("file", "The filename (Transformation in XML) to launch", optionFilename=new StringBuffer()),
new CommandLineOption("level", "The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)", optionLoglevel=new StringBuffer()),
new CommandLineOption("logfile", "The logging file to write to", optionLogfile=new StringBuffer()),
new CommandLineOption("log", "The logging file to write to (deprecated)", optionLogfile=new StringBuffer(), false, true),
new CommandLineOption("listdir", "List the directories in the repository", optionListdir=new StringBuffer(), true, false),
new CommandLineOption("listtrans", "List the transformations in the specified directory", optionListtrans=new StringBuffer(), true, false),
new CommandLineOption("listrep", "List the available repositories", optionListrep=new StringBuffer(), true, false),
new CommandLineOption("exprep", "Export all repository objects to one XML file", optionExprep=new StringBuffer(), true, false),
new CommandLineOption("norep", "Do not log into the repository", optionNorep=new StringBuffer(), true, false),
new CommandLineOption("safemode", "Run in safe mode: with extra checking enabled", optionSafemode=new StringBuffer(), true, false),
};
if (args.size()==0 )
{
CommandLineOption.printUsage(options);
System.exit(9);
}
// Parse the options...
CommandLineOption.parseArguments(args, options);
String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null);
String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null);
String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null);
if (kettleRepname !=null && kettleRepname .length()>0) optionRepname = new StringBuffer(kettleRepname);
if (kettleUsername!=null && kettleUsername.length()>0) optionUsername = new StringBuffer(kettleUsername);
if (kettlePassword!=null && kettlePassword.length()>0) optionPassword = new StringBuffer(kettlePassword);
LogWriter log;
if (Const.isEmpty(optionLogfile))
{
log=LogWriter.getInstance( LogWriter.LOG_LEVEL_BASIC );
}
else
{
log=LogWriter.getInstance( optionLogfile.toString(), true, LogWriter.LOG_LEVEL_BASIC );
}
if (!Const.isEmpty(optionLoglevel))
{
log.setLogLevel(optionLoglevel.toString());
log.logMinimal("Pan", "Logging is at level : "+log.getLogLevelDesc());
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// This is where the action starts.
// Print the options before we start processing when running in Debug or Rowlevel
//
if (log.isDebug())
{
System.out.println("Arguments:");
for (int i=0;i<options.length;i++)
{
if (!options[i].isHiddenOption()) System.out.println(Const.rightPad(options[i].getOption(),12)+" : "+options[i].getArgument());
}
System.out.println("");
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
log.logMinimal("Pan", "Start of run.");
/* Load the plugins etc.*/
StepLoader steploader = StepLoader.getInstance();
if (!steploader.read())
{
log.logError("Spoon", "Error loading steps... halting Pan!");
System.exit(8);
}
Date start, stop;
Calendar cal;
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
cal=Calendar.getInstance();
start=cal.getTime();
log.logDebug("Pan", "Allocate new transformation.");
TransMeta transMeta = new TransMeta();
try
{
log.logDebug("Pan", "Starting to look at options...");
// Read kettle transformation specified on command-line?
if (!Const.isEmpty(optionRepname) || !Const.isEmpty(optionFilename))
{
log.logDebug("Pan", "Parsing command line options.");
if (!Const.isEmpty(optionRepname) && !"Y".equalsIgnoreCase(optionNorep.toString()))
{
log.logDebug("Pan", "Loading available repositories.");
RepositoriesMeta repsinfo = new RepositoriesMeta(log);
if (repsinfo.readData())
{
log.logDebug("Pan", "Finding repository ["+optionRepname+"]");
repinfo = repsinfo.findRepository(optionRepname.toString());
if (repinfo!=null)
{
// Define and connect to the repository...
log.logDebug("Pan", "Allocate & connect to repository.");
Repository rep = new Repository(log, repinfo, userinfo);
if (rep.connect("Pan commandline"))
{
RepositoryDirectory directory = rep.getDirectoryTree(); // Default = root
// Find the directory name if one is specified...
if (!Const.isEmpty(optionDirname))
{
directory = rep.getDirectoryTree().findDirectory(optionDirname.toString());
}
if (directory!=null)
{
// Check username, password
log.logDebug("Pan", "Check supplied username and password.");
userinfo = new UserInfo(rep, optionUsername.toString(), optionPassword.toString());
if (userinfo.getID()>0)
{
// Load a transformation
if (!Const.isEmpty(optionTransname))
{
log.logDebug("Pan", "Load the transformation info...");
transMeta = new TransMeta(rep, optionTransname.toString(), directory);
log.logDebug("Pan", "Allocate transformation...");
trans = new Trans(log, transMeta);
}
else
// List the transformations in the repository
if ("Y".equalsIgnoreCase(optionListtrans.toString()))
{
log.logDebug("Pan", "Getting list of transformations in directory: "+directory);
String transnames[] = rep.getTransformationNames(directory.getID());
for (int i=0;i<transnames.length;i++)
{
System.out.println(transnames[i]);
}
}
else
// List the directories in the repository
if ("Y".equalsIgnoreCase(optionListdir.toString()))
{
String dirnames[] = rep.getDirectoryNames(directory.getID());
for (int i=0;i<dirnames.length;i++)
{
System.out.println(dirnames[i]);
}
}
else
// Export the repository
if (!Const.isEmpty(optionExprep))
{
System.out.println("Exporting all objects in the repository to file ["+optionExprep+"]");
rep.exportAllObjects(null, optionExprep.toString());
System.out.println("Finished exporting all objects in the repository to file ["+optionExprep+"]");
}
else
{
System.out.println("ERROR: No transformation name supplied: which one should be run?");
}
}
else
{
System.out.println("ERROR: Can't verify username and password.");
userinfo=null;
repinfo=null;
}
}
else
{
System.out.println("ERROR: Can't find the specified directory ["+optionDirname+"]");
userinfo=null;
repinfo=null;
}
rep.disconnect();
}
else
{
System.out.println("ERROR: Can't connect to the repository.");
}
}
else
{
System.out.println("ERROR: No repository provided, can't load transformation.");
}
}
else
{
System.out.println("ERROR: No repositories defined on this system.");
}
}
// Try to load the transformation from file, even if it failed to load from the repository
// You could implement some failover mechanism this way.
//
if (trans==null && !Const.isEmpty(optionFilename))
{
log.logDetailed("Pan", "Loading transformation from XML file ["+optionFilename+"]");
transMeta = new TransMeta(optionFilename.toString());
trans = new Trans(log, transMeta);
}
}
if ("Y".equalsIgnoreCase(optionListrep.toString()))
{
log.logDebug("Pan", "Getting the list of repositories...");
RepositoriesMeta ri = new RepositoriesMeta(log);
if (ri.readData())
{
System.out.println("List of repositories:");
for (int i=0;i<ri.nrRepositories();i++)
{
RepositoryMeta rinfo = ri.getRepository(i);
System.out.println("#"+(i+1)+" : "+rinfo.getName()+" ["+rinfo.getDescription()+"] ");
}
}
else
{
System.out.println("ERROR: Unable to read/parse the repositories XML file.");
}
}
}
catch(KettleException e)
{
trans=null;
transMeta=null;
System.out.println("Processing has stopped because of an error: "+e.getMessage());
}
if (trans==null)
{
if (!"Y".equalsIgnoreCase(optionListtrans.toString()) &&
!"Y".equalsIgnoreCase(optionListdir.toString()) &&
!"Y".equalsIgnoreCase(optionListrep.toString()) &&
Const.isEmpty(optionExprep)
)
{
System.out.println("ERROR: Pan can't continue because the transformation couldn't be loaded.");
}
System.exit(7);
}
try
{
// See if we want to run in safe mode:
if ("Y".equalsIgnoreCase(optionSafemode.toString()))
{
trans.setSafeModeEnabled(true);
}
// allocate & run the required sub-threads
boolean ok = trans.execute((String[])args.toArray(new String[args.size()]));
trans.waitUntilFinished();
trans.endProcessing("end");
log.logMinimal("Pan", "Finished!");
cal=Calendar.getInstance();
stop=cal.getTime();
String begin=df.format(start).toString();
String end =df.format(stop).toString();
log.logMinimal("Pan", "Start="+begin+", Stop="+end);
long millis=stop.getTime()-start.getTime();
log.logMinimal("Pan", "Processing ended after "+(millis/1000)+" seconds.");
if (ok)
{
trans.printStats((int)millis/1000);
System.exit(0);
}
else
{
System.exit(1);
}
}
catch(KettleException ke)
{
System.out.println("ERROR occurred: "+ke.getMessage());
log.logError("Pan", "Unexpected error occurred: "+ke.getMessage());
System.exit(2);
}
}
| public static void main(String[] a) throws KettleException
{
EnvUtil.environmentInit();
ArrayList args = new ArrayList();
for (int i=0;i<a.length;i++)
{
if (a[i].length()>0)
{
args.add(a[i]);
}
}
RepositoryMeta repinfo = null;
UserInfo userinfo = null;
Trans trans = null;
// The options:
StringBuffer optionRepname, optionUsername, optionPassword, optionTransname, optionDirname, optionFilename, optionLoglevel;
StringBuffer optionLogfile, optionListdir, optionListtrans, optionListrep, optionExprep, optionNorep, optionSafemode;
CommandLineOption options[] = new CommandLineOption[]
{
new CommandLineOption("rep", "Repository name", optionRepname=new StringBuffer()),
new CommandLineOption("user", "Repository username", optionUsername=new StringBuffer()),
new CommandLineOption("pass", "Repository password", optionPassword=new StringBuffer()),
new CommandLineOption("trans", "The name of the transformation to launch", optionTransname=new StringBuffer()),
new CommandLineOption("dir", "The directory (don't forget the leading /)", optionDirname=new StringBuffer()),
new CommandLineOption("file", "The filename (Transformation in XML) to launch", optionFilename=new StringBuffer()),
new CommandLineOption("level", "The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)", optionLoglevel=new StringBuffer()),
new CommandLineOption("logfile", "The logging file to write to", optionLogfile=new StringBuffer()),
new CommandLineOption("log", "The logging file to write to (deprecated)", optionLogfile=new StringBuffer(), false, true),
new CommandLineOption("listdir", "List the directories in the repository", optionListdir=new StringBuffer(), true, false),
new CommandLineOption("listtrans", "List the transformations in the specified directory", optionListtrans=new StringBuffer(), true, false),
new CommandLineOption("listrep", "List the available repositories", optionListrep=new StringBuffer(), true, false),
new CommandLineOption("exprep", "Export all repository objects to one XML file", optionExprep=new StringBuffer(), true, false),
new CommandLineOption("norep", "Do not log into the repository", optionNorep=new StringBuffer(), true, false),
new CommandLineOption("safemode", "Run in safe mode: with extra checking enabled", optionSafemode=new StringBuffer(), true, false),
};
if (args.size()==0 )
{
CommandLineOption.printUsage(options);
System.exit(9);
}
// Parse the options...
CommandLineOption.parseArguments(args, options);
String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null);
String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null);
String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null);
if (kettleRepname !=null && kettleRepname .length()>0) optionRepname = new StringBuffer(kettleRepname);
if (kettleUsername!=null && kettleUsername.length()>0) optionUsername = new StringBuffer(kettleUsername);
if (kettlePassword!=null && kettlePassword.length()>0) optionPassword = new StringBuffer(kettlePassword);
LogWriter log;
if (Const.isEmpty(optionLogfile))
{
log=LogWriter.getInstance( LogWriter.LOG_LEVEL_BASIC );
}
else
{
log=LogWriter.getInstance( optionLogfile.toString(), true, LogWriter.LOG_LEVEL_BASIC );
}
if (!Const.isEmpty(optionLoglevel))
{
log.setLogLevel(optionLoglevel.toString());
log.logMinimal("Pan", "Logging is at level : "+log.getLogLevelDesc());
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// This is where the action starts.
// Print the options before we start processing when running in Debug or Rowlevel
//
if (log.isDebug())
{
System.out.println("Arguments:");
for (int i=0;i<options.length;i++)
{
if (!options[i].isHiddenOption()) System.out.println(Const.rightPad(options[i].getOption(),12)+" : "+options[i].getArgument());
}
System.out.println("");
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
log.logMinimal("Pan", "Start of run.");
/* Load the plugins etc.*/
StepLoader steploader = StepLoader.getInstance();
if (!steploader.read())
{
log.logError("Spoon", "Error loading steps... halting Pan!");
System.exit(8);
}
Date start, stop;
Calendar cal;
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
cal=Calendar.getInstance();
start=cal.getTime();
log.logDebug("Pan", "Allocate new transformation.");
TransMeta transMeta = new TransMeta();
try
{
log.logDebug("Pan", "Starting to look at options...");
// Read kettle transformation specified on command-line?
if (!Const.isEmpty(optionRepname) || !Const.isEmpty(optionFilename))
{
log.logDebug("Pan", "Parsing command line options.");
if (!Const.isEmpty(optionRepname) && !"Y".equalsIgnoreCase(optionNorep.toString()))
{
log.logDebug("Pan", "Loading available repositories.");
RepositoriesMeta repsinfo = new RepositoriesMeta(log);
if (repsinfo.readData())
{
log.logDebug("Pan", "Finding repository ["+optionRepname+"]");
repinfo = repsinfo.findRepository(optionRepname.toString());
if (repinfo!=null)
{
// Define and connect to the repository...
log.logDebug("Pan", "Allocate & connect to repository.");
Repository rep = new Repository(log, repinfo, userinfo);
if (rep.connect("Pan commandline"))
{
RepositoryDirectory directory = rep.getDirectoryTree(); // Default = root
// Find the directory name if one is specified...
if (!Const.isEmpty(optionDirname))
{
directory = rep.getDirectoryTree().findDirectory(optionDirname.toString());
}
if (directory!=null)
{
// Check username, password
log.logDebug("Pan", "Check supplied username and password.");
userinfo = new UserInfo(rep, optionUsername.toString(), optionPassword.toString());
if (userinfo.getID()>0)
{
// Load a transformation
if (!Const.isEmpty(optionTransname))
{
log.logDebug("Pan", "Load the transformation info...");
transMeta = new TransMeta(rep, optionTransname.toString(), directory);
log.logDebug("Pan", "Allocate transformation...");
trans = new Trans(log, transMeta);
}
else
// List the transformations in the repository
if ("Y".equalsIgnoreCase(optionListtrans.toString()))
{
log.logDebug("Pan", "Getting list of transformations in directory: "+directory);
String transnames[] = rep.getTransformationNames(directory.getID());
for (int i=0;i<transnames.length;i++)
{
System.out.println(transnames[i]);
}
}
else
// List the directories in the repository
if ("Y".equalsIgnoreCase(optionListdir.toString()))
{
String dirnames[] = rep.getDirectoryNames(directory.getID());
for (int i=0;i<dirnames.length;i++)
{
System.out.println(dirnames[i]);
}
}
else
// Export the repository
if (!Const.isEmpty(optionExprep))
{
System.out.println("Exporting all objects in the repository to file ["+optionExprep+"]");
rep.exportAllObjects(null, optionExprep.toString());
System.out.println("Finished exporting all objects in the repository to file ["+optionExprep+"]");
}
else
{
System.out.println("ERROR: No transformation name supplied: which one should be run?");
}
}
else
{
System.out.println("ERROR: Can't verify username and password.");
userinfo=null;
repinfo=null;
}
}
else
{
System.out.println("ERROR: Can't find the specified directory ["+optionDirname+"]");
userinfo=null;
repinfo=null;
}
rep.disconnect();
}
else
{
System.out.println("ERROR: Can't connect to the repository.");
}
}
else
{
System.out.println("ERROR: No repository provided, can't load transformation.");
}
}
else
{
System.out.println("ERROR: No repositories defined on this system.");
}
}
// Try to load the transformation from file, even if it failed to load from the repository
// You could implement some failover mechanism this way.
//
if (trans==null && !Const.isEmpty(optionFilename))
{
log.logDetailed("Pan", "Loading transformation from XML file ["+optionFilename+"]");
transMeta = new TransMeta(optionFilename.toString());
trans = new Trans(log, transMeta);
}
}
if ("Y".equalsIgnoreCase(optionListrep.toString()))
{
log.logDebug("Pan", "Getting the list of repositories...");
RepositoriesMeta ri = new RepositoriesMeta(log);
if (ri.readData())
{
System.out.println("List of repositories:");
for (int i=0;i<ri.nrRepositories();i++)
{
RepositoryMeta rinfo = ri.getRepository(i);
System.out.println("#"+(i+1)+" : "+rinfo.getName()+" ["+rinfo.getDescription()+"] ");
}
}
else
{
System.out.println("ERROR: Unable to read/parse the repositories XML file.");
}
}
}
catch(KettleException e)
{
trans=null;
transMeta=null;
System.out.println("Processing has stopped because of an error: "+e.getMessage());
}
if (trans==null)
{
if (!"Y".equalsIgnoreCase(optionListtrans.toString()) &&
!"Y".equalsIgnoreCase(optionListdir.toString()) &&
!"Y".equalsIgnoreCase(optionListrep.toString()) &&
Const.isEmpty(optionExprep)
)
{
System.out.println("ERROR: Pan can't continue because the transformation couldn't be loaded.");
}
System.exit(7);
}
try
{
// See if we want to run in safe mode:
if ("Y".equalsIgnoreCase(optionSafemode.toString()))
{
trans.setSafeModeEnabled(true);
}
// allocate & run the required sub-threads
boolean ok = trans.execute((String[])args.toArray(new String[args.size()]));
if (!ok)
{
System.out.println("Unable to prepare and initialize this transformation");
System.exit(3);
}
trans.waitUntilFinished();
trans.endProcessing("end");
log.logMinimal("Pan", "Finished!");
cal=Calendar.getInstance();
stop=cal.getTime();
String begin=df.format(start).toString();
String end =df.format(stop).toString();
log.logMinimal("Pan", "Start="+begin+", Stop="+end);
long millis=stop.getTime()-start.getTime();
log.logMinimal("Pan", "Processing ended after "+(millis/1000)+" seconds.");
if (trans.getResult().getNrErrors()==0)
{
trans.printStats((int)millis/1000);
System.exit(0);
}
else
{
System.exit(1);
}
}
catch(KettleException ke)
{
System.out.println("ERROR occurred: "+ke.getMessage());
log.logError("Pan", "Unexpected error occurred: "+ke.getMessage());
System.exit(2);
}
}
|
diff --git a/AudioRacer-Android/src/at/fhv/audioracer/client/android/activity/PlayGameActivity.java b/AudioRacer-Android/src/at/fhv/audioracer/client/android/activity/PlayGameActivity.java
index 313bfac..2e78aea 100644
--- a/AudioRacer-Android/src/at/fhv/audioracer/client/android/activity/PlayGameActivity.java
+++ b/AudioRacer-Android/src/at/fhv/audioracer/client/android/activity/PlayGameActivity.java
@@ -1,451 +1,451 @@
package at.fhv.audioracer.client.android.activity;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import at.fhv.audioracer.client.android.R;
import at.fhv.audioracer.client.android.activity.listener.IControlMode;
import at.fhv.audioracer.client.android.controller.ClientManager;
import at.fhv.audioracer.client.android.network.task.PlayerReadyAsyncTask;
import at.fhv.audioracer.client.android.network.task.params.NetworkParams;
import at.fhv.audioracer.client.android.util.SystemUiHider;
import at.fhv.audioracer.client.android.util.SystemUiHiderAndroidRacer;
/**
* This is the main activity to play the game.<br>
* At first, a player can choose between different 'control modes':<br>
* <ul>
* <li>Standard controls: 4 buttons layout: up, down, left, right</li>
* <li>(not yet implemented) Joystick controls: use an 'on-screen-joystick' to control the car.</li>
* <li>(not yet implemented) Motion controls: use the motion sensors to control the car.</li>
* </ul>
*/
public class PlayGameActivity extends Activity implements IControlMode {
private SystemUiHider _systemUiHider;
public static enum ControlMode {
STANDARD,
// JOYSTICK,
SENSOR, ;
}
protected boolean _speedUp;
protected boolean _speedDown;
protected boolean _steerLeft;
protected boolean _steerRight;
private View _chooseControlsView;
private View _standardControlsView;
private View _motionSensorControlsView;
private ImageView _msCtrlImgView;
private List<ThreadControlMode> _threads;
private ControlMode _chosenControlMode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game);
// get all views
_chooseControlsView = findViewById(R.id.choose_controls);
_standardControlsView = findViewById(R.id.standard_controls);
_motionSensorControlsView = findViewById(R.id.motion_sensor_controls);
// get the 'motion sensor' image view.
// a circle and the current 'motion position' will be drawn onto this view.
_msCtrlImgView = (ImageView) findViewById(R.id.ms_ctrl_img_view);
// set other views than 'chooseControlsView' invisible
_standardControlsView.setVisibility(View.INVISIBLE);
_motionSensorControlsView.setVisibility(View.INVISIBLE);
// possible threads
_threads = new LinkedList<PlayGameActivity.ThreadControlMode>();
_threads.add(new ThreadControlMode(ControlMode.STANDARD, new StandardControlThread()));
_threads.add(new ThreadControlMode(ControlMode.SENSOR, new MotionSensorControlThread()));
/* ChooseControls */
// Choose 'Standard controls'
final Button stdCtrlButton = (Button) findViewById(R.id.std_ctrl);
stdCtrlButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ready(ControlMode.STANDARD);
}
});
// Choose 'Motion Sensor'
final Button msCtrlButton = (Button) findViewById(R.id.ms_ctrl);
msCtrlButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ready(ControlMode.SENSOR);
}
});
final Button upButton = (Button) findViewById(R.id.std_ctrl_up);
final Button downButton = (Button) findViewById(R.id.std_ctrl_down);
final Button leftButton = (Button) findViewById(R.id.std_ctrl_left);
final Button rightButton = (Button) findViewById(R.id.std_ctrl_right);
upButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
_speedUp = true;
}
if (MotionEvent.ACTION_UP == event.getAction()) {
_speedUp = false;
}
- Log.d("foo", "speedUp " + _speedUp);
- return false;
+ Log.d("control", "speedUp " + _speedUp);
+ return true;
}
});
downButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
_speedDown = true;
}
if (MotionEvent.ACTION_UP == event.getAction()) {
_speedDown = false;
}
- Log.d("foo", "speedDown " + _speedDown);
- return false;
+ Log.d("control", "speedDown " + _speedDown);
+ return true;
}
});
leftButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
_steerLeft = true;
}
if (MotionEvent.ACTION_UP == event.getAction()) {
_steerLeft = false;
}
- Log.d("foo", "steerLeft " + _steerLeft);
- return false;
+ Log.d("control", "steerLeft " + _steerLeft);
+ return true;
}
});
rightButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
_steerRight = true;
}
if (MotionEvent.ACTION_UP == event.getAction()) {
_steerRight = false;
}
- Log.d("foo", "steerRight " + _steerRight);
- return false;
+ Log.d("control", "steerRight " + _steerRight);
+ return true;
}
});
/* End of: ChooseControls */
// hide SystemUi
_systemUiHider = new SystemUiHiderAndroidRacer(this, _standardControlsView, SystemUiHider.FLAG_FULLSCREEN);
_systemUiHider.setup();
_systemUiHider.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
@Override
public void onVisibilityChange(boolean visible) {
Log.d("foo", "onVisibilityChange: visible? " + visible);
}
});
_systemUiHider.hide();
}
@Override
protected void onResume() {
super.onResume();
// enable controls again.
if (_chosenControlMode != null) {
setControlMode(_chosenControlMode);
}
}
@Override
protected void onStop() {
super.onStop();
stopAllThreads();
}
@Override
protected void onPause() {
super.onPause();
stopAllThreads();
}
private void ready(ControlMode mode) {
new PlayerReadyAsyncTask(this, mode).execute(new NetworkParams());
}
@Override
public void setControlMode(ControlMode mode) {
_chosenControlMode = mode;
switch (mode) {
case STANDARD:
_chooseControlsView.setVisibility(View.INVISIBLE);
_standardControlsView.setVisibility(View.VISIBLE);
_motionSensorControlsView.setVisibility(View.INVISIBLE);
startThread(mode);
break;
case SENSOR:
_chooseControlsView.setVisibility(View.INVISIBLE);
_standardControlsView.setVisibility(View.INVISIBLE);
_motionSensorControlsView.setVisibility(View.VISIBLE);
startThread(mode);
break;
default:
// set control to STANDARD
setControlMode(ControlMode.STANDARD);
}
}
private void startThread(ControlMode mode) {
for (ThreadControlMode tcm : _threads) {
if (tcm.mode == mode) {
tcm.thread.start();
return;
}
}
}
private void stopAllThreads() {
for (ThreadControlMode tcm : _threads) {
tcm.thread.stop();
}
}
/* Standard controls */
/* copied from AudioRacer-PlayerSimulator: package at.fhv.audioracer.simulator.player.pivot.CarControlComponent */
private static final float CONTROL_SENSITY = 1.f;
protected static final long MAX_CONTROL_WAIT = 10;
private float _speed;
private float _direction;
private class ThreadControlMode {
private ControlMode mode;
private ControlThread thread;
public ThreadControlMode(ControlMode mode, ControlThread thread) {
this.mode = mode;
this.thread = thread;
}
}
protected abstract class ControlThread implements Runnable {
protected volatile long _lastUpdate;
private volatile Thread _thread;
public void start() {
_thread = new Thread(this);
_thread.start();
}
public void stop() {
_thread = null;
reset();
}
protected abstract void reset();
@Override
public void run() {
Thread thisThread = Thread.currentThread();
_lastUpdate = System.currentTimeMillis();
while (thisThread == _thread) {
long now = System.currentTimeMillis();
// call the 'hook'
control();
long wait = MAX_CONTROL_WAIT - (System.currentTimeMillis() - _lastUpdate);
_lastUpdate = now;
if (wait > 0) {
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public abstract void control();
}
protected class StandardControlThread extends ControlThread {
@Override
public void control() {
float sensity = (((System.currentTimeMillis() - _lastUpdate) / 1000.f) * CONTROL_SENSITY);
if (_speedUp) {
_speed = Math.min(1.f, (_speed + sensity));
} else if (_speedDown) {
_speed = Math.max(-1.f, (_speed - sensity));
} else if (_speed < 0) {
_speed = Math.min(0.f, (_speed + sensity));
} else if (_speed > 0) {
_speed = Math.max(0.f, (_speed - sensity));
}
if (_steerLeft) {
_direction = Math.max(-1.f, (_direction - sensity));
} else if (_steerRight) {
_direction = Math.min(1.f, (_direction + sensity));
} else if (_direction < 0) {
_direction = Math.min(0.f, (_direction + sensity));
} else if (_direction > 0) {
_direction = Math.max(0.f, (_direction - sensity));
}
// note that this is sent continuously
ClientManager.getInstance().getPlayerClient().getPlayerServer().updateVelocity(_speed, _direction);
}
@Override
protected void reset() {
_speedUp = false;
_speedDown = false;
_steerLeft = false;
_steerRight = false;
}
}
/* end of: copied from AudioRacer-PlayerSimulator: package at.fhv.audioracer.simulator.player.pivot.CarControlComponent */
/* end of: Standard controls */
/* Motion sensor controls */
protected class MotionSensorControlThread extends ControlThread {
private Bitmap _bmp;
private Paint _cPaint;
private Paint _pPaint;
private Canvas _cv;
private Integer _minDim = null;
float _x;
float _y;
float _z;
private SensorManager _sensorManager;
private Sensor _sensor;
private SensorEventListener _sensorListener;
public MotionSensorControlThread() {
int cxy = getMinScreenDimension();
_bmp = Bitmap.createBitmap(cxy, cxy, Bitmap.Config.ARGB_8888);
_cv = new Canvas(_bmp);
// circle paint
_cPaint = new Paint();
_cPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
_cPaint.setColor(Color.WHITE);
// point paint
_pPaint = new Paint();
_pPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
_pPaint.setColor(Color.BLUE);
}
private int getMinScreenDimension() {
if (_minDim == null) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
_minDim = Math.min(size.x, size.y);
Log.d(ACTIVITY_SERVICE, "getMinScreenDimension: " + _minDim);
}
return _minDim;
}
private void initSensorValues() {
if (_sensorManager == null) {
_sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
_sensor = _sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
_sensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
_x = values[0];
_y = values[1];
_z = values[2];
String xyz = String.format("%f4.5\t%f4.5\t%f4.5", _x, _y, _z);
Log.d("sensor", xyz);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// no op
}
};
_sensorManager.registerListener(_sensorListener, _sensor, SensorManager.SENSOR_DELAY_GAME);
}
}
@Override
protected void reset() {
if (_sensorManager != null) {
_sensorManager.unregisterListener(_sensorListener);
}
_sensorManager = null;
_sensor = null;
}
@Override
public void control() {
initSensorValues();
final int cxy = getMinScreenDimension();
final int centerXY = cxy / 2;
final int radius = cxy / 2;
final int motionX = centerXY + (int) (radius * _y);
final int motionY = centerXY + (int) (radius * _x);
_msCtrlImgView.post(new Runnable() {
@Override
public void run() {
_cv.drawCircle(centerXY, centerXY, radius, _cPaint);
_cv.drawCircle(motionX, motionY, 5, _pPaint);
_msCtrlImgView.setBackground(new BitmapDrawable(getResources(), _bmp));
}
});
}
}
/* end of: Motion sensor controls */
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game);
// get all views
_chooseControlsView = findViewById(R.id.choose_controls);
_standardControlsView = findViewById(R.id.standard_controls);
_motionSensorControlsView = findViewById(R.id.motion_sensor_controls);
// get the 'motion sensor' image view.
// a circle and the current 'motion position' will be drawn onto this view.
_msCtrlImgView = (ImageView) findViewById(R.id.ms_ctrl_img_view);
// set other views than 'chooseControlsView' invisible
_standardControlsView.setVisibility(View.INVISIBLE);
_motionSensorControlsView.setVisibility(View.INVISIBLE);
// possible threads
_threads = new LinkedList<PlayGameActivity.ThreadControlMode>();
_threads.add(new ThreadControlMode(ControlMode.STANDARD, new StandardControlThread()));
_threads.add(new ThreadControlMode(ControlMode.SENSOR, new MotionSensorControlThread()));
/* ChooseControls */
// Choose 'Standard controls'
final Button stdCtrlButton = (Button) findViewById(R.id.std_ctrl);
stdCtrlButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ready(ControlMode.STANDARD);
}
});
// Choose 'Motion Sensor'
final Button msCtrlButton = (Button) findViewById(R.id.ms_ctrl);
msCtrlButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ready(ControlMode.SENSOR);
}
});
final Button upButton = (Button) findViewById(R.id.std_ctrl_up);
final Button downButton = (Button) findViewById(R.id.std_ctrl_down);
final Button leftButton = (Button) findViewById(R.id.std_ctrl_left);
final Button rightButton = (Button) findViewById(R.id.std_ctrl_right);
upButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
_speedUp = true;
}
if (MotionEvent.ACTION_UP == event.getAction()) {
_speedUp = false;
}
Log.d("foo", "speedUp " + _speedUp);
return false;
}
});
downButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
_speedDown = true;
}
if (MotionEvent.ACTION_UP == event.getAction()) {
_speedDown = false;
}
Log.d("foo", "speedDown " + _speedDown);
return false;
}
});
leftButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
_steerLeft = true;
}
if (MotionEvent.ACTION_UP == event.getAction()) {
_steerLeft = false;
}
Log.d("foo", "steerLeft " + _steerLeft);
return false;
}
});
rightButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
_steerRight = true;
}
if (MotionEvent.ACTION_UP == event.getAction()) {
_steerRight = false;
}
Log.d("foo", "steerRight " + _steerRight);
return false;
}
});
/* End of: ChooseControls */
// hide SystemUi
_systemUiHider = new SystemUiHiderAndroidRacer(this, _standardControlsView, SystemUiHider.FLAG_FULLSCREEN);
_systemUiHider.setup();
_systemUiHider.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
@Override
public void onVisibilityChange(boolean visible) {
Log.d("foo", "onVisibilityChange: visible? " + visible);
}
});
_systemUiHider.hide();
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game);
// get all views
_chooseControlsView = findViewById(R.id.choose_controls);
_standardControlsView = findViewById(R.id.standard_controls);
_motionSensorControlsView = findViewById(R.id.motion_sensor_controls);
// get the 'motion sensor' image view.
// a circle and the current 'motion position' will be drawn onto this view.
_msCtrlImgView = (ImageView) findViewById(R.id.ms_ctrl_img_view);
// set other views than 'chooseControlsView' invisible
_standardControlsView.setVisibility(View.INVISIBLE);
_motionSensorControlsView.setVisibility(View.INVISIBLE);
// possible threads
_threads = new LinkedList<PlayGameActivity.ThreadControlMode>();
_threads.add(new ThreadControlMode(ControlMode.STANDARD, new StandardControlThread()));
_threads.add(new ThreadControlMode(ControlMode.SENSOR, new MotionSensorControlThread()));
/* ChooseControls */
// Choose 'Standard controls'
final Button stdCtrlButton = (Button) findViewById(R.id.std_ctrl);
stdCtrlButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ready(ControlMode.STANDARD);
}
});
// Choose 'Motion Sensor'
final Button msCtrlButton = (Button) findViewById(R.id.ms_ctrl);
msCtrlButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ready(ControlMode.SENSOR);
}
});
final Button upButton = (Button) findViewById(R.id.std_ctrl_up);
final Button downButton = (Button) findViewById(R.id.std_ctrl_down);
final Button leftButton = (Button) findViewById(R.id.std_ctrl_left);
final Button rightButton = (Button) findViewById(R.id.std_ctrl_right);
upButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
_speedUp = true;
}
if (MotionEvent.ACTION_UP == event.getAction()) {
_speedUp = false;
}
Log.d("control", "speedUp " + _speedUp);
return true;
}
});
downButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
_speedDown = true;
}
if (MotionEvent.ACTION_UP == event.getAction()) {
_speedDown = false;
}
Log.d("control", "speedDown " + _speedDown);
return true;
}
});
leftButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
_steerLeft = true;
}
if (MotionEvent.ACTION_UP == event.getAction()) {
_steerLeft = false;
}
Log.d("control", "steerLeft " + _steerLeft);
return true;
}
});
rightButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
_steerRight = true;
}
if (MotionEvent.ACTION_UP == event.getAction()) {
_steerRight = false;
}
Log.d("control", "steerRight " + _steerRight);
return true;
}
});
/* End of: ChooseControls */
// hide SystemUi
_systemUiHider = new SystemUiHiderAndroidRacer(this, _standardControlsView, SystemUiHider.FLAG_FULLSCREEN);
_systemUiHider.setup();
_systemUiHider.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
@Override
public void onVisibilityChange(boolean visible) {
Log.d("foo", "onVisibilityChange: visible? " + visible);
}
});
_systemUiHider.hide();
}
|
diff --git a/melete-util/src/java/org/etudes/basiclti/SakaiBLTIUtil.java b/melete-util/src/java/org/etudes/basiclti/SakaiBLTIUtil.java
index f92154b6..4ccfcb46 100644
--- a/melete-util/src/java/org/etudes/basiclti/SakaiBLTIUtil.java
+++ b/melete-util/src/java/org/etudes/basiclti/SakaiBLTIUtil.java
@@ -1,385 +1,385 @@
/**********************************************************************************
* $URL$
* $Id$
**********************************************************************************
*
* Copyright (c) 2008, 2009 Etudes, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
**********************************************************************************/
package org.etudes.basiclti;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.net.URL;
import org.imsglobal.basiclti.BasicLTIUtil;
import org.etudes.linktool.LinkToolUtil;
// Sakai APIs
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.tool.api.Placement;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SitePage;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.tool.api.ActiveTool;
import org.sakaiproject.tool.cover.ActiveToolManager;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.util.ResourceLoader;
/**
* Some Sakai Utility code for IMS Basic LTI
* This is mostly code to support the Sakai conventions for
* making and launching BLTI resources within Sakai.
*/
public class SakaiBLTIUtil {
private static Log M_log = LogFactory.getLog(SakaiBLTIUtil.class);
public static void dPrint(String str)
{
// M_log.warn(str)
}
// Look at a Placement and come up with the launch urls, and
// other launch parameters to drive the launch.
public static boolean loadFromPlacement(Properties info, Properties launch, Placement placement)
{
Properties config = placement.getConfig();
dPrint("Sakai properties=" + config);
String launch_url = toNull(config.getProperty("imsti.launch", null));
setProperty(info, "launch_url", launch_url);
if ( launch_url == null ) {
String xml = toNull(config.getProperty("imsti.xml", null));
if ( xml == null ) return false;
BasicLTIUtil.parseDescriptor(info, launch, xml);
}
setProperty(info, "secret", config.getProperty("imsti.secret", null) );
setProperty(info, "key", config.getProperty("imsti.key", null) );
setProperty(info, "debug", config.getProperty("imsti.debug", null) );
setProperty(info, "frameheight", config.getProperty("imsti.frameheight", null) );
setProperty(info, "newwindow", config.getProperty("imsti.newwindow", null) );
setProperty(info, "title", config.getProperty("imsti.tooltitle", null) );
if ( info.getProperty("launch_url", null) != null ||
info.getProperty("secure_launch_url", null) != null ) {
return true;
}
return false;
}
public static boolean sakaiInfo(Properties props, Placement placement)
{
dPrint("placement="+ placement.getId());
dPrint("placement title=" + placement.getTitle());
String context = placement.getContext();
dPrint("ContextID="+context);
return sakaiInfo(props, context, placement.getId());
}
// Retrieve the Sakai information about users, etc.
public static boolean sakaiInfo(Properties props, String context, String placementId)
{
Site site = null;
try {
site = SiteService.getSite(context);
} catch (Exception e) {
dPrint("No site/page associated with Launch context="+context);
return false;
}
User user = UserDirectoryService.getCurrentUser();
// Start setting the Basici LTI parameters
setProperty(props,"resource_link_id",placementId);
// TODO: Think about anonymus
if ( user != null )
{
setProperty(props,"user_id",user.getId());
- setProperty(props,"launch_presentaion_locale","en_US"); // TODO: Really get this
+ setProperty(props,"launch_presentation_locale","en_US"); // TODO: Really get this
setProperty(props,"lis_person_name_given",user.getFirstName());
setProperty(props,"lis_person_name_family",user.getLastName());
setProperty(props,"lis_person_name_full",user.getDisplayName());
- setProperty(props,"lis_person_contact_emailprimary",user.getEmail());
+ setProperty(props,"lis_person_contact_email_primary",user.getEmail());
setProperty(props,"lis_person_sourcedid",user.getEid());
}
String theRole = "Learner";
if ( SecurityService.isSuperUser() )
{
theRole = "Instructor";
}
else if ( SiteService.allowUpdateSite(context) )
{
theRole = "Instructor";
}
setProperty(props,"roles",theRole);
if ( site != null ) {
String context_type = site.getType();
if ( context_type != null && context_type.toLowerCase().contains("course") ){
setProperty(props,"context_type","CourseOffering");
}
setProperty(props,"context_id",site.getId());
+ setProperty(props,"context_label",site.getTitle());
setProperty(props,"context_title",site.getTitle());
- setProperty(props,"course_name",site.getShortDescription());
String courseRoster = getExternalRealmId(site.getId());
if ( courseRoster != null )
{
setProperty(props,"lis_course_offering_sourced_id",courseRoster);
}
}
// Sakai-Unique fields - compatible with LinkTool
Session s = SessionManager.getCurrentSession();
if (s != null) {
String sessionid = s.getId();
if (sessionid != null) {
sessionid = LinkToolUtil.encrypt(sessionid);
setProperty(props,"sakai_session",sessionid);
}
}
// We pass this along in the Sakai world - it might
// might be useful to the external tool
String serverId = ServerConfigurationService.getServerId();
setProperty(props,"sakai_serverid",serverId);
setProperty(props,"sakai_server",getOurServerUrl());
// Get the organizational information
setProperty(props,"tool_consmer_instance_guid", ServerConfigurationService.getString("basiclti.consumer_instance_guid",null));
setProperty(props,"tool_consmer_instance_name", ServerConfigurationService.getString("basiclti.consumer_instance_name",null));
setProperty(props,"tool_consmer_instance_url", ServerConfigurationService.getString("basiclti.consumer_instance_url",null));
setProperty(props,"launch_presentation_return_url", ServerConfigurationService.getString("basiclti.consumer_return_url",null));
return true;
}
// getProperty(String name);
// Gnerate HTML from a descriptor and properties from
public static String[] postLaunchHTML(String descriptor, String contextId, String resourceId, ResourceProperties props, ResourceLoader rb)
{
if ( descriptor == null || contextId == null || resourceId == null )
return postError("<p>" + getRB(rb, "error.descriptor" ,"Error, missing contextId, resourceid or descriptor")+"</p>" );
// Add user, course, etc to the launch parameters
Properties launch = new Properties();
if ( ! sakaiInfo(launch, contextId, resourceId) ) {
return postError("<p>" + getRB(rb, "error.info.resource",
"Error, cannot load Sakai information for resource=")+resourceId+".</p>");
}
Properties info = new Properties();
if ( ! BasicLTIUtil.parseDescriptor(info, launch, descriptor) ) {
return postError("<p>" + getRB(rb, "error.badxml.resource",
"Error, cannot parse descriptor for resource=")+resourceId+".</p>");
}
return postLaunchHTML(info, launch, rb);
}
// This must return an HTML message as the [0] in the array
// If things are successful - the launch URL is in [1]
public static String[] postLaunchHTML(String placementId, ResourceLoader rb)
{
if ( placementId == null ) return postError("<p>" + getRB(rb, "error.missing" ,"Error, missing placementId")+"</p>" );
ToolConfiguration placement = SiteService.findTool(placementId);
if ( placement == null ) return postError("<p>" + getRB(rb, "error.load" ,"Error, cannot load placement=")+placementId+".</p>");
// Add user, course, etc to the launch parameters
Properties launch = new Properties();
if ( ! sakaiInfo(launch, placement) ) {
return postError("<p>" + getRB(rb, "error.missing",
"Error, cannot load Sakai information for placement=")+placementId+".</p>");
}
// Retrieve the launch detail
Properties info = new Properties();
if ( ! loadFromPlacement(info, launch, placement) ) {
return postError("<p>" + getRB(rb, "error.nolaunch" ,"Not Configured.")+"</p>");
}
return postLaunchHTML(info, launch, rb);
}
public static String[] postLaunchHTML(Properties info, Properties launch, ResourceLoader rb)
{
String launch_url = info.getProperty("secure_launch_url");
if ( launch_url == null ) launch_url = info.getProperty("launch_url");
if ( launch_url == null ) return postError("<p>" + getRB(rb, "error.missing" ,"Not configured")+"</p>");
String org_guid = ServerConfigurationService.getString("basiclti.consumer_instance_guid",null);
String org_name = ServerConfigurationService.getString("basiclti.consumer_instance_name",null);
String org_url = ServerConfigurationService.getString("basiclti.consumer_instance_url",null);
// Look up the LMS-wide secret and key - default key is guid
String key = getToolConsumerInfo(launch_url,"key");
if ( key == null ) key = org_guid;
String secret = getToolConsumerInfo(launch_url,"secret");
// Demand LMS-wide key/secret to be both or none
if ( key == null || secret == null ) {
key = null;
secret = null;
}
// If we do not have LMS-wide info, use the local key/secret
if ( secret == null ) {
secret = toNull(info.getProperty("secret"));
key = toNull(info.getProperty("key"));
}
// Pull in all of the custom parameters
for(Object okey : info.keySet() ) {
String skey = (String) okey;
if ( ! skey.startsWith("custom_") ) continue;
String value = info.getProperty(skey);
if ( value == null ) continue;
setProperty(launch, skey, value);
}
String oauth_callback = ServerConfigurationService.getString("basiclti.oauth_callback",null);
// Too bad there is not a better default callback url for OAuth
// Actually since we are using signing-only, there is really not much point
// In OAuth 6.2.3, this is after the user is authorized
if ( oauth_callback == null ) oauth_callback = "about:blank";
setProperty(launch, "oauth_callback", oauth_callback);
setProperty(launch, BasicLTIUtil.BASICLTI_SUBMIT, getRB(rb, "launch.button", "Press to Launch External Tool"));
// Sanity checks
if ( secret == null ) {
return postError("<p>" + getRB(rb, "error.nosecret", "Error - must have a secret.")+"</p>");
}
if ( secret != null && key == null ){
return postError("<p>" + getRB(rb, "error.nokey", "Error - must have a secret and a key.")+"</p>");
}
launch = BasicLTIUtil.signProperties(launch, launch_url, "POST",
key, secret, org_guid, org_name, org_url);
if ( launch == null ) return postError("<p>" + getRB(rb, "error.sign", "Error signing message.")+"</p>");
dPrint("LAUNCH III="+launch);
boolean dodebug = toNull(info.getProperty("debug")) != null;
String postData = BasicLTIUtil.postLaunchHTML(launch, launch_url, dodebug);
String [] retval = { postData, launch_url };
return retval;
}
public static String[] postError(String str) {
String [] retval = { str };
return retval;
}
public static String getRB(ResourceLoader rb, String key, String def)
{
if ( rb == null ) return def;
return rb.getString(key, def);
}
public static void setProperty(Properties props, String key, String value)
{
if ( value == null ) return;
if ( value.trim().length() < 1 ) return;
props.setProperty(key, value);
}
private static String getContext()
{
String retval = ToolManager.getCurrentPlacement().getContext();
return retval;
}
private static String getExternalRealmId(String siteId) {
String realmId = SiteService.siteReference(siteId);
String rv = null;
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
rv = realm.getProviderGroupId();
} catch (GroupNotDefinedException e) {
dPrint("SiteParticipantHelper.getExternalRealmId: site realm not found"+e.getMessage());
}
return rv;
} // getExternalRealmId
// Look through a series of secrets from the properties based on the launchUrl
private static String getToolConsumerInfo(String launchUrl, String data)
{
String default_secret = ServerConfigurationService.getString("basiclti.consumer_instance_"+data,null);
dPrint("launchUrl = "+launchUrl);
URL url = null;
try {
url = new URL(launchUrl);
}
catch (Exception e) {
url = null;
}
if ( url == null ) return default_secret;
String hostName = url.getHost();
dPrint("host = "+hostName);
if ( hostName == null || hostName.length() < 1 ) return default_secret;
// Look for the property starting with the full name
String org_info = ServerConfigurationService.getString("basiclti.consumer_instance_"+data+"."+hostName,null);
if ( org_info != null ) return org_info;
for ( int i = 0; i < hostName.length(); i++ ) {
if ( hostName.charAt(i) != '.' ) continue;
if ( i > hostName.length()-2 ) continue;
String hostPart = hostName.substring(i+1);
String propName = "basiclti.consumer_instance_"+data+"."+hostPart;
org_info = ServerConfigurationService.getString(propName,null);
if ( org_info != null ) return org_info;
}
return default_secret;
}
static private String getOurServerUrl() {
String ourUrl = ServerConfigurationService.getString("sakai.rutgers.linktool.serverUrl");
if (ourUrl == null || ourUrl.equals(""))
ourUrl = ServerConfigurationService.getServerUrl();
if (ourUrl == null || ourUrl.equals(""))
ourUrl = "http://127.0.0.1:8080";
return ourUrl;
}
public static String toNull(String str)
{
if ( str == null ) return null;
if ( str.trim().length() < 1 ) return null;
return str;
}
}
| false | true | public static boolean sakaiInfo(Properties props, String context, String placementId)
{
Site site = null;
try {
site = SiteService.getSite(context);
} catch (Exception e) {
dPrint("No site/page associated with Launch context="+context);
return false;
}
User user = UserDirectoryService.getCurrentUser();
// Start setting the Basici LTI parameters
setProperty(props,"resource_link_id",placementId);
// TODO: Think about anonymus
if ( user != null )
{
setProperty(props,"user_id",user.getId());
setProperty(props,"launch_presentaion_locale","en_US"); // TODO: Really get this
setProperty(props,"lis_person_name_given",user.getFirstName());
setProperty(props,"lis_person_name_family",user.getLastName());
setProperty(props,"lis_person_name_full",user.getDisplayName());
setProperty(props,"lis_person_contact_emailprimary",user.getEmail());
setProperty(props,"lis_person_sourcedid",user.getEid());
}
String theRole = "Learner";
if ( SecurityService.isSuperUser() )
{
theRole = "Instructor";
}
else if ( SiteService.allowUpdateSite(context) )
{
theRole = "Instructor";
}
setProperty(props,"roles",theRole);
if ( site != null ) {
String context_type = site.getType();
if ( context_type != null && context_type.toLowerCase().contains("course") ){
setProperty(props,"context_type","CourseOffering");
}
setProperty(props,"context_id",site.getId());
setProperty(props,"context_title",site.getTitle());
setProperty(props,"course_name",site.getShortDescription());
String courseRoster = getExternalRealmId(site.getId());
if ( courseRoster != null )
{
setProperty(props,"lis_course_offering_sourced_id",courseRoster);
}
}
// Sakai-Unique fields - compatible with LinkTool
Session s = SessionManager.getCurrentSession();
if (s != null) {
String sessionid = s.getId();
if (sessionid != null) {
sessionid = LinkToolUtil.encrypt(sessionid);
setProperty(props,"sakai_session",sessionid);
}
}
// We pass this along in the Sakai world - it might
// might be useful to the external tool
String serverId = ServerConfigurationService.getServerId();
setProperty(props,"sakai_serverid",serverId);
setProperty(props,"sakai_server",getOurServerUrl());
// Get the organizational information
setProperty(props,"tool_consmer_instance_guid", ServerConfigurationService.getString("basiclti.consumer_instance_guid",null));
setProperty(props,"tool_consmer_instance_name", ServerConfigurationService.getString("basiclti.consumer_instance_name",null));
setProperty(props,"tool_consmer_instance_url", ServerConfigurationService.getString("basiclti.consumer_instance_url",null));
setProperty(props,"launch_presentation_return_url", ServerConfigurationService.getString("basiclti.consumer_return_url",null));
return true;
}
| public static boolean sakaiInfo(Properties props, String context, String placementId)
{
Site site = null;
try {
site = SiteService.getSite(context);
} catch (Exception e) {
dPrint("No site/page associated with Launch context="+context);
return false;
}
User user = UserDirectoryService.getCurrentUser();
// Start setting the Basici LTI parameters
setProperty(props,"resource_link_id",placementId);
// TODO: Think about anonymus
if ( user != null )
{
setProperty(props,"user_id",user.getId());
setProperty(props,"launch_presentation_locale","en_US"); // TODO: Really get this
setProperty(props,"lis_person_name_given",user.getFirstName());
setProperty(props,"lis_person_name_family",user.getLastName());
setProperty(props,"lis_person_name_full",user.getDisplayName());
setProperty(props,"lis_person_contact_email_primary",user.getEmail());
setProperty(props,"lis_person_sourcedid",user.getEid());
}
String theRole = "Learner";
if ( SecurityService.isSuperUser() )
{
theRole = "Instructor";
}
else if ( SiteService.allowUpdateSite(context) )
{
theRole = "Instructor";
}
setProperty(props,"roles",theRole);
if ( site != null ) {
String context_type = site.getType();
if ( context_type != null && context_type.toLowerCase().contains("course") ){
setProperty(props,"context_type","CourseOffering");
}
setProperty(props,"context_id",site.getId());
setProperty(props,"context_label",site.getTitle());
setProperty(props,"context_title",site.getTitle());
String courseRoster = getExternalRealmId(site.getId());
if ( courseRoster != null )
{
setProperty(props,"lis_course_offering_sourced_id",courseRoster);
}
}
// Sakai-Unique fields - compatible with LinkTool
Session s = SessionManager.getCurrentSession();
if (s != null) {
String sessionid = s.getId();
if (sessionid != null) {
sessionid = LinkToolUtil.encrypt(sessionid);
setProperty(props,"sakai_session",sessionid);
}
}
// We pass this along in the Sakai world - it might
// might be useful to the external tool
String serverId = ServerConfigurationService.getServerId();
setProperty(props,"sakai_serverid",serverId);
setProperty(props,"sakai_server",getOurServerUrl());
// Get the organizational information
setProperty(props,"tool_consmer_instance_guid", ServerConfigurationService.getString("basiclti.consumer_instance_guid",null));
setProperty(props,"tool_consmer_instance_name", ServerConfigurationService.getString("basiclti.consumer_instance_name",null));
setProperty(props,"tool_consmer_instance_url", ServerConfigurationService.getString("basiclti.consumer_instance_url",null));
setProperty(props,"launch_presentation_return_url", ServerConfigurationService.getString("basiclti.consumer_return_url",null));
return true;
}
|
diff --git a/src/java/com/eviware/soapui/impl/wsdl/teststeps/assertions/AbstractTestAssertionFactory.java b/src/java/com/eviware/soapui/impl/wsdl/teststeps/assertions/AbstractTestAssertionFactory.java
index 160b731ca..975eeb539 100644
--- a/src/java/com/eviware/soapui/impl/wsdl/teststeps/assertions/AbstractTestAssertionFactory.java
+++ b/src/java/com/eviware/soapui/impl/wsdl/teststeps/assertions/AbstractTestAssertionFactory.java
@@ -1,94 +1,94 @@
/*
* soapUI, copyright (C) 2004-2008 eviware.com
*
* soapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details at gnu.org.
*/
package com.eviware.soapui.impl.wsdl.teststeps.assertions;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.List;
import com.eviware.soapui.config.RequestAssertionConfig;
import com.eviware.soapui.impl.wsdl.teststeps.assertions.WsdlAssertionRegistry.AssertableType;
import com.eviware.soapui.model.ModelItem;
import com.eviware.soapui.model.testsuite.Assertable;
import com.eviware.soapui.model.testsuite.TestAssertion;
public abstract class AbstractTestAssertionFactory implements TestAssertionFactory
{
private final String id;
private final String label;
private final Class<? extends TestAssertion> assertionClass;
private final Class<? extends ModelItem> targetClass;
public AbstractTestAssertionFactory( String id, String label, Class<? extends TestAssertion> assertionClass )
{
this.id = id;
this.label = label;
this.assertionClass = assertionClass;
targetClass = null;
}
public AbstractTestAssertionFactory( String id, String label, Class<? extends TestAssertion> assertionClass, Class<? extends ModelItem> targetClass )
{
this.id = id;
this.label = label;
this.assertionClass = assertionClass;
this.targetClass = targetClass;
}
public String getAssertionId()
{
return id;
}
public String getAssertionLabel()
{
return label;
}
@SuppressWarnings("deprecation")
public boolean canAssert( Assertable assertable )
{
- List<Class<?>> classes = Arrays.asList(assertable.getClass().getClasses());
+ List<Class> classes = Arrays.asList(assertable.getClass().getClasses());
if( targetClass != null && !classes.contains(targetClass))
return false;
if( assertable.getAssertableType() == AssertableType.BOTH )
return true;
if(assertable.getAssertableType() == AssertableType.REQUEST && classes.contains( RequestAssertion.class ))
return true;
else if(assertable.getAssertableType() == AssertableType.RESPONSE && classes.contains( ResponseAssertion.class ))
return true;
return false;
}
public TestAssertion buildAssertion(RequestAssertionConfig config, Assertable assertable)
{
try
{
Constructor<? extends TestAssertion> ctor = assertionClass
.getConstructor(new Class[] { RequestAssertionConfig.class,
Assertable.class });
return ctor.newInstance(config, assertable);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
| true | true | public boolean canAssert( Assertable assertable )
{
List<Class<?>> classes = Arrays.asList(assertable.getClass().getClasses());
if( targetClass != null && !classes.contains(targetClass))
return false;
if( assertable.getAssertableType() == AssertableType.BOTH )
return true;
if(assertable.getAssertableType() == AssertableType.REQUEST && classes.contains( RequestAssertion.class ))
return true;
else if(assertable.getAssertableType() == AssertableType.RESPONSE && classes.contains( ResponseAssertion.class ))
return true;
return false;
}
| public boolean canAssert( Assertable assertable )
{
List<Class> classes = Arrays.asList(assertable.getClass().getClasses());
if( targetClass != null && !classes.contains(targetClass))
return false;
if( assertable.getAssertableType() == AssertableType.BOTH )
return true;
if(assertable.getAssertableType() == AssertableType.REQUEST && classes.contains( RequestAssertion.class ))
return true;
else if(assertable.getAssertableType() == AssertableType.RESPONSE && classes.contains( ResponseAssertion.class ))
return true;
return false;
}
|
diff --git a/src/test/java/org/jboss/aerogear/unifiedpush/message/UnifiedMessageTest.java b/src/test/java/org/jboss/aerogear/unifiedpush/message/UnifiedMessageTest.java
index 7172e2e..e49b1eb 100644
--- a/src/test/java/org/jboss/aerogear/unifiedpush/message/UnifiedMessageTest.java
+++ b/src/test/java/org/jboss/aerogear/unifiedpush/message/UnifiedMessageTest.java
@@ -1,111 +1,111 @@
/**
* JBoss, Home of Professional Open Source
* Copyright Red Hat, Inc., and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.aerogear.unifiedpush.message;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class UnifiedMessageTest {
@Test
public void simpleBroadcastMessageTest() {
UnifiedMessage unifiedMessage = new UnifiedMessage.Builder()
.pushApplicationId("c7fc6525-5506-4ca9-9cf1-55cc261ddb9c")
.masterSecret("8b2f43a9-23c8-44fe-bee9-d6b0af9e316b")
.attribute("custom","customValue")
.build();
assertEquals("c7fc6525-5506-4ca9-9cf1-55cc261ddb9c", unifiedMessage.getPushApplicationId());
assertEquals("8b2f43a9-23c8-44fe-bee9-d6b0af9e316b",unifiedMessage.getMasterSecret());
- assertEquals("customValue",unifiedMessage.getAttributes().get("customValue"));
+ assertEquals("customValue",unifiedMessage.getAttributes().get("custom"));
}
@Test
public void specialKeysTests() {
UnifiedMessage unifiedMessage = new UnifiedMessage.Builder()
.alert("Hello from Java Sender API, via JUnit")
.sound("default")
.badge("badge")
.build();
assertEquals("Hello from Java Sender API, via JUnit",unifiedMessage.getAttributes().get("alert"));
assertEquals("default",unifiedMessage.getAttributes().get("sound"));
assertEquals("badge",unifiedMessage.getAttributes().get("badge"));
}
@Test
public void simpleSelectiveMessageWithAliasesTest() {
List aliases = new ArrayList<String>();
aliases.add("mike");
UnifiedMessage unifiedMessage = new UnifiedMessage.Builder()
.aliases(aliases)
.build();
assertEquals(1,unifiedMessage.getAliases().size());
}
@Test
public void simpleSelectiveMessageWithDevicesTest() {
List devices = new ArrayList<String>();
devices.add("iPad");
UnifiedMessage unifiedMessage = new UnifiedMessage.Builder()
.deviceType(devices)
.build();
assertEquals(1,unifiedMessage.getDeviceType().size());
}
@Test
public void simplePushBroadcastMessageTest() {
UnifiedMessage unifiedMessage = new UnifiedMessage.Builder()
.simplePush("version=1")
.build();
assertEquals("version=1",unifiedMessage.getAttributes().get("simple-push"));
}
@Test
public void simplePushBroadcastWrongVersionFormatMessageTest() {
UnifiedMessage unifiedMessage = new UnifiedMessage.Builder()
.simplePush("2")
.build();
assertEquals("version=2",unifiedMessage.getAttributes().get("simple-push"));
}
@Test
public void simplePushSelectiveVersionMessageTest() {
Map<String, String> simplePush = new HashMap<String, String>();
simplePush.put("channel1","version=1");
UnifiedMessage unifiedMessage = new UnifiedMessage.Builder()
.simplePush(simplePush)
.build();
assertEquals("version=1", ((Map)unifiedMessage.getAttributes().get("simple-push")).get("channel1"));
}
@Test
public void simplePushSelectiveWrongVersionFormatMessageTest() {
Map<String, String> simplePush = new HashMap<String, String>();
simplePush.put("channel1","1");
UnifiedMessage unifiedMessage = new UnifiedMessage.Builder()
.simplePush(simplePush)
.build();
assertEquals("version=1", ((Map)unifiedMessage.getAttributes().get("simple-push")).get("channel1"));
}
}
| true | true | public void simpleBroadcastMessageTest() {
UnifiedMessage unifiedMessage = new UnifiedMessage.Builder()
.pushApplicationId("c7fc6525-5506-4ca9-9cf1-55cc261ddb9c")
.masterSecret("8b2f43a9-23c8-44fe-bee9-d6b0af9e316b")
.attribute("custom","customValue")
.build();
assertEquals("c7fc6525-5506-4ca9-9cf1-55cc261ddb9c", unifiedMessage.getPushApplicationId());
assertEquals("8b2f43a9-23c8-44fe-bee9-d6b0af9e316b",unifiedMessage.getMasterSecret());
assertEquals("customValue",unifiedMessage.getAttributes().get("customValue"));
}
| public void simpleBroadcastMessageTest() {
UnifiedMessage unifiedMessage = new UnifiedMessage.Builder()
.pushApplicationId("c7fc6525-5506-4ca9-9cf1-55cc261ddb9c")
.masterSecret("8b2f43a9-23c8-44fe-bee9-d6b0af9e316b")
.attribute("custom","customValue")
.build();
assertEquals("c7fc6525-5506-4ca9-9cf1-55cc261ddb9c", unifiedMessage.getPushApplicationId());
assertEquals("8b2f43a9-23c8-44fe-bee9-d6b0af9e316b",unifiedMessage.getMasterSecret());
assertEquals("customValue",unifiedMessage.getAttributes().get("custom"));
}
|
diff --git a/src/pt/webdetails/cda/CdaContentGenerator.java b/src/pt/webdetails/cda/CdaContentGenerator.java
index 034e700d..bfdf66c5 100644
--- a/src/pt/webdetails/cda/CdaContentGenerator.java
+++ b/src/pt/webdetails/cda/CdaContentGenerator.java
@@ -1,209 +1,209 @@
package pt.webdetails.cda;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.platform.api.engine.IParameterProvider;
import org.pentaho.platform.api.repository.IContentItem;
import org.pentaho.platform.engine.core.solution.ActionInfo;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.platform.engine.services.solution.BaseContentGenerator;
import pt.webdetails.cda.discovery.DiscoveryOptions;
import pt.webdetails.cda.query.QueryOptions;
import pt.webdetails.cda.settings.CdaSettings;
import pt.webdetails.cda.settings.SettingsManager;
@SuppressWarnings("unchecked")
public class CdaContentGenerator extends BaseContentGenerator
{
private static Log logger = LogFactory.getLog(CdaContentGenerator.class);
public static final String PLUGIN_NAME = "pentaho-cda";
private static final long serialVersionUID = 1L;
private static final String MIME_TYPE = "text/html";
private static final int DEFAULT_PAGE_SIZE = 20;
private static final int DEFAULT_START_PAGE = 0;
public CdaContentGenerator()
{
}
@Override
public void createContent() throws Exception
{
final IParameterProvider pathParams = parameterProviders.get("path");
final IParameterProvider requestParams = parameterProviders.get("request");
final IContentItem contentItem = outputHandler.getOutputContentItem("response", "content", "", instanceId, MIME_TYPE);
final OutputStream out = contentItem.getOutputStream(null);
try
{
final Class[] params = {IParameterProvider.class, OutputStream.class};
final String method = pathParams.getStringParameter("path", null).replace("/", "").toLowerCase();
try
{
final Method mthd = this.getClass().getMethod(method, params);
mthd.invoke(this, requestParams, out);
}
catch (NoSuchMethodException e)
{
logger.error(Messages.getErrorString("DashboardDesignerContentGenerator.ERROR_001_INVALID_METHOD_EXCEPTION") + " : " + method);
}
}
catch (Exception e)
{
final String message = e.getCause() != null ? e.getCause().getClass().getName() + " - " + e.getCause().getMessage() : e.getClass().getName() + " - " + e.getMessage();
logger.error(message);
}
}
public void doquery(final IParameterProvider pathParams, final OutputStream out) throws Exception
{
final CdaEngine engine = CdaEngine.getInstance();
final QueryOptions queryOptions = new QueryOptions();
- final CdaSettings cdaSettings = SettingsManager.getInstance().parseSettingsFile(getRelativePath(pathParams));
+ final CdaSettings cdaSettings = SettingsManager.getInstance().parseSettingsFile(PentahoSystem.getApplicationContext().getSolutionPath(getRelativePath(pathParams)));
// Handle paging options
// We assume that any paging options found mean that the user actively wants paging.
final long pageSize = pathParams.getLongParameter("pageSize", 0);
final long pageStart = pathParams.getLongParameter("pageStart", 0);
final boolean paginate = pathParams.getStringParameter("paginate", "false").equals("true") ? true : false;
if (pageSize > 0 || pageStart > 0 || paginate)
{
if (pageSize > Integer.MAX_VALUE || pageStart > Integer.MAX_VALUE)
{
throw new ArithmeticException("Paging values too large");
}
queryOptions.setPaginate(true);
queryOptions.setPageSize(pageSize > 0 ? (int) pageSize : paginate ? DEFAULT_PAGE_SIZE : 0);
queryOptions.setPageStart(pageStart > 0 ? (int) pageStart : paginate ? DEFAULT_START_PAGE : 0);
}
// Handle the query itself and its output format...
queryOptions.setOutputType(pathParams.getStringParameter("outputType", "json"));
queryOptions.setDataAccessId(pathParams.getStringParameter("dataAccessId", "<blank>"));
final ArrayList<Integer> sortBy = new ArrayList<Integer>();
// Integer[] def = {};
// for (Object obj : pathParams.getArrayParameter("sortBy", def)) {
// sortBy.add(Integer.parseInt((String) obj));
// }
// queryOptions.setSortBy(sortBy);
if (pathParams.getStringParameter("sortBy", null) != null)
{
logger.warn("sortBy not implemented yet");
}
// ... and the query parameters
// We identify any pathParams starting with "param" as query parameters
final Iterator<String> params = (Iterator<String>) pathParams.getParameterNames();
while (params.hasNext())
{
final String param = params.next();
if (param.startsWith("param"))
{
queryOptions.addParameter(param.substring(5), pathParams.getStringParameter(param, ""));
}
}
// Finally, pass the query to the engine
engine.doQuery(out, cdaSettings, queryOptions);
}
public void listqueries(final IParameterProvider pathParams, final OutputStream out) throws Exception
{
final CdaEngine engine = CdaEngine.getInstance();
final String path = PentahoSystem.getApplicationContext().getSolutionPath(getRelativePath(pathParams)).replaceAll("//+", "/");
// final ISolutionRepository solutionRepository = PentahoSystem.get(ISolutionRepository.class, userSession);
final CdaSettings cdaSettings = SettingsManager.getInstance().parseSettingsFile(path);
// Handle the query itself and its output format...
final DiscoveryOptions discoveryOptions = new DiscoveryOptions();
discoveryOptions.setOutputType(pathParams.getStringParameter("outputType", "json"));
engine.listQueries(out, cdaSettings, discoveryOptions);
}
public void listparameters(final IParameterProvider pathParams, final OutputStream out) throws Exception
{
final CdaEngine engine = CdaEngine.getInstance();
final DiscoveryOptions discoveryOptions = new DiscoveryOptions();
final String path = PentahoSystem.getApplicationContext().getSolutionPath(getRelativePath(pathParams)).replaceAll("//+", "/");
// final ISolutionRepository solutionRepository = PentahoSystem.get(ISolutionRepository.class, userSession);
final CdaSettings cdaSettings = SettingsManager.getInstance().parseSettingsFile(path);
discoveryOptions.setDataAccessId(pathParams.getStringParameter("dataAccessId", "<blank>"));
discoveryOptions.setOutputType(pathParams.getStringParameter("outputType", "json"));
engine.listParameters(out, cdaSettings, discoveryOptions);
}
public void getcdalist(final IParameterProvider pathParams, final OutputStream out) throws Exception
{
final CdaEngine engine = CdaEngine.getInstance();
final DiscoveryOptions discoveryOptions = new DiscoveryOptions();
discoveryOptions.setOutputType(pathParams.getStringParameter("outputType", "json"));
engine.getCdaList(out, discoveryOptions, userSession);
}
public void clearcache(final IParameterProvider pathParams, final OutputStream out) throws Exception
{
SettingsManager.getInstance().clearCache();
}
public void syncronize(final IParameterProvider pathParams, final OutputStream out) throws Exception
{
throw new UnsupportedOperationException("Feature not implemented yet");
// final SyncronizeCdfStructure syncCdfStructure = new SyncronizeCdfStructure();
// syncCdfStructure.syncronize(userSession, out, pathParams);
}
@Override
public Log getLogger()
{
return logger;
}
private String getRelativePath(final IParameterProvider pathParams)
{
return ActionInfo.buildSolutionPath(
pathParams.getStringParameter("solution", ""),
pathParams.getStringParameter("path", ""),
pathParams.getStringParameter("file", ""));
}
}
| true | true | public void doquery(final IParameterProvider pathParams, final OutputStream out) throws Exception
{
final CdaEngine engine = CdaEngine.getInstance();
final QueryOptions queryOptions = new QueryOptions();
final CdaSettings cdaSettings = SettingsManager.getInstance().parseSettingsFile(getRelativePath(pathParams));
// Handle paging options
// We assume that any paging options found mean that the user actively wants paging.
final long pageSize = pathParams.getLongParameter("pageSize", 0);
final long pageStart = pathParams.getLongParameter("pageStart", 0);
final boolean paginate = pathParams.getStringParameter("paginate", "false").equals("true") ? true : false;
if (pageSize > 0 || pageStart > 0 || paginate)
{
if (pageSize > Integer.MAX_VALUE || pageStart > Integer.MAX_VALUE)
{
throw new ArithmeticException("Paging values too large");
}
queryOptions.setPaginate(true);
queryOptions.setPageSize(pageSize > 0 ? (int) pageSize : paginate ? DEFAULT_PAGE_SIZE : 0);
queryOptions.setPageStart(pageStart > 0 ? (int) pageStart : paginate ? DEFAULT_START_PAGE : 0);
}
// Handle the query itself and its output format...
queryOptions.setOutputType(pathParams.getStringParameter("outputType", "json"));
queryOptions.setDataAccessId(pathParams.getStringParameter("dataAccessId", "<blank>"));
final ArrayList<Integer> sortBy = new ArrayList<Integer>();
// Integer[] def = {};
// for (Object obj : pathParams.getArrayParameter("sortBy", def)) {
// sortBy.add(Integer.parseInt((String) obj));
// }
// queryOptions.setSortBy(sortBy);
if (pathParams.getStringParameter("sortBy", null) != null)
{
logger.warn("sortBy not implemented yet");
}
// ... and the query parameters
// We identify any pathParams starting with "param" as query parameters
final Iterator<String> params = (Iterator<String>) pathParams.getParameterNames();
while (params.hasNext())
{
final String param = params.next();
if (param.startsWith("param"))
{
queryOptions.addParameter(param.substring(5), pathParams.getStringParameter(param, ""));
}
}
// Finally, pass the query to the engine
engine.doQuery(out, cdaSettings, queryOptions);
}
| public void doquery(final IParameterProvider pathParams, final OutputStream out) throws Exception
{
final CdaEngine engine = CdaEngine.getInstance();
final QueryOptions queryOptions = new QueryOptions();
final CdaSettings cdaSettings = SettingsManager.getInstance().parseSettingsFile(PentahoSystem.getApplicationContext().getSolutionPath(getRelativePath(pathParams)));
// Handle paging options
// We assume that any paging options found mean that the user actively wants paging.
final long pageSize = pathParams.getLongParameter("pageSize", 0);
final long pageStart = pathParams.getLongParameter("pageStart", 0);
final boolean paginate = pathParams.getStringParameter("paginate", "false").equals("true") ? true : false;
if (pageSize > 0 || pageStart > 0 || paginate)
{
if (pageSize > Integer.MAX_VALUE || pageStart > Integer.MAX_VALUE)
{
throw new ArithmeticException("Paging values too large");
}
queryOptions.setPaginate(true);
queryOptions.setPageSize(pageSize > 0 ? (int) pageSize : paginate ? DEFAULT_PAGE_SIZE : 0);
queryOptions.setPageStart(pageStart > 0 ? (int) pageStart : paginate ? DEFAULT_START_PAGE : 0);
}
// Handle the query itself and its output format...
queryOptions.setOutputType(pathParams.getStringParameter("outputType", "json"));
queryOptions.setDataAccessId(pathParams.getStringParameter("dataAccessId", "<blank>"));
final ArrayList<Integer> sortBy = new ArrayList<Integer>();
// Integer[] def = {};
// for (Object obj : pathParams.getArrayParameter("sortBy", def)) {
// sortBy.add(Integer.parseInt((String) obj));
// }
// queryOptions.setSortBy(sortBy);
if (pathParams.getStringParameter("sortBy", null) != null)
{
logger.warn("sortBy not implemented yet");
}
// ... and the query parameters
// We identify any pathParams starting with "param" as query parameters
final Iterator<String> params = (Iterator<String>) pathParams.getParameterNames();
while (params.hasNext())
{
final String param = params.next();
if (param.startsWith("param"))
{
queryOptions.addParameter(param.substring(5), pathParams.getStringParameter(param, ""));
}
}
// Finally, pass the query to the engine
engine.doQuery(out, cdaSettings, queryOptions);
}
|
diff --git a/javax-cache/src/main/java/org/jboss/lhotse/cache/infinispan/InfinispanCacheFactory.java b/javax-cache/src/main/java/org/jboss/lhotse/cache/infinispan/InfinispanCacheFactory.java
index f352a8c..b50996e 100644
--- a/javax-cache/src/main/java/org/jboss/lhotse/cache/infinispan/InfinispanCacheFactory.java
+++ b/javax-cache/src/main/java/org/jboss/lhotse/cache/infinispan/InfinispanCacheFactory.java
@@ -1,130 +1,132 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.lhotse.cache.infinispan;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;
import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.kohsuke.MetaInfServices;
/**
* Infinispan javax.cache factory implementation.
*
* @author <a href="mailto:[email protected]">Ales Justin</a>
*/
@MetaInfServices
public class InfinispanCacheFactory implements CacheFactory
{
private static Logger log = Logger.getLogger(InfinispanCacheFactory.class.getName());
private EmbeddedCacheManager cacheManager;
public InfinispanCacheFactory() throws IOException
{
try
{
cacheManager = doJNDILookup();
}
catch (Throwable t)
{
log.warning("Failed to do JNDI lookup, using standalone configuration: " + t);
cacheManager = doStandalone();
}
}
protected EmbeddedCacheManager doJNDILookup() throws IOException
{
Properties jndiProperties = new Properties();
URL jndiPropertiesURL = getClass().getClassLoader().getResource("jndi.properties");
if (jndiPropertiesURL != null)
{
InputStream is = jndiPropertiesURL.openStream();
try
{
jndiProperties.load(is);
}
finally
{
try
{
is.close();
}
catch (IOException ignored)
{
}
}
}
- String jndiNamespace = jndiProperties.getProperty("infinispan.jndi.name", "java:CacheManager");
+ String jndiNamespace = jndiProperties.getProperty("infinispan.jndi.name", "java:CacheManager/lhotse");
Context ctx = null;
try
{
ctx = new InitialContext(jndiProperties);
- return (EmbeddedCacheManager) ctx.lookup(jndiNamespace);
+ EmbeddedCacheManager manager = (EmbeddedCacheManager) ctx.lookup(jndiNamespace);
+ log.info("Using JNDI found CacheManager: " + jndiNamespace);
+ return manager;
}
catch (NamingException ne)
{
String msg = "Unable to retrieve CacheManager from JNDI [" + jndiNamespace + "]";
log.info(msg + ": " + ne);
throw new IOException(msg);
}
finally
{
if (ctx != null)
{
try
{
ctx.close();
}
catch (NamingException ne)
{
log.info("Unable to release initial context: " + ne);
}
}
}
}
protected EmbeddedCacheManager doStandalone() throws IOException
{
String configurationFile = System.getProperty("org.jboss.lhotse.cache.configurationFile", "infinispan-config.xml");
return new DefaultCacheManager(configurationFile, true);
}
public Cache createCache(Map map) throws CacheException
{
String cacheName = (String) map.get("cache-name");
org.infinispan.Cache cache = cacheManager.getCache(cacheName);
return new InfinispanCache(cache);
}
}
| false | true | protected EmbeddedCacheManager doJNDILookup() throws IOException
{
Properties jndiProperties = new Properties();
URL jndiPropertiesURL = getClass().getClassLoader().getResource("jndi.properties");
if (jndiPropertiesURL != null)
{
InputStream is = jndiPropertiesURL.openStream();
try
{
jndiProperties.load(is);
}
finally
{
try
{
is.close();
}
catch (IOException ignored)
{
}
}
}
String jndiNamespace = jndiProperties.getProperty("infinispan.jndi.name", "java:CacheManager");
Context ctx = null;
try
{
ctx = new InitialContext(jndiProperties);
return (EmbeddedCacheManager) ctx.lookup(jndiNamespace);
}
catch (NamingException ne)
{
String msg = "Unable to retrieve CacheManager from JNDI [" + jndiNamespace + "]";
log.info(msg + ": " + ne);
throw new IOException(msg);
}
finally
{
if (ctx != null)
{
try
{
ctx.close();
}
catch (NamingException ne)
{
log.info("Unable to release initial context: " + ne);
}
}
}
}
| protected EmbeddedCacheManager doJNDILookup() throws IOException
{
Properties jndiProperties = new Properties();
URL jndiPropertiesURL = getClass().getClassLoader().getResource("jndi.properties");
if (jndiPropertiesURL != null)
{
InputStream is = jndiPropertiesURL.openStream();
try
{
jndiProperties.load(is);
}
finally
{
try
{
is.close();
}
catch (IOException ignored)
{
}
}
}
String jndiNamespace = jndiProperties.getProperty("infinispan.jndi.name", "java:CacheManager/lhotse");
Context ctx = null;
try
{
ctx = new InitialContext(jndiProperties);
EmbeddedCacheManager manager = (EmbeddedCacheManager) ctx.lookup(jndiNamespace);
log.info("Using JNDI found CacheManager: " + jndiNamespace);
return manager;
}
catch (NamingException ne)
{
String msg = "Unable to retrieve CacheManager from JNDI [" + jndiNamespace + "]";
log.info(msg + ": " + ne);
throw new IOException(msg);
}
finally
{
if (ctx != null)
{
try
{
ctx.close();
}
catch (NamingException ne)
{
log.info("Unable to release initial context: " + ne);
}
}
}
}
|
diff --git a/src/com/dmdirc/addons/relaybot/RelayCallbackManager.java b/src/com/dmdirc/addons/relaybot/RelayCallbackManager.java
index f07d69f2..88c44ebb 100644
--- a/src/com/dmdirc/addons/relaybot/RelayCallbackManager.java
+++ b/src/com/dmdirc/addons/relaybot/RelayCallbackManager.java
@@ -1,197 +1,197 @@
/*
* Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.addons.relaybot;
import com.dmdirc.Channel;
import com.dmdirc.ChannelEventHandler;
import com.dmdirc.parser.common.CallbackManager;
import com.dmdirc.parser.common.CallbackNotFoundException;
import com.dmdirc.parser.common.CallbackObject;
import com.dmdirc.parser.common.ChildImplementations;
import com.dmdirc.parser.interfaces.Parser;
import com.dmdirc.parser.interfaces.callbacks.CallbackInterface;
import com.dmdirc.parser.interfaces.callbacks.ChannelMessageListener;
import com.dmdirc.parser.interfaces.callbacks.SocketCloseListener;
import com.dmdirc.parser.irc.IRCParser;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* This is a callback manager that when created will replace the callback
* manager of the given parser with itself.
*
* When a new callback is added it will be allowed unless the RelayBotPlugin
* says otherwise.
*
* When the parser disconnects, the original CBM is restored.
*
* @author shane
*/
public class RelayCallbackManager extends CallbackManager implements SocketCloseListener {
/** Pluign that created this callback manager. */
private final RelayBotPlugin myPlugin;
/** Original CallbackManager */
private final CallbackManager originalCBM;
/**
* Create a new RelayCallbackManager and replace
*
* @param myPlugin
* @param parser
*/
public RelayCallbackManager(final RelayBotPlugin myPlugin, final IRCParser parser) {
super(parser, getImplementations());
this.myPlugin = myPlugin;
this.originalCBM = parser.getCallbackManager();
setCallbackManager(parser, this);
addCallback(SocketCloseListener.class, this);
}
private static Map<Class<?>, Class<?>> getImplementations() {
final Map<Class<?>, Class<?>> implementations
= new HashMap<Class<?>, Class<?>>();
for (Class<?> child : IRCParser.class.getAnnotation(ChildImplementations.class).value()) {
for (Class<?> iface : child.getInterfaces()) {
implementations.put(iface, child);
}
}
return implementations;
}
/** {@inheritDoc} */
@Override
public <S extends CallbackInterface> void addCallback(final Class<S> callback, final S o, final String target) throws CallbackNotFoundException {
// Don't allow the core to give itself a ChannelMessageListener if we
// already have a listener for this channel.
if (o instanceof ChannelEventHandler && callback == ChannelMessageListener.class) {
try {
// Get the old callback manager
final Field field = o.getClass().getDeclaredField("owner");
field.setAccessible(true);
final Channel channel = (Channel) field.get(o);
if (myPlugin.isListening(channel)) {
return;
}
} catch (NoSuchFieldException ex) {
ex.printStackTrace();
} catch (SecurityException ex) {
ex.printStackTrace();
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
// Unless the plugin says we are listening instead of this channel, then
// we can add the callback.
forceAddCallback(callback, o, target);
}
/**
* Add a callback with a specific target.
* This method will throw a CallbackNotFoundException if the callback does not exist.
*
* @param <T> The type of callback
* @param callback Type of callback object.
* @param o instance of ICallbackInterface to add.
* @param target Parameter to specify that a callback should only fire for specific things
* @throws CallbackNotFoundException If callback is not found.
* @throws NullPointerException If 'o' is null
*/
public <T extends CallbackInterface> void forceAddCallback(final Class<T> callback, final T o, final String target) throws CallbackNotFoundException {
super.addCallback(callback, o, target);
}
/**
* Set the Callback Manager of a given parser.
*
* @param parser
* @param cbm
*/
private void setCallbackManager(final IRCParser parser, final CallbackManager cbm) {
try {
// Get the old callback manager
- final Field field = parser.getClass().getDeclaredField("myCallbackManager");
+ final Field field = parser.getClass().getSuperclass().getDeclaredField("callbackManager");
field.setAccessible(true);
@SuppressWarnings("unchecked")
final CallbackManager oldCBM = (CallbackManager) field.get(parser);
// Clone the known CallbackObjects list (horrible code ahoy!)
// First get the old map of callbacks
final Field cbField = CallbackManager.class.getDeclaredField("callbackHash");
cbField.setAccessible(true);
@SuppressWarnings("unchecked")
final Map<Class<? extends CallbackInterface>, CallbackObject> oldCallbackHash = (Map<Class<? extends CallbackInterface>, CallbackObject>) cbField.get(oldCBM);
// Clear my map of callbacks
@SuppressWarnings("unchecked")
final Map<Class<? extends CallbackInterface>, CallbackObject> myCallbackHash = (Map<Class<? extends CallbackInterface>, CallbackObject>) cbField.get(cbm);
myCallbackHash.clear();
// Now add them all to the new cbm.
for (CallbackObject callback : oldCallbackHash.values()) {
// Change their manager to the new one.
final Field ownerField = CallbackObject.class.getDeclaredField("myManager");
ownerField.setAccessible(true);
ownerField.set(callback, cbm);
// And add them to the CBM
cbm.addCallbackType(callback);
}
// Replace the old one with the new one.
field.set(parser, cbm);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (NoSuchFieldException ex) {
ex.printStackTrace();
} catch (SecurityException ex) {
ex.printStackTrace();
}
}
/**
* When the socket closes, reset the callback manager.
*
* @param parser
*/
@Override
public void onSocketClosed(final Parser parser, final Date date) {
if (parser.getCallbackManager() instanceof RelayCallbackManager) {
setCallbackManager((IRCParser)parser, originalCBM);
}
}
}
| true | true | private void setCallbackManager(final IRCParser parser, final CallbackManager cbm) {
try {
// Get the old callback manager
final Field field = parser.getClass().getDeclaredField("myCallbackManager");
field.setAccessible(true);
@SuppressWarnings("unchecked")
final CallbackManager oldCBM = (CallbackManager) field.get(parser);
// Clone the known CallbackObjects list (horrible code ahoy!)
// First get the old map of callbacks
final Field cbField = CallbackManager.class.getDeclaredField("callbackHash");
cbField.setAccessible(true);
@SuppressWarnings("unchecked")
final Map<Class<? extends CallbackInterface>, CallbackObject> oldCallbackHash = (Map<Class<? extends CallbackInterface>, CallbackObject>) cbField.get(oldCBM);
// Clear my map of callbacks
@SuppressWarnings("unchecked")
final Map<Class<? extends CallbackInterface>, CallbackObject> myCallbackHash = (Map<Class<? extends CallbackInterface>, CallbackObject>) cbField.get(cbm);
myCallbackHash.clear();
// Now add them all to the new cbm.
for (CallbackObject callback : oldCallbackHash.values()) {
// Change their manager to the new one.
final Field ownerField = CallbackObject.class.getDeclaredField("myManager");
ownerField.setAccessible(true);
ownerField.set(callback, cbm);
// And add them to the CBM
cbm.addCallbackType(callback);
}
// Replace the old one with the new one.
field.set(parser, cbm);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (NoSuchFieldException ex) {
ex.printStackTrace();
} catch (SecurityException ex) {
ex.printStackTrace();
}
}
| private void setCallbackManager(final IRCParser parser, final CallbackManager cbm) {
try {
// Get the old callback manager
final Field field = parser.getClass().getSuperclass().getDeclaredField("callbackManager");
field.setAccessible(true);
@SuppressWarnings("unchecked")
final CallbackManager oldCBM = (CallbackManager) field.get(parser);
// Clone the known CallbackObjects list (horrible code ahoy!)
// First get the old map of callbacks
final Field cbField = CallbackManager.class.getDeclaredField("callbackHash");
cbField.setAccessible(true);
@SuppressWarnings("unchecked")
final Map<Class<? extends CallbackInterface>, CallbackObject> oldCallbackHash = (Map<Class<? extends CallbackInterface>, CallbackObject>) cbField.get(oldCBM);
// Clear my map of callbacks
@SuppressWarnings("unchecked")
final Map<Class<? extends CallbackInterface>, CallbackObject> myCallbackHash = (Map<Class<? extends CallbackInterface>, CallbackObject>) cbField.get(cbm);
myCallbackHash.clear();
// Now add them all to the new cbm.
for (CallbackObject callback : oldCallbackHash.values()) {
// Change their manager to the new one.
final Field ownerField = CallbackObject.class.getDeclaredField("myManager");
ownerField.setAccessible(true);
ownerField.set(callback, cbm);
// And add them to the CBM
cbm.addCallbackType(callback);
}
// Replace the old one with the new one.
field.set(parser, cbm);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (NoSuchFieldException ex) {
ex.printStackTrace();
} catch (SecurityException ex) {
ex.printStackTrace();
}
}
|
diff --git a/ArjunaJTS/jts/tests/classes/com/hp/mwtests/ts/jts/remote/current/CurrentTest.java b/ArjunaJTS/jts/tests/classes/com/hp/mwtests/ts/jts/remote/current/CurrentTest.java
index 63397f59e..9c0bbbdde 100644
--- a/ArjunaJTS/jts/tests/classes/com/hp/mwtests/ts/jts/remote/current/CurrentTest.java
+++ b/ArjunaJTS/jts/tests/classes/com/hp/mwtests/ts/jts/remote/current/CurrentTest.java
@@ -1,164 +1,164 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* (C) 2005-2006,
* @author JBoss Inc.
*/
/*
* Copyright (C) 1998, 1999, 2000,
*
* Arjuna Solutions Limited,
* Newcastle upon Tyne,
* Tyne and Wear,
* UK.
*
* $Id: CurrentTest.java 2342 2006-03-30 13:06:17Z $
*/
package com.hp.mwtests.ts.jts.remote.current;
import org.omg.CosTransactions.Control;
import com.arjuna.ats.internal.jts.ORBManager;
import com.arjuna.ats.internal.jts.OTSImpleManager;
import com.arjuna.ats.internal.jts.orbspecific.CurrentImple;
import com.arjuna.orbportability.OA;
import com.arjuna.orbportability.ORB;
import com.arjuna.orbportability.RootOA;
import com.arjuna.orbportability.Services;
import com.hp.mwtests.ts.jts.TestModule.grid;
import com.hp.mwtests.ts.jts.TestModule.gridHelper;
import com.hp.mwtests.ts.jts.resources.TestUtility;
public class CurrentTest
{
public static void main(String[] args) throws Exception
{
ORB myORB = null;
RootOA myOA = null;
myORB = ORB.getInstance("test");
myOA = OA.getRootOA(myORB);
myORB.initORB(new String[] {}, null);
myOA.initOA();
ORBManager.setORB(myORB);
ORBManager.setPOA(myOA);
CurrentImple current = OTSImpleManager.current();
Control myControl = null;
String gridReference = args[0];
grid gridVar = null; // pointer the grid object that will be used.
int h = -1, w = -1, v = -1;
System.out.println("Beginning transaction.");
try
{
current.begin();
myControl = current.get_control();
TestUtility.assertTrue(myControl != null);
}
catch (Exception sysEx)
{
sysEx.printStackTrace(System.err);
TestUtility.fail(sysEx.toString());
}
try
{
Services serv = new Services(myORB);
gridVar = gridHelper.narrow(myORB.orb().string_to_object(TestUtility.getService(gridReference)));
}
catch (Exception sysEx)
{
TestUtility.fail("failed to bind to grid: "+sysEx);
sysEx.printStackTrace(System.err);
}
try
{
h = gridVar.height();
w = gridVar.width();
}
catch (Exception sysEx)
{
TestUtility.fail("grid height/width failed: "+sysEx);
sysEx.printStackTrace(System.err);
}
System.out.println("height is "+h);
System.out.println("width is "+w);
try
{
gridVar.set(2, 4, 123, myControl);
v = gridVar.get(2, 4, myControl);
}
catch (Exception sysEx)
{
TestUtility.fail("grid set/get failed: "+sysEx);
sysEx.printStackTrace(System.err);
}
- // no problem setting and getting the elememt:
+ // no problem setting and getting the element:
System.out.println("grid[2,4] is "+v);
// sanity check: make sure we got the value 123 back:
if (v != 123)
{
TestUtility.fail("something went seriously wrong");
try
{
current.rollback();
}
catch (Exception e)
{
TestUtility.fail("rollback error: "+e);
e.printStackTrace(System.err);
}
}
else
{
System.out.println("Committing transaction.");
try
{
current.commit(true);
}
catch (Exception e)
{
TestUtility.fail("commit error: "+e);
e.printStackTrace(System.err);
}
myOA.destroy();
myORB.shutdown();
System.out.println("Passed");
}
}
}
| true | true | public static void main(String[] args) throws Exception
{
ORB myORB = null;
RootOA myOA = null;
myORB = ORB.getInstance("test");
myOA = OA.getRootOA(myORB);
myORB.initORB(new String[] {}, null);
myOA.initOA();
ORBManager.setORB(myORB);
ORBManager.setPOA(myOA);
CurrentImple current = OTSImpleManager.current();
Control myControl = null;
String gridReference = args[0];
grid gridVar = null; // pointer the grid object that will be used.
int h = -1, w = -1, v = -1;
System.out.println("Beginning transaction.");
try
{
current.begin();
myControl = current.get_control();
TestUtility.assertTrue(myControl != null);
}
catch (Exception sysEx)
{
sysEx.printStackTrace(System.err);
TestUtility.fail(sysEx.toString());
}
try
{
Services serv = new Services(myORB);
gridVar = gridHelper.narrow(myORB.orb().string_to_object(TestUtility.getService(gridReference)));
}
catch (Exception sysEx)
{
TestUtility.fail("failed to bind to grid: "+sysEx);
sysEx.printStackTrace(System.err);
}
try
{
h = gridVar.height();
w = gridVar.width();
}
catch (Exception sysEx)
{
TestUtility.fail("grid height/width failed: "+sysEx);
sysEx.printStackTrace(System.err);
}
System.out.println("height is "+h);
System.out.println("width is "+w);
try
{
gridVar.set(2, 4, 123, myControl);
v = gridVar.get(2, 4, myControl);
}
catch (Exception sysEx)
{
TestUtility.fail("grid set/get failed: "+sysEx);
sysEx.printStackTrace(System.err);
}
// no problem setting and getting the elememt:
System.out.println("grid[2,4] is "+v);
// sanity check: make sure we got the value 123 back:
if (v != 123)
{
TestUtility.fail("something went seriously wrong");
try
{
current.rollback();
}
catch (Exception e)
{
TestUtility.fail("rollback error: "+e);
e.printStackTrace(System.err);
}
}
else
{
System.out.println("Committing transaction.");
try
{
current.commit(true);
}
catch (Exception e)
{
TestUtility.fail("commit error: "+e);
e.printStackTrace(System.err);
}
myOA.destroy();
myORB.shutdown();
System.out.println("Passed");
}
}
| public static void main(String[] args) throws Exception
{
ORB myORB = null;
RootOA myOA = null;
myORB = ORB.getInstance("test");
myOA = OA.getRootOA(myORB);
myORB.initORB(new String[] {}, null);
myOA.initOA();
ORBManager.setORB(myORB);
ORBManager.setPOA(myOA);
CurrentImple current = OTSImpleManager.current();
Control myControl = null;
String gridReference = args[0];
grid gridVar = null; // pointer the grid object that will be used.
int h = -1, w = -1, v = -1;
System.out.println("Beginning transaction.");
try
{
current.begin();
myControl = current.get_control();
TestUtility.assertTrue(myControl != null);
}
catch (Exception sysEx)
{
sysEx.printStackTrace(System.err);
TestUtility.fail(sysEx.toString());
}
try
{
Services serv = new Services(myORB);
gridVar = gridHelper.narrow(myORB.orb().string_to_object(TestUtility.getService(gridReference)));
}
catch (Exception sysEx)
{
TestUtility.fail("failed to bind to grid: "+sysEx);
sysEx.printStackTrace(System.err);
}
try
{
h = gridVar.height();
w = gridVar.width();
}
catch (Exception sysEx)
{
TestUtility.fail("grid height/width failed: "+sysEx);
sysEx.printStackTrace(System.err);
}
System.out.println("height is "+h);
System.out.println("width is "+w);
try
{
gridVar.set(2, 4, 123, myControl);
v = gridVar.get(2, 4, myControl);
}
catch (Exception sysEx)
{
TestUtility.fail("grid set/get failed: "+sysEx);
sysEx.printStackTrace(System.err);
}
// no problem setting and getting the element:
System.out.println("grid[2,4] is "+v);
// sanity check: make sure we got the value 123 back:
if (v != 123)
{
TestUtility.fail("something went seriously wrong");
try
{
current.rollback();
}
catch (Exception e)
{
TestUtility.fail("rollback error: "+e);
e.printStackTrace(System.err);
}
}
else
{
System.out.println("Committing transaction.");
try
{
current.commit(true);
}
catch (Exception e)
{
TestUtility.fail("commit error: "+e);
e.printStackTrace(System.err);
}
myOA.destroy();
myORB.shutdown();
System.out.println("Passed");
}
}
|
diff --git a/src/ie/broadsheet/app/PostDetailActivity.java b/src/ie/broadsheet/app/PostDetailActivity.java
index 82631a1..152b875 100644
--- a/src/ie/broadsheet/app/PostDetailActivity.java
+++ b/src/ie/broadsheet/app/PostDetailActivity.java
@@ -1,63 +1,63 @@
package ie.broadsheet.app;
import ie.broadsheet.app.fragments.PostDetailFragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
/**
* An activity representing a single Post detail screen. This activity is only used on handset devices. On tablet-size
* devices, item details are presented side-by-side with a list of items in a {@link PostListActivity}.
* <p>
* This activity is mostly just a 'shell' activity containing nothing more than a {@link PostDetailFragment}.
*/
public class PostDetailActivity extends BaseFragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_detail);
// Show the Up button in the action bar.
- getActionBar().setDisplayHomeAsUpEnabled(true);
+ getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments
.putInt(PostDetailFragment.ARG_ITEM_ID, getIntent().getIntExtra(PostDetailFragment.ARG_ITEM_ID, 0));
arguments.putString(PostDetailFragment.ARG_ITEM_URL,
getIntent().getStringExtra(PostDetailFragment.ARG_ITEM_URL));
PostDetailFragment fragment = new PostDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction().add(R.id.post_detail_container, fragment).commit();
}
}
@Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpTo(this, new Intent(this, PostListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_detail);
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments
.putInt(PostDetailFragment.ARG_ITEM_ID, getIntent().getIntExtra(PostDetailFragment.ARG_ITEM_ID, 0));
arguments.putString(PostDetailFragment.ARG_ITEM_URL,
getIntent().getStringExtra(PostDetailFragment.ARG_ITEM_URL));
PostDetailFragment fragment = new PostDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction().add(R.id.post_detail_container, fragment).commit();
}
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_detail);
// Show the Up button in the action bar.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments
.putInt(PostDetailFragment.ARG_ITEM_ID, getIntent().getIntExtra(PostDetailFragment.ARG_ITEM_ID, 0));
arguments.putString(PostDetailFragment.ARG_ITEM_URL,
getIntent().getStringExtra(PostDetailFragment.ARG_ITEM_URL));
PostDetailFragment fragment = new PostDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction().add(R.id.post_detail_container, fragment).commit();
}
}
|
diff --git a/src/com/wolvencraft/prison/mines/util/Message.java b/src/com/wolvencraft/prison/mines/util/Message.java
index 21cd975..3645ef6 100644
--- a/src/com/wolvencraft/prison/mines/util/Message.java
+++ b/src/com/wolvencraft/prison/mines/util/Message.java
@@ -1,111 +1,111 @@
package com.wolvencraft.prison.mines.util;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.wolvencraft.prison.mines.CommandManager;
import com.wolvencraft.prison.mines.PrisonMine;
public class Message extends com.wolvencraft.prison.util.Message {
private static Logger logger = Logger.getLogger("PrisonMine");
public static void send(CommandSender sender, String message) {
if(message == null) message = "";
sender.sendMessage(Util.parseVars(message, PrisonMine.getCurMine(sender)));
}
public static void send(String message) {
if(message == null) message = "";
send(CommandManager.getSender(), message);
}
public static void sendSuccess(CommandSender sender, String message) {
if(message == null) message = "";
send(sender, PrisonMine.getLanguage().GENERAL_SUCCESS + " " + ChatColor.WHITE + message);
}
public static void sendSuccess(String message) {
if(message == null) message = "";
sendSuccess(CommandManager.getSender(), message);
}
public static void sendError(CommandSender sender, String message) {
if(message == null) message = "";
send(sender, PrisonMine.getLanguage().GENERAL_ERROR + " " + ChatColor.WHITE + message);
}
public static void sendError(String message) {
if(message == null) message = "";
sendError(CommandManager.getSender(), message);
}
public static void sendCustom(String title, String message) {
if(message == null) message = "";
send(CommandManager.getSender(), ChatColor.GOLD + "[" + title + "] " + ChatColor.WHITE + message);
}
/**
* Broadcasts a message to all players on the server
* @param message Message to be sent
*/
public static void broadcast(String message) {
if(message == null) message = "";
message = PrisonMine.getLanguage().GENERAL_SUCCESS + " " + ChatColor.WHITE + message;
for (Player p : Bukkit.getServer().getOnlinePlayers()) {
- if(p.hasPermission("mcprison.mine.reset.broadcast")) p.sendMessage(Util.parseColors(message));
+ if(p.hasPermission("prison.mine.reset.broadcast")) p.sendMessage(Util.parseColors(message));
}
Bukkit.getServer().getConsoleSender().sendMessage(Util.parseColors(message));
}
/**
* Sends a message into the server log if debug is enabled
* @param message Message to be sent
*/
public static void debug(String message) {
if (PrisonMine.getSettings().DEBUG) log(message);
}
/**
* Sends a message into the server log
* @param message Message to be sent
*/
public static void log(String message) {
logger.info("[PrisonMine] " + message);
}
/**
* Sends a message into the server log
* @param level Severity level
* @param message Message to be sent
*/
public static void log(Level level, String message) {
logger.log(level, "[PrisonMine] " + message);
}
public static void formatHelp(String command, String arguments, String description, String node) {
if(!arguments.equalsIgnoreCase("")) arguments = " " + arguments;
if(Util.hasPermission(node) || node.equals(""))
send(ChatColor.GOLD + "/mine " + command + ChatColor.GRAY + arguments + ChatColor.WHITE + " " + description);
}
public static void formatMessage(String message) {
send(" " + message);
}
public static void formatHelp(String command, String arguments, String description) {
formatHelp(command, arguments, description, "");
return;
}
public static void formatHeader(int padding, String name) {
CommandSender sender = CommandManager.getSender();
String spaces = "";
for(int i = 0; i < padding; i++) { spaces = spaces + " "; }
sender.sendMessage(spaces + "-=[ " + ChatColor.BLUE + name + ChatColor.WHITE + " ]=-");
}
}
| true | true | public static void broadcast(String message) {
if(message == null) message = "";
message = PrisonMine.getLanguage().GENERAL_SUCCESS + " " + ChatColor.WHITE + message;
for (Player p : Bukkit.getServer().getOnlinePlayers()) {
if(p.hasPermission("mcprison.mine.reset.broadcast")) p.sendMessage(Util.parseColors(message));
}
Bukkit.getServer().getConsoleSender().sendMessage(Util.parseColors(message));
}
| public static void broadcast(String message) {
if(message == null) message = "";
message = PrisonMine.getLanguage().GENERAL_SUCCESS + " " + ChatColor.WHITE + message;
for (Player p : Bukkit.getServer().getOnlinePlayers()) {
if(p.hasPermission("prison.mine.reset.broadcast")) p.sendMessage(Util.parseColors(message));
}
Bukkit.getServer().getConsoleSender().sendMessage(Util.parseColors(message));
}
|
diff --git a/HakunaContacta/src/de/hakunacontacta/client/Page2.java b/HakunaContacta/src/de/hakunacontacta/client/Page2.java
index a3a924a..0736120 100644
--- a/HakunaContacta/src/de/hakunacontacta/client/Page2.java
+++ b/HakunaContacta/src/de/hakunacontacta/client/Page2.java
@@ -1,347 +1,348 @@
package de.hakunacontacta.client;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.smartgwt.client.types.DragDataAction;
import com.smartgwt.client.widgets.layout.HStack;
import com.smartgwt.client.widgets.tree.Tree;
import com.smartgwt.client.widgets.tree.TreeGrid;
import com.smartgwt.client.widgets.tree.TreeNode;
import com.smartgwt.client.widgets.tree.events.FolderDropEvent;
import com.smartgwt.client.widgets.tree.events.FolderDropHandler;
import de.hakunacontacta.shared.ExportTypeEnum;
/**
* @author MB
* @category GUI
*/
public class Page2 extends Composite {
private VerticalPanel page2 = new VerticalPanel();
private ClientEngine clientEngine;
private VerticalPanel mainPanel = new VerticalPanel();
private HorizontalPanel addPanel = new HorizontalPanel();
private TextBox addExportfieldTextBox = new TextBox();
private Button addExportfieldButton = new Button("Add");
private Tree thisSourceTypesTree = null;
private Tree thisExportTypesTree = null;
TreeGrid sourceGrid = null;
TreeGrid exportGrid = null;
private ExportTypeEnum currentFormat = ExportTypeEnum.CSVWord;
private String dateiendung = "csv";
private String encoded = "";
private HTML downloadLink = null;
/**
* Der Konstruktor von Page2 erwartet eine ClientEngine, welche der
* Kontaktpunkt zur GreetingServiceImpl und damit zur Server-Seite ist.
* Au�erdem werden die Daten der ersten Seite ben�tigt.
*
* @param cEngine
* ist der Kontaktpunkt des Clients zum Server
* @param contactSourceTypesTree
* liefert den Content aus Page1
*/
public Page2(ClientEngine cEngine, Tree contactSourceTypesTree) {
thisSourceTypesTree = contactSourceTypesTree;
clientEngine = cEngine;
initPage();
initWidget(page2);
}
public void setThisExportTypesTree(Tree ExportTypesTree) {
thisExportTypesTree = ExportTypesTree;
}
/**
* Diese Methode wird beim erneuten Seitenaufbau geladen um den Inhalt der
* Grids zu aktuallisieren
*/
public void updateData() {
sourceGrid.setData(thisSourceTypesTree);
sourceGrid.getData().openAll();
exportGrid.setData(thisExportTypesTree);
exportGrid.getData().openAll();
}
/**
* Diese Methode erstellt eine url und liefert einen Base64-codierten String
* mit einer Dateiendung abh�ngig vom im dropdown-men� gew�hlten Wert an den
* Browser
*/
public void createDownloadLink() {
if (currentFormat == ExportTypeEnum.CSV) {
dateiendung = "csv";
} else if (currentFormat == ExportTypeEnum.XML) {
dateiendung = "xml";
} else if (currentFormat == ExportTypeEnum.vCard) {
dateiendung = "vCard";
} else if (currentFormat == ExportTypeEnum.CSVWord) {
dateiendung = "csv";
}
if (downloadLink != null) {
page2.remove(downloadLink);
}
class MyModule {
public native void openURL(String url, String filename) /*-{
$wnd.url = url;
var uri = $wnd.url;
var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = filename;
downloadLink.id = "download"
document.body.appendChild(downloadLink);
document.getElementById('download').click();
document.body.removeChild(downloadLink);
}-*/;
}
if (!ClientEngine.isIEBrowser()) {
MyModule embeddedJavaScript = new MyModule();
embeddedJavaScript.openURL("data:application/" + dateiendung + ";base64," + encoded, "ContactExport." + dateiendung);
}
else {
Window.open("data:application/" + dateiendung + ";base64," + encoded, "ContactExport." + dateiendung, "");
}
}
public void setEncoded(String encoded) {
this.encoded = encoded;
}
/**
* Diese Methode erstellt alle Elemente, Widgets und Handler auf der zweiten
* Seite und verwaltet die Kommunikation mit der ClientEngine
*/
private void initPage() {
clientEngine.setPage2(this);
page2.setPixelSize(1000, 350);
Button exportButton = new Button("Download Exportdatei");
exportButton.addStyleName("exportButton");
Button zurueckButton = new Button("Zur\u00FCck zur Kontaktauswahl");
zurueckButton.addStyleName("zurueckButton");
// Linke Seite
sourceGrid = new TreeGrid();
sourceGrid.setHeight(350);
sourceGrid.setWidth(250);
sourceGrid.setBorder("1px solid #ABABAB");
sourceGrid.setDragDataAction(DragDataAction.COPY);
sourceGrid.setCanDragRecordsOut(true);
sourceGrid.setData(thisSourceTypesTree);
sourceGrid.getData().openAll();
sourceGrid.setShowHeader(false);
sourceGrid.setTreeFieldTitle("Quellfelder");
// Rechte Seite
exportGrid = new TreeGrid();
exportGrid.setCanAcceptDroppedRecords(true);
exportGrid.setCanRemoveRecords(true);
exportGrid.setCanReorderRecords(true);
exportGrid.setShowHeader(false);
exportGrid.setCanAcceptDrop(false);
exportGrid.setTreeFieldTitle("Exportfelder");
exportGrid.setHeight(320);
exportGrid.setWidth(250);
+ exportGrid.setParentAlreadyContainsChildMessage("Dieses Exportfeld enth�lt bereits das ausgew\u00E4hlte Informations-Objekt.");
exportGrid.setBorder("1px solid #ABABAB");
exportGrid.setAlternateRecordStyles(true);
exportGrid.addFolderDropHandler(new FolderDropHandler() {
@Override
public void onFolderDrop(FolderDropEvent folderDropEvent) {
final TreeNode target = folderDropEvent.getFolder();
if (target.getAttribute("Name").compareTo("root") == 0) {
folderDropEvent.cancel();
}
}
});
clientEngine.getExportFields(ExportTypeEnum.CSVWord, true);
// Dropdown-Menu
final ListBox formatList = new ListBox();
formatList.addStyleName("chooseFormat");
formatList.setTitle("Exportformat");
formatList.addItem("CSV f\u00FCr Word-Serienbriefe"); // Index 0
formatList.addItem("CSV"); // Index 1
formatList.addItem("vCard"); // Index 2
formatList.addItem("XML (xCard)"); // Index 3
formatList.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
int selectedIndex = formatList.getSelectedIndex();
if (selectedIndex == 0) {
// Methode f�r CSV-Word-Serienbriefe
clientEngine.writeExportOptions(thisExportTypesTree, currentFormat, ExportTypeEnum.CSVWord);
currentFormat = ExportTypeEnum.CSVWord;
}
if (selectedIndex == 1) {
// Methode f�r CSV
clientEngine.writeExportOptions(thisExportTypesTree, currentFormat, ExportTypeEnum.CSV);
currentFormat = ExportTypeEnum.CSV;
}
if (selectedIndex == 2) {
// Methode f�r vCard
clientEngine.writeExportOptions(thisExportTypesTree, currentFormat, ExportTypeEnum.vCard);
currentFormat = ExportTypeEnum.vCard;
}
if (selectedIndex == 3) {
// Methode f�r XML
clientEngine.writeExportOptions(thisExportTypesTree, currentFormat, ExportTypeEnum.XML);
currentFormat = ExportTypeEnum.XML;
}
}
});
// Bewegt den Mauscursor in die Input-Box
addExportfieldTextBox.setFocus(true);
// Achtet auf Mausaktivit�ten beim Hinzuf�gen-Knopf.
addExportfieldButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
final String name = addExportfieldTextBox.getText().trim();
addExportfieldTextBox.setFocus(true);
if (name.matches("")) {
Window.alert("Der Exportfeldname ist leer! Bitte geben Sie einen Namen ein!");
addExportfieldTextBox.selectAll();
return;
}
- if (!name.matches("^[0-9A-Za-z\\.]{1,15}$")) {
+ if (!name.matches("^[0-9A-Za-z\\.\\-]{1,15}$")) {
Window.alert("Der Exportfeldname \"" + name + "\" enth\u00E4lt ung\u00FCltige Zeichen.");
addExportfieldTextBox.selectAll();
return;
}
// Kein Exportfeld hinzuf�gen, falls bereits vorhanden
if (thisExportTypesTree.find("Name", name) != null) {
Window.alert("Es ist bereits ein Exportfeld mit dem Namen \"" + name + "\" vorhanden.");
return;
}
addExportfieldTextBox.setText("");
TreeNode childNode = new TreeNode();
childNode.setAttribute("Name", name);
childNode.setCanDrag(false);
childNode.setIsFolder(true);
thisExportTypesTree.add(childNode, thisExportTypesTree.getRoot());
}
});
// Achtet auf Tastatur-Aktivit�ten in der Input-Box
addExportfieldTextBox.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
final String name = addExportfieldTextBox.getText().trim();
addExportfieldTextBox.setFocus(true);
if (!name.matches("^[0-9A-Za-z\\.]{1,15}$")) {
Window.alert("Der Exportfeldname \"" + name + "\" enth\u00E4lt ung\u00FCltige Zeichen.");
addExportfieldTextBox.selectAll();
return;
}
// F�gt das ExportFeld nicht hinzu, falls bereits vorhanden
if (thisExportTypesTree.find("Name", name) != null) {
Window.alert("Es ist bereits ein Exportfeld mit dem Namen \"" + name + "\" vorhanden.");
return;
}
TreeNode childNode = new TreeNode();
childNode.setAttribute("Name", name);
childNode.setCanDrag(false);
childNode.setIsFolder(true);
thisExportTypesTree.add(childNode, thisExportTypesTree.getRoot());
}
}
});
sourceGrid.setStyleName("sourceGrid");
exportGrid.setStyleName("exportGrid");
exportGrid.setBaseStyle("grid2records");
addExportfieldButton.setStyleName("addExportfieldButton");
addExportfieldTextBox.setStyleName("addExportfieldTextBox");
addPanel.add(addExportfieldTextBox);
addPanel.add(addExportfieldButton);
addPanel.addStyleName("addPanel");
final HTML tip2 = new HTML(
"<div id=\"tip2\"><p><b>Exportfelder erstellen:</b></br></br>1. Exportfeldname eingeben</br></br>2. Mit \"Add\" Exportfeldname best\u00E4tigen.</br></br>3. Neuer Exportfeldordner erscheint.</br></br>4. Per Drag & Drop Informations-</br>felder der linken Seite in den Exportordner ziehen.</br></br>5.Priorit\u00E4t der Exportdaten durch Reihenfolge im Exportfeld zuweisen.</p></div>");
tip2.setPixelSize(200, 350);
HStack grids = new HStack(3);
grids.addMember(sourceGrid);
grids.addMember(tip2);
grids.addMember(exportGrid);
grids.setStyleName("grids2");
grids.draw();
final HTML exportFormat = new HTML("Exportformat: ");
exportFormat.addStyleName("exportFormat");
HTML gridHeaders2 = new HTML("<div id=\"gridHeader21\">Informationsfelder</br>Ihrer Kontakte</div><div id=\"gridHeader22\">Exportfelder</div>");
gridHeaders2.setStyleName("gridHeaders");
mainPanel.add(gridHeaders2);
mainPanel.add(exportFormat);
mainPanel.add(formatList);
mainPanel.add(grids);
mainPanel.add(addPanel);
mainPanel.addStyleName("mainPanel");
exportButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
clientEngine.getFile(thisExportTypesTree, currentFormat, currentFormat);
}
});
zurueckButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
History.newItem("page1", true);
}
});
page2.add(mainPanel);
page2.add(exportButton);
page2.add(zurueckButton);
page2.setStyleName("page2");
}
}
| false | true | private void initPage() {
clientEngine.setPage2(this);
page2.setPixelSize(1000, 350);
Button exportButton = new Button("Download Exportdatei");
exportButton.addStyleName("exportButton");
Button zurueckButton = new Button("Zur\u00FCck zur Kontaktauswahl");
zurueckButton.addStyleName("zurueckButton");
// Linke Seite
sourceGrid = new TreeGrid();
sourceGrid.setHeight(350);
sourceGrid.setWidth(250);
sourceGrid.setBorder("1px solid #ABABAB");
sourceGrid.setDragDataAction(DragDataAction.COPY);
sourceGrid.setCanDragRecordsOut(true);
sourceGrid.setData(thisSourceTypesTree);
sourceGrid.getData().openAll();
sourceGrid.setShowHeader(false);
sourceGrid.setTreeFieldTitle("Quellfelder");
// Rechte Seite
exportGrid = new TreeGrid();
exportGrid.setCanAcceptDroppedRecords(true);
exportGrid.setCanRemoveRecords(true);
exportGrid.setCanReorderRecords(true);
exportGrid.setShowHeader(false);
exportGrid.setCanAcceptDrop(false);
exportGrid.setTreeFieldTitle("Exportfelder");
exportGrid.setHeight(320);
exportGrid.setWidth(250);
exportGrid.setBorder("1px solid #ABABAB");
exportGrid.setAlternateRecordStyles(true);
exportGrid.addFolderDropHandler(new FolderDropHandler() {
@Override
public void onFolderDrop(FolderDropEvent folderDropEvent) {
final TreeNode target = folderDropEvent.getFolder();
if (target.getAttribute("Name").compareTo("root") == 0) {
folderDropEvent.cancel();
}
}
});
clientEngine.getExportFields(ExportTypeEnum.CSVWord, true);
// Dropdown-Menu
final ListBox formatList = new ListBox();
formatList.addStyleName("chooseFormat");
formatList.setTitle("Exportformat");
formatList.addItem("CSV f\u00FCr Word-Serienbriefe"); // Index 0
formatList.addItem("CSV"); // Index 1
formatList.addItem("vCard"); // Index 2
formatList.addItem("XML (xCard)"); // Index 3
formatList.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
int selectedIndex = formatList.getSelectedIndex();
if (selectedIndex == 0) {
// Methode f�r CSV-Word-Serienbriefe
clientEngine.writeExportOptions(thisExportTypesTree, currentFormat, ExportTypeEnum.CSVWord);
currentFormat = ExportTypeEnum.CSVWord;
}
if (selectedIndex == 1) {
// Methode f�r CSV
clientEngine.writeExportOptions(thisExportTypesTree, currentFormat, ExportTypeEnum.CSV);
currentFormat = ExportTypeEnum.CSV;
}
if (selectedIndex == 2) {
// Methode f�r vCard
clientEngine.writeExportOptions(thisExportTypesTree, currentFormat, ExportTypeEnum.vCard);
currentFormat = ExportTypeEnum.vCard;
}
if (selectedIndex == 3) {
// Methode f�r XML
clientEngine.writeExportOptions(thisExportTypesTree, currentFormat, ExportTypeEnum.XML);
currentFormat = ExportTypeEnum.XML;
}
}
});
// Bewegt den Mauscursor in die Input-Box
addExportfieldTextBox.setFocus(true);
// Achtet auf Mausaktivit�ten beim Hinzuf�gen-Knopf.
addExportfieldButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
final String name = addExportfieldTextBox.getText().trim();
addExportfieldTextBox.setFocus(true);
if (name.matches("")) {
Window.alert("Der Exportfeldname ist leer! Bitte geben Sie einen Namen ein!");
addExportfieldTextBox.selectAll();
return;
}
if (!name.matches("^[0-9A-Za-z\\.]{1,15}$")) {
Window.alert("Der Exportfeldname \"" + name + "\" enth\u00E4lt ung\u00FCltige Zeichen.");
addExportfieldTextBox.selectAll();
return;
}
// Kein Exportfeld hinzuf�gen, falls bereits vorhanden
if (thisExportTypesTree.find("Name", name) != null) {
Window.alert("Es ist bereits ein Exportfeld mit dem Namen \"" + name + "\" vorhanden.");
return;
}
addExportfieldTextBox.setText("");
TreeNode childNode = new TreeNode();
childNode.setAttribute("Name", name);
childNode.setCanDrag(false);
childNode.setIsFolder(true);
thisExportTypesTree.add(childNode, thisExportTypesTree.getRoot());
}
});
// Achtet auf Tastatur-Aktivit�ten in der Input-Box
addExportfieldTextBox.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
final String name = addExportfieldTextBox.getText().trim();
addExportfieldTextBox.setFocus(true);
if (!name.matches("^[0-9A-Za-z\\.]{1,15}$")) {
Window.alert("Der Exportfeldname \"" + name + "\" enth\u00E4lt ung\u00FCltige Zeichen.");
addExportfieldTextBox.selectAll();
return;
}
// F�gt das ExportFeld nicht hinzu, falls bereits vorhanden
if (thisExportTypesTree.find("Name", name) != null) {
Window.alert("Es ist bereits ein Exportfeld mit dem Namen \"" + name + "\" vorhanden.");
return;
}
TreeNode childNode = new TreeNode();
childNode.setAttribute("Name", name);
childNode.setCanDrag(false);
childNode.setIsFolder(true);
thisExportTypesTree.add(childNode, thisExportTypesTree.getRoot());
}
}
});
sourceGrid.setStyleName("sourceGrid");
exportGrid.setStyleName("exportGrid");
exportGrid.setBaseStyle("grid2records");
addExportfieldButton.setStyleName("addExportfieldButton");
addExportfieldTextBox.setStyleName("addExportfieldTextBox");
addPanel.add(addExportfieldTextBox);
addPanel.add(addExportfieldButton);
addPanel.addStyleName("addPanel");
final HTML tip2 = new HTML(
"<div id=\"tip2\"><p><b>Exportfelder erstellen:</b></br></br>1. Exportfeldname eingeben</br></br>2. Mit \"Add\" Exportfeldname best\u00E4tigen.</br></br>3. Neuer Exportfeldordner erscheint.</br></br>4. Per Drag & Drop Informations-</br>felder der linken Seite in den Exportordner ziehen.</br></br>5.Priorit\u00E4t der Exportdaten durch Reihenfolge im Exportfeld zuweisen.</p></div>");
tip2.setPixelSize(200, 350);
HStack grids = new HStack(3);
grids.addMember(sourceGrid);
grids.addMember(tip2);
grids.addMember(exportGrid);
grids.setStyleName("grids2");
grids.draw();
final HTML exportFormat = new HTML("Exportformat: ");
exportFormat.addStyleName("exportFormat");
HTML gridHeaders2 = new HTML("<div id=\"gridHeader21\">Informationsfelder</br>Ihrer Kontakte</div><div id=\"gridHeader22\">Exportfelder</div>");
gridHeaders2.setStyleName("gridHeaders");
mainPanel.add(gridHeaders2);
mainPanel.add(exportFormat);
mainPanel.add(formatList);
mainPanel.add(grids);
mainPanel.add(addPanel);
mainPanel.addStyleName("mainPanel");
exportButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
clientEngine.getFile(thisExportTypesTree, currentFormat, currentFormat);
}
});
zurueckButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
History.newItem("page1", true);
}
});
page2.add(mainPanel);
page2.add(exportButton);
page2.add(zurueckButton);
page2.setStyleName("page2");
}
| private void initPage() {
clientEngine.setPage2(this);
page2.setPixelSize(1000, 350);
Button exportButton = new Button("Download Exportdatei");
exportButton.addStyleName("exportButton");
Button zurueckButton = new Button("Zur\u00FCck zur Kontaktauswahl");
zurueckButton.addStyleName("zurueckButton");
// Linke Seite
sourceGrid = new TreeGrid();
sourceGrid.setHeight(350);
sourceGrid.setWidth(250);
sourceGrid.setBorder("1px solid #ABABAB");
sourceGrid.setDragDataAction(DragDataAction.COPY);
sourceGrid.setCanDragRecordsOut(true);
sourceGrid.setData(thisSourceTypesTree);
sourceGrid.getData().openAll();
sourceGrid.setShowHeader(false);
sourceGrid.setTreeFieldTitle("Quellfelder");
// Rechte Seite
exportGrid = new TreeGrid();
exportGrid.setCanAcceptDroppedRecords(true);
exportGrid.setCanRemoveRecords(true);
exportGrid.setCanReorderRecords(true);
exportGrid.setShowHeader(false);
exportGrid.setCanAcceptDrop(false);
exportGrid.setTreeFieldTitle("Exportfelder");
exportGrid.setHeight(320);
exportGrid.setWidth(250);
exportGrid.setParentAlreadyContainsChildMessage("Dieses Exportfeld enth�lt bereits das ausgew\u00E4hlte Informations-Objekt.");
exportGrid.setBorder("1px solid #ABABAB");
exportGrid.setAlternateRecordStyles(true);
exportGrid.addFolderDropHandler(new FolderDropHandler() {
@Override
public void onFolderDrop(FolderDropEvent folderDropEvent) {
final TreeNode target = folderDropEvent.getFolder();
if (target.getAttribute("Name").compareTo("root") == 0) {
folderDropEvent.cancel();
}
}
});
clientEngine.getExportFields(ExportTypeEnum.CSVWord, true);
// Dropdown-Menu
final ListBox formatList = new ListBox();
formatList.addStyleName("chooseFormat");
formatList.setTitle("Exportformat");
formatList.addItem("CSV f\u00FCr Word-Serienbriefe"); // Index 0
formatList.addItem("CSV"); // Index 1
formatList.addItem("vCard"); // Index 2
formatList.addItem("XML (xCard)"); // Index 3
formatList.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
int selectedIndex = formatList.getSelectedIndex();
if (selectedIndex == 0) {
// Methode f�r CSV-Word-Serienbriefe
clientEngine.writeExportOptions(thisExportTypesTree, currentFormat, ExportTypeEnum.CSVWord);
currentFormat = ExportTypeEnum.CSVWord;
}
if (selectedIndex == 1) {
// Methode f�r CSV
clientEngine.writeExportOptions(thisExportTypesTree, currentFormat, ExportTypeEnum.CSV);
currentFormat = ExportTypeEnum.CSV;
}
if (selectedIndex == 2) {
// Methode f�r vCard
clientEngine.writeExportOptions(thisExportTypesTree, currentFormat, ExportTypeEnum.vCard);
currentFormat = ExportTypeEnum.vCard;
}
if (selectedIndex == 3) {
// Methode f�r XML
clientEngine.writeExportOptions(thisExportTypesTree, currentFormat, ExportTypeEnum.XML);
currentFormat = ExportTypeEnum.XML;
}
}
});
// Bewegt den Mauscursor in die Input-Box
addExportfieldTextBox.setFocus(true);
// Achtet auf Mausaktivit�ten beim Hinzuf�gen-Knopf.
addExportfieldButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
final String name = addExportfieldTextBox.getText().trim();
addExportfieldTextBox.setFocus(true);
if (name.matches("")) {
Window.alert("Der Exportfeldname ist leer! Bitte geben Sie einen Namen ein!");
addExportfieldTextBox.selectAll();
return;
}
if (!name.matches("^[0-9A-Za-z\\.\\-]{1,15}$")) {
Window.alert("Der Exportfeldname \"" + name + "\" enth\u00E4lt ung\u00FCltige Zeichen.");
addExportfieldTextBox.selectAll();
return;
}
// Kein Exportfeld hinzuf�gen, falls bereits vorhanden
if (thisExportTypesTree.find("Name", name) != null) {
Window.alert("Es ist bereits ein Exportfeld mit dem Namen \"" + name + "\" vorhanden.");
return;
}
addExportfieldTextBox.setText("");
TreeNode childNode = new TreeNode();
childNode.setAttribute("Name", name);
childNode.setCanDrag(false);
childNode.setIsFolder(true);
thisExportTypesTree.add(childNode, thisExportTypesTree.getRoot());
}
});
// Achtet auf Tastatur-Aktivit�ten in der Input-Box
addExportfieldTextBox.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
final String name = addExportfieldTextBox.getText().trim();
addExportfieldTextBox.setFocus(true);
if (!name.matches("^[0-9A-Za-z\\.]{1,15}$")) {
Window.alert("Der Exportfeldname \"" + name + "\" enth\u00E4lt ung\u00FCltige Zeichen.");
addExportfieldTextBox.selectAll();
return;
}
// F�gt das ExportFeld nicht hinzu, falls bereits vorhanden
if (thisExportTypesTree.find("Name", name) != null) {
Window.alert("Es ist bereits ein Exportfeld mit dem Namen \"" + name + "\" vorhanden.");
return;
}
TreeNode childNode = new TreeNode();
childNode.setAttribute("Name", name);
childNode.setCanDrag(false);
childNode.setIsFolder(true);
thisExportTypesTree.add(childNode, thisExportTypesTree.getRoot());
}
}
});
sourceGrid.setStyleName("sourceGrid");
exportGrid.setStyleName("exportGrid");
exportGrid.setBaseStyle("grid2records");
addExportfieldButton.setStyleName("addExportfieldButton");
addExportfieldTextBox.setStyleName("addExportfieldTextBox");
addPanel.add(addExportfieldTextBox);
addPanel.add(addExportfieldButton);
addPanel.addStyleName("addPanel");
final HTML tip2 = new HTML(
"<div id=\"tip2\"><p><b>Exportfelder erstellen:</b></br></br>1. Exportfeldname eingeben</br></br>2. Mit \"Add\" Exportfeldname best\u00E4tigen.</br></br>3. Neuer Exportfeldordner erscheint.</br></br>4. Per Drag & Drop Informations-</br>felder der linken Seite in den Exportordner ziehen.</br></br>5.Priorit\u00E4t der Exportdaten durch Reihenfolge im Exportfeld zuweisen.</p></div>");
tip2.setPixelSize(200, 350);
HStack grids = new HStack(3);
grids.addMember(sourceGrid);
grids.addMember(tip2);
grids.addMember(exportGrid);
grids.setStyleName("grids2");
grids.draw();
final HTML exportFormat = new HTML("Exportformat: ");
exportFormat.addStyleName("exportFormat");
HTML gridHeaders2 = new HTML("<div id=\"gridHeader21\">Informationsfelder</br>Ihrer Kontakte</div><div id=\"gridHeader22\">Exportfelder</div>");
gridHeaders2.setStyleName("gridHeaders");
mainPanel.add(gridHeaders2);
mainPanel.add(exportFormat);
mainPanel.add(formatList);
mainPanel.add(grids);
mainPanel.add(addPanel);
mainPanel.addStyleName("mainPanel");
exportButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
clientEngine.getFile(thisExportTypesTree, currentFormat, currentFormat);
}
});
zurueckButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
History.newItem("page1", true);
}
});
page2.add(mainPanel);
page2.add(exportButton);
page2.add(zurueckButton);
page2.setStyleName("page2");
}
|
diff --git a/src/test/system/java/org/apache/hadoop/mapred/TestDistributedCacheModifiedFile.java b/src/test/system/java/org/apache/hadoop/mapred/TestDistributedCacheModifiedFile.java
index e617bf893..b563b8fe4 100644
--- a/src/test/system/java/org/apache/hadoop/mapred/TestDistributedCacheModifiedFile.java
+++ b/src/test/system/java/org/apache/hadoop/mapred/TestDistributedCacheModifiedFile.java
@@ -1,342 +1,343 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import java.io.DataOutputStream;
import java.net.URI;
import java.util.Collection;
import java.util.ArrayList;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.apache.hadoop.mapreduce.test.system.JTProtocol;
import org.apache.hadoop.mapreduce.test.system.TTClient;
import org.apache.hadoop.mapreduce.test.system.JobInfo;
import org.apache.hadoop.mapreduce.test.system.TaskInfo;
import org.apache.hadoop.mapreduce.test.system.MRCluster;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.UtilsForTests;
import org.apache.hadoop.mapreduce.test.system.FinishTaskControlAction;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.examples.SleepJob;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
/**
* Verify the Distributed Cache functionality.
* This test scenario is for a distributed cache file behaviour
* when it is modified before and after being
* accessed by maximum two jobs. Once a job uses a distributed cache file
* that file is stored in the mapred.local.dir. If the next job
* uses the same file, but with differnt timestamp, then that
* file is stored again. So, if two jobs choose
* the same tasktracker for their job execution
* then, the distributed cache file should be found twice.
*
* This testcase runs a job with a distributed cache file. All the
* tasks' corresponding tasktracker's handle is got and checked for
* the presence of distributed cache with proper permissions in the
* proper directory. Next when job
* runs again and if any of its tasks hits the same tasktracker, which
* ran one of the task of the previous job, then that
* file should be uploaded again and task should not use the old file.
* This is verified.
*/
public class TestDistributedCacheModifiedFile {
private static MRCluster cluster = null;
private static FileSystem dfs = null;
private static FileSystem ttFs = null;
private static JobClient client = null;
private static FsPermission permission = new FsPermission((short)00777);
private static String uriPath = "hdfs:///tmp/test.txt";
private static final Path URIPATH = new Path(uriPath);
private String distributedFileName = "test.txt";
static final Log LOG = LogFactory.
getLog(TestDistributedCacheModifiedFile.class);
public TestDistributedCacheModifiedFile() throws Exception {
}
@BeforeClass
public static void setUp() throws Exception {
cluster = MRCluster.createCluster(new Configuration());
cluster.setUp();
client = cluster.getJTClient().getClient();
dfs = client.getFs();
//Deleting the file if it already exists
dfs.delete(URIPATH, true);
Collection<TTClient> tts = cluster.getTTClients();
//Stopping all TTs
for (TTClient tt : tts) {
tt.kill();
}
//Starting all TTs
for (TTClient tt : tts) {
tt.start();
}
//Waiting for 5 seconds to make sure tasktrackers are ready
Thread.sleep(5000);
}
@AfterClass
public static void tearDown() throws Exception {
cluster.tearDown();
dfs.delete(URIPATH, true);
Collection<TTClient> tts = cluster.getTTClients();
//Stopping all TTs
for (TTClient tt : tts) {
tt.kill();
}
//Starting all TTs
for (TTClient tt : tts) {
tt.start();
}
}
@Test
/**
* This tests Distributed Cache for modified file
* @param none
* @return void
*/
public void testDistributedCache() throws Exception {
Configuration conf = new Configuration(cluster.getConf());
JTProtocol wovenClient = cluster.getJTClient().getProxy();
//This counter will check for count of a loop,
//which might become infinite.
int count = 0;
//This boolean will decide whether to run job again
boolean continueLoop = true;
//counter for job Loop
int countLoop = 0;
//This counter increases with all the tasktrackers in which tasks ran
int taskTrackerCounter = 0;
//This will store all the tasktrackers in which tasks ran
ArrayList<String> taskTrackerCollection = new ArrayList<String>();
//This boolean tells if two tasks ran onteh same tasktracker or not
boolean taskTrackerFound = false;
do {
SleepJob job = new SleepJob();
job.setConf(conf);
conf = job.setupJobConf(5, 1, 1000, 1000, 100, 100);
+ conf.setBoolean("mapreduce.job.complete.cancel.delegation.tokens", false);
//Before starting, Modify the file
String input = "This will be the content of\n" + "distributed cache\n";
//Creating the path with the file
DataOutputStream file =
UtilsForTests.createTmpFileDFS(dfs, URIPATH, permission, input);
DistributedCache.createSymlink(conf);
URI uri = URI.create(uriPath);
DistributedCache.addCacheFile(uri, conf);
JobConf jconf = new JobConf(conf);
//Controls the job till all verification is done
FinishTaskControlAction.configureControlActionForJob(conf);
//Submitting the job
RunningJob rJob = cluster.getJTClient().getClient().submitJob(jconf);
//counter for job Loop
countLoop++;
TTClient tClient = null;
JobInfo jInfo = wovenClient.getJobInfo(rJob.getID());
LOG.info("jInfo is :" + jInfo);
//Assert if jobInfo is null
Assert.assertNotNull("jobInfo is null", jInfo);
//Wait for the job to start running.
count = 0;
while (jInfo.getStatus().getRunState() != JobStatus.RUNNING) {
UtilsForTests.waitFor(10000);
count++;
jInfo = wovenClient.getJobInfo(rJob.getID());
//If the count goes beyond a point, then break; This is to avoid
//infinite loop under unforeseen circumstances. Testcase will anyway
//fail later.
if (count > 10) {
Assert.fail("job has not reached running state for more than" +
"100 seconds. Failing at this point");
}
}
LOG.info("job id is :" + rJob.getID().toString());
TaskInfo[] taskInfos = cluster.getJTClient().getProxy()
.getTaskInfo(rJob.getID());
boolean distCacheFileIsFound;
for (TaskInfo taskInfo : taskInfos) {
distCacheFileIsFound = false;
String[] taskTrackers = taskInfo.getTaskTrackers();
for (String taskTracker : taskTrackers) {
//Formatting tasktracker to get just its FQDN
taskTracker = UtilsForTests.getFQDNofTT(taskTracker);
LOG.info("taskTracker is :" + taskTracker);
//The tasktrackerFound variable is initialized
taskTrackerFound = false;
//This will be entered from the second job onwards
if (countLoop > 1) {
if (taskTracker != null) {
continueLoop = taskTrackerCollection.contains(taskTracker);
}
if (continueLoop) {
taskTrackerFound = true;
}
}
//Collecting the tasktrackers
if (taskTracker != null)
taskTrackerCollection.add(taskTracker);
//we have loopped through two times to look for task
//getting submitted on same tasktrackers.The same tasktracker
//for subsequent jobs was not hit maybe because of many number
//of tasktrackers. So, testcase has to stop here.
if (countLoop > 1) {
continueLoop = false;
}
tClient = cluster.getTTClient(taskTracker);
//tClient maybe null because the task is already dead. Ex: setup
if (tClient == null) {
continue;
}
String[] localDirs = tClient.getMapredLocalDirs();
int distributedFileCount = 0;
//Go to every single path
for (String localDir : localDirs) {
//Public Distributed cache will always be stored under
//mapre.local.dir/tasktracker/archive
localDir = localDir + Path.SEPARATOR +
TaskTracker.getPublicDistributedCacheDir();
LOG.info("localDir is : " + localDir);
//Get file status of all the directories
//and files under that path.
FileStatus[] fileStatuses = tClient.listStatus(localDir,
true, true);
for (FileStatus fileStatus : fileStatuses) {
Path path = fileStatus.getPath();
LOG.info("path is :" + path.toString());
//Checking if the received path ends with
//the distributed filename
distCacheFileIsFound = (path.toString()).
endsWith(distributedFileName);
//If file is found, check for its permission.
//Since the file is found break out of loop
if (distCacheFileIsFound){
LOG.info("PATH found is :" + path.toString());
distributedFileCount++;
String filename = path.getName();
FsPermission fsPerm = fileStatus.getPermission();
Assert.assertTrue("File Permission is not 777",
fsPerm.equals(new FsPermission("777")));
}
}
}
LOG.debug("The distributed FileCount is :" + distributedFileCount);
LOG.debug("The taskTrackerFound is :" + taskTrackerFound);
// If distributed cache is modified in dfs
// between two job runs, it can be present more than once
// in any of the task tracker, in which job ran.
if (distributedFileCount != 2 && taskTrackerFound) {
Assert.fail("The distributed cache file has to be two. " +
"But found was " + distributedFileCount);
} else if (distributedFileCount > 1 && !taskTrackerFound) {
Assert.fail("The distributed cache file cannot more than one." +
" But found was " + distributedFileCount);
} else if (distributedFileCount < 1)
Assert.fail("The distributed cache file is less than one. " +
"But found was " + distributedFileCount);
if (!distCacheFileIsFound) {
Assert.assertEquals("The distributed cache file does not exist",
distCacheFileIsFound, false);
}
}
}
//Allow the job to continue through MR control job.
for (TaskInfo taskInfoRemaining : taskInfos) {
FinishTaskControlAction action = new FinishTaskControlAction(TaskID
.downgrade(taskInfoRemaining.getTaskID()));
Collection<TTClient> tts = cluster.getTTClients();
for (TTClient cli : tts) {
cli.getProxy().sendAction(action);
}
}
//Killing the job because all the verification needed
//for this testcase is completed.
rJob.killJob();
//Waiting for 3 seconds for cleanup to start
Thread.sleep(3000);
//Getting the last cleanup task's tasktracker also, as
//distributed cache gets uploaded even during cleanup.
TaskInfo[] myTaskInfos = wovenClient.getTaskInfo(rJob.getID());
if (myTaskInfos != null) {
for(TaskInfo info : myTaskInfos) {
if(info.isSetupOrCleanup()) {
String[] taskTrackers = info.getTaskTrackers();
for(String taskTracker : taskTrackers) {
//Formatting tasktracker to get just its FQDN
taskTracker = UtilsForTests.getFQDNofTT(taskTracker);
LOG.info("taskTracker is :" + taskTracker);
//Collecting the tasktrackers
if (taskTracker != null)
taskTrackerCollection.add(taskTracker);
}
}
}
}
//Making sure that the job is complete.
while (jInfo != null && !jInfo.getStatus().isJobComplete()) {
Thread.sleep(10000);
jInfo = wovenClient.getJobInfo(rJob.getID());
}
} while (continueLoop);
}
}
| true | true | public void testDistributedCache() throws Exception {
Configuration conf = new Configuration(cluster.getConf());
JTProtocol wovenClient = cluster.getJTClient().getProxy();
//This counter will check for count of a loop,
//which might become infinite.
int count = 0;
//This boolean will decide whether to run job again
boolean continueLoop = true;
//counter for job Loop
int countLoop = 0;
//This counter increases with all the tasktrackers in which tasks ran
int taskTrackerCounter = 0;
//This will store all the tasktrackers in which tasks ran
ArrayList<String> taskTrackerCollection = new ArrayList<String>();
//This boolean tells if two tasks ran onteh same tasktracker or not
boolean taskTrackerFound = false;
do {
SleepJob job = new SleepJob();
job.setConf(conf);
conf = job.setupJobConf(5, 1, 1000, 1000, 100, 100);
//Before starting, Modify the file
String input = "This will be the content of\n" + "distributed cache\n";
//Creating the path with the file
DataOutputStream file =
UtilsForTests.createTmpFileDFS(dfs, URIPATH, permission, input);
DistributedCache.createSymlink(conf);
URI uri = URI.create(uriPath);
DistributedCache.addCacheFile(uri, conf);
JobConf jconf = new JobConf(conf);
//Controls the job till all verification is done
FinishTaskControlAction.configureControlActionForJob(conf);
//Submitting the job
RunningJob rJob = cluster.getJTClient().getClient().submitJob(jconf);
//counter for job Loop
countLoop++;
TTClient tClient = null;
JobInfo jInfo = wovenClient.getJobInfo(rJob.getID());
LOG.info("jInfo is :" + jInfo);
//Assert if jobInfo is null
Assert.assertNotNull("jobInfo is null", jInfo);
//Wait for the job to start running.
count = 0;
while (jInfo.getStatus().getRunState() != JobStatus.RUNNING) {
UtilsForTests.waitFor(10000);
count++;
jInfo = wovenClient.getJobInfo(rJob.getID());
//If the count goes beyond a point, then break; This is to avoid
//infinite loop under unforeseen circumstances. Testcase will anyway
//fail later.
if (count > 10) {
Assert.fail("job has not reached running state for more than" +
"100 seconds. Failing at this point");
}
}
LOG.info("job id is :" + rJob.getID().toString());
TaskInfo[] taskInfos = cluster.getJTClient().getProxy()
.getTaskInfo(rJob.getID());
boolean distCacheFileIsFound;
for (TaskInfo taskInfo : taskInfos) {
distCacheFileIsFound = false;
String[] taskTrackers = taskInfo.getTaskTrackers();
for (String taskTracker : taskTrackers) {
//Formatting tasktracker to get just its FQDN
taskTracker = UtilsForTests.getFQDNofTT(taskTracker);
LOG.info("taskTracker is :" + taskTracker);
//The tasktrackerFound variable is initialized
taskTrackerFound = false;
//This will be entered from the second job onwards
if (countLoop > 1) {
if (taskTracker != null) {
continueLoop = taskTrackerCollection.contains(taskTracker);
}
if (continueLoop) {
taskTrackerFound = true;
}
}
//Collecting the tasktrackers
if (taskTracker != null)
taskTrackerCollection.add(taskTracker);
//we have loopped through two times to look for task
//getting submitted on same tasktrackers.The same tasktracker
//for subsequent jobs was not hit maybe because of many number
//of tasktrackers. So, testcase has to stop here.
if (countLoop > 1) {
continueLoop = false;
}
tClient = cluster.getTTClient(taskTracker);
//tClient maybe null because the task is already dead. Ex: setup
if (tClient == null) {
continue;
}
String[] localDirs = tClient.getMapredLocalDirs();
int distributedFileCount = 0;
//Go to every single path
for (String localDir : localDirs) {
//Public Distributed cache will always be stored under
//mapre.local.dir/tasktracker/archive
localDir = localDir + Path.SEPARATOR +
TaskTracker.getPublicDistributedCacheDir();
LOG.info("localDir is : " + localDir);
//Get file status of all the directories
//and files under that path.
FileStatus[] fileStatuses = tClient.listStatus(localDir,
true, true);
for (FileStatus fileStatus : fileStatuses) {
Path path = fileStatus.getPath();
LOG.info("path is :" + path.toString());
//Checking if the received path ends with
//the distributed filename
distCacheFileIsFound = (path.toString()).
endsWith(distributedFileName);
//If file is found, check for its permission.
//Since the file is found break out of loop
if (distCacheFileIsFound){
LOG.info("PATH found is :" + path.toString());
distributedFileCount++;
String filename = path.getName();
FsPermission fsPerm = fileStatus.getPermission();
Assert.assertTrue("File Permission is not 777",
fsPerm.equals(new FsPermission("777")));
}
}
}
LOG.debug("The distributed FileCount is :" + distributedFileCount);
LOG.debug("The taskTrackerFound is :" + taskTrackerFound);
// If distributed cache is modified in dfs
// between two job runs, it can be present more than once
// in any of the task tracker, in which job ran.
if (distributedFileCount != 2 && taskTrackerFound) {
Assert.fail("The distributed cache file has to be two. " +
"But found was " + distributedFileCount);
} else if (distributedFileCount > 1 && !taskTrackerFound) {
Assert.fail("The distributed cache file cannot more than one." +
" But found was " + distributedFileCount);
} else if (distributedFileCount < 1)
Assert.fail("The distributed cache file is less than one. " +
"But found was " + distributedFileCount);
if (!distCacheFileIsFound) {
Assert.assertEquals("The distributed cache file does not exist",
distCacheFileIsFound, false);
}
}
}
//Allow the job to continue through MR control job.
for (TaskInfo taskInfoRemaining : taskInfos) {
FinishTaskControlAction action = new FinishTaskControlAction(TaskID
.downgrade(taskInfoRemaining.getTaskID()));
Collection<TTClient> tts = cluster.getTTClients();
for (TTClient cli : tts) {
cli.getProxy().sendAction(action);
}
}
//Killing the job because all the verification needed
//for this testcase is completed.
rJob.killJob();
//Waiting for 3 seconds for cleanup to start
Thread.sleep(3000);
//Getting the last cleanup task's tasktracker also, as
//distributed cache gets uploaded even during cleanup.
TaskInfo[] myTaskInfos = wovenClient.getTaskInfo(rJob.getID());
if (myTaskInfos != null) {
for(TaskInfo info : myTaskInfos) {
if(info.isSetupOrCleanup()) {
String[] taskTrackers = info.getTaskTrackers();
for(String taskTracker : taskTrackers) {
//Formatting tasktracker to get just its FQDN
taskTracker = UtilsForTests.getFQDNofTT(taskTracker);
LOG.info("taskTracker is :" + taskTracker);
//Collecting the tasktrackers
if (taskTracker != null)
taskTrackerCollection.add(taskTracker);
}
}
}
}
//Making sure that the job is complete.
while (jInfo != null && !jInfo.getStatus().isJobComplete()) {
Thread.sleep(10000);
jInfo = wovenClient.getJobInfo(rJob.getID());
}
} while (continueLoop);
}
| public void testDistributedCache() throws Exception {
Configuration conf = new Configuration(cluster.getConf());
JTProtocol wovenClient = cluster.getJTClient().getProxy();
//This counter will check for count of a loop,
//which might become infinite.
int count = 0;
//This boolean will decide whether to run job again
boolean continueLoop = true;
//counter for job Loop
int countLoop = 0;
//This counter increases with all the tasktrackers in which tasks ran
int taskTrackerCounter = 0;
//This will store all the tasktrackers in which tasks ran
ArrayList<String> taskTrackerCollection = new ArrayList<String>();
//This boolean tells if two tasks ran onteh same tasktracker or not
boolean taskTrackerFound = false;
do {
SleepJob job = new SleepJob();
job.setConf(conf);
conf = job.setupJobConf(5, 1, 1000, 1000, 100, 100);
conf.setBoolean("mapreduce.job.complete.cancel.delegation.tokens", false);
//Before starting, Modify the file
String input = "This will be the content of\n" + "distributed cache\n";
//Creating the path with the file
DataOutputStream file =
UtilsForTests.createTmpFileDFS(dfs, URIPATH, permission, input);
DistributedCache.createSymlink(conf);
URI uri = URI.create(uriPath);
DistributedCache.addCacheFile(uri, conf);
JobConf jconf = new JobConf(conf);
//Controls the job till all verification is done
FinishTaskControlAction.configureControlActionForJob(conf);
//Submitting the job
RunningJob rJob = cluster.getJTClient().getClient().submitJob(jconf);
//counter for job Loop
countLoop++;
TTClient tClient = null;
JobInfo jInfo = wovenClient.getJobInfo(rJob.getID());
LOG.info("jInfo is :" + jInfo);
//Assert if jobInfo is null
Assert.assertNotNull("jobInfo is null", jInfo);
//Wait for the job to start running.
count = 0;
while (jInfo.getStatus().getRunState() != JobStatus.RUNNING) {
UtilsForTests.waitFor(10000);
count++;
jInfo = wovenClient.getJobInfo(rJob.getID());
//If the count goes beyond a point, then break; This is to avoid
//infinite loop under unforeseen circumstances. Testcase will anyway
//fail later.
if (count > 10) {
Assert.fail("job has not reached running state for more than" +
"100 seconds. Failing at this point");
}
}
LOG.info("job id is :" + rJob.getID().toString());
TaskInfo[] taskInfos = cluster.getJTClient().getProxy()
.getTaskInfo(rJob.getID());
boolean distCacheFileIsFound;
for (TaskInfo taskInfo : taskInfos) {
distCacheFileIsFound = false;
String[] taskTrackers = taskInfo.getTaskTrackers();
for (String taskTracker : taskTrackers) {
//Formatting tasktracker to get just its FQDN
taskTracker = UtilsForTests.getFQDNofTT(taskTracker);
LOG.info("taskTracker is :" + taskTracker);
//The tasktrackerFound variable is initialized
taskTrackerFound = false;
//This will be entered from the second job onwards
if (countLoop > 1) {
if (taskTracker != null) {
continueLoop = taskTrackerCollection.contains(taskTracker);
}
if (continueLoop) {
taskTrackerFound = true;
}
}
//Collecting the tasktrackers
if (taskTracker != null)
taskTrackerCollection.add(taskTracker);
//we have loopped through two times to look for task
//getting submitted on same tasktrackers.The same tasktracker
//for subsequent jobs was not hit maybe because of many number
//of tasktrackers. So, testcase has to stop here.
if (countLoop > 1) {
continueLoop = false;
}
tClient = cluster.getTTClient(taskTracker);
//tClient maybe null because the task is already dead. Ex: setup
if (tClient == null) {
continue;
}
String[] localDirs = tClient.getMapredLocalDirs();
int distributedFileCount = 0;
//Go to every single path
for (String localDir : localDirs) {
//Public Distributed cache will always be stored under
//mapre.local.dir/tasktracker/archive
localDir = localDir + Path.SEPARATOR +
TaskTracker.getPublicDistributedCacheDir();
LOG.info("localDir is : " + localDir);
//Get file status of all the directories
//and files under that path.
FileStatus[] fileStatuses = tClient.listStatus(localDir,
true, true);
for (FileStatus fileStatus : fileStatuses) {
Path path = fileStatus.getPath();
LOG.info("path is :" + path.toString());
//Checking if the received path ends with
//the distributed filename
distCacheFileIsFound = (path.toString()).
endsWith(distributedFileName);
//If file is found, check for its permission.
//Since the file is found break out of loop
if (distCacheFileIsFound){
LOG.info("PATH found is :" + path.toString());
distributedFileCount++;
String filename = path.getName();
FsPermission fsPerm = fileStatus.getPermission();
Assert.assertTrue("File Permission is not 777",
fsPerm.equals(new FsPermission("777")));
}
}
}
LOG.debug("The distributed FileCount is :" + distributedFileCount);
LOG.debug("The taskTrackerFound is :" + taskTrackerFound);
// If distributed cache is modified in dfs
// between two job runs, it can be present more than once
// in any of the task tracker, in which job ran.
if (distributedFileCount != 2 && taskTrackerFound) {
Assert.fail("The distributed cache file has to be two. " +
"But found was " + distributedFileCount);
} else if (distributedFileCount > 1 && !taskTrackerFound) {
Assert.fail("The distributed cache file cannot more than one." +
" But found was " + distributedFileCount);
} else if (distributedFileCount < 1)
Assert.fail("The distributed cache file is less than one. " +
"But found was " + distributedFileCount);
if (!distCacheFileIsFound) {
Assert.assertEquals("The distributed cache file does not exist",
distCacheFileIsFound, false);
}
}
}
//Allow the job to continue through MR control job.
for (TaskInfo taskInfoRemaining : taskInfos) {
FinishTaskControlAction action = new FinishTaskControlAction(TaskID
.downgrade(taskInfoRemaining.getTaskID()));
Collection<TTClient> tts = cluster.getTTClients();
for (TTClient cli : tts) {
cli.getProxy().sendAction(action);
}
}
//Killing the job because all the verification needed
//for this testcase is completed.
rJob.killJob();
//Waiting for 3 seconds for cleanup to start
Thread.sleep(3000);
//Getting the last cleanup task's tasktracker also, as
//distributed cache gets uploaded even during cleanup.
TaskInfo[] myTaskInfos = wovenClient.getTaskInfo(rJob.getID());
if (myTaskInfos != null) {
for(TaskInfo info : myTaskInfos) {
if(info.isSetupOrCleanup()) {
String[] taskTrackers = info.getTaskTrackers();
for(String taskTracker : taskTrackers) {
//Formatting tasktracker to get just its FQDN
taskTracker = UtilsForTests.getFQDNofTT(taskTracker);
LOG.info("taskTracker is :" + taskTracker);
//Collecting the tasktrackers
if (taskTracker != null)
taskTrackerCollection.add(taskTracker);
}
}
}
}
//Making sure that the job is complete.
while (jInfo != null && !jInfo.getStatus().isJobComplete()) {
Thread.sleep(10000);
jInfo = wovenClient.getJobInfo(rJob.getID());
}
} while (continueLoop);
}
|
diff --git a/src/org/acl/root/IncomingCallScanner.java b/src/org/acl/root/IncomingCallScanner.java
index 486c746..0c92782 100644
--- a/src/org/acl/root/IncomingCallScanner.java
+++ b/src/org/acl/root/IncomingCallScanner.java
@@ -1,223 +1,224 @@
package org.acl.root;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.acl.root.core.BlackList;
import org.acl.root.observers.CallObserver;
import org.acl.root.observers.Logger;
import org.acl.root.observers.UserNotifier;
import org.acl.root.utils.CallInfo;
import org.acl.root.utils.Contact;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Binder;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
/**
* This is the service responsible of capturing incoming calls and
* perform the required actions.
*
* @author Francisco P�rez-Sorrosal (fperez)
*
*/
public class IncomingCallScanner extends Service {
private static final String TAG = "IncomingCallScanner";
private boolean filterAllCalls = false;
private AudioManager am;
private int currentAudioMode;
/****************************************
* Binder class
****************************************/
public class LocalBinder extends Binder {
IncomingCallScanner getService() {
return IncomingCallScanner.this;
}
}
private final IBinder mBinder = new LocalBinder();
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private BroadcastReceiver phoneStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
Log.d(TAG, "Call State=" + state);
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
Log.d(TAG, "Idle");
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
} else if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
String incomingNumber = intent
.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.d(TAG, "Incoming call " + incomingNumber);
if(filterAllCalls || BlackList.INSTANCE.containsContact(incomingNumber)) {
// Telephony actions
if (!killCall(context)) {
Log.e(TAG, "Unable to kill incoming call");
}
// Get relevant call info and notify observers
CallInfo.Builder callInfoBuilder = new CallInfo.Builder(getApplicationContext(), incomingNumber);
Contact contact = BlackList.INSTANCE.getContact(incomingNumber);
if (contact != null) {
callInfoBuilder.caller(contact.getName()).
emailAddresses(contact.getEmailAddresses());
}
notifyCallObservers(callInfoBuilder.build());
UserNotifier.INSTANCE.showCallScannerNotification(getApplicationContext(),
UserNotifier.CallScannerNotification.INCOMING_CALL);
} else {
am.setRingerMode(currentAudioMode);
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
Log.d(TAG, "Offhook");
+ am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
} else if (intent.getAction().equals(
"android.intent.action.NEW_OUTGOING_CALL")) {
// Outgoing call: DO NOTHING at this time
// String outgoingNumber = intent
// .getStringExtra(Intent.EXTRA_PHONE_NUMBER);
// Log.d(TAG, "Outgoing call " + outgoingNumber);
// setResultData(null); // Kills the outgoing call
} else {
Log.e(TAG, "Unexpected intent.action=" + intent.getAction());
}
}
};
// ------------------------- Lifecycle -------------------------
@Override
public void onCreate() {
// Add the log and UserNotifier as default observers
addCallObserver(Logger.INSTANCE);
addCallObserver(UserNotifier.INSTANCE);
BlackList.INSTANCE.loadFromFile(getApplicationContext());
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
currentAudioMode = am.getRingerMode();
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
registerReceiver(phoneStateReceiver, filter);
Log.d(TAG, "Created");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Received start id " + startId + ": " + intent);
UserNotifier.INSTANCE.showCallScannerNotification(getApplicationContext(),
UserNotifier.CallScannerNotification.INIT);
// Service will continue running (sticky) until it's explicitly stopped
return START_STICKY;
}
@Override
public void onDestroy() {
BlackList.INSTANCE.saveToFile(getApplicationContext());
// Stop filtering calls, otherwise they'll continue to be filtered
am.setRingerMode(currentAudioMode);
am = null;
unregisterReceiver(phoneStateReceiver);
removeCallObserver(Logger.INSTANCE);
removeCallObserver(UserNotifier.INSTANCE);
UserNotifier.INSTANCE.cancelCallScannerNotification(getApplicationContext());
Toast.makeText(getApplicationContext(), R.string.ics_service_stopped, Toast.LENGTH_SHORT).show();
Log.d(TAG, "Stopped");
}
// ------------------------ End Lifecycle ---------------------------------
private boolean killCall(Context context) {
try {
// Get the boring old TelephonyManager
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
// Get the getITelephony() method
Class classTelephony = Class.forName(telephonyManager.getClass()
.getName());
Method methodGetITelephony = classTelephony
.getDeclaredMethod("getITelephony");
// Ignore that the method is supposed to be private
methodGetITelephony.setAccessible(true);
// Invoke getITelephony() to get the ITelephony interface
Object telephonyInterface = methodGetITelephony
.invoke(telephonyManager);
// Get the endCall method from ITelephony
Class telephonyInterfaceClass = Class.forName(telephonyInterface
.getClass().getName());
Method methodEndCall = telephonyInterfaceClass
.getDeclaredMethod("endCall");
// Invoke endCall()
methodEndCall.invoke(telephonyInterface);
} catch (Exception e) { // Many things can go wrong with reflection
Log.e(TAG, e.toString());
return false;
}
return true;
}
public void filterAllCalls(boolean decision) {
filterAllCalls = decision;
}
public boolean isAllCallsFilterEnabled() {
return (filterAllCalls == true);
}
/**
* Observer pattern for call observers
*/
private List<CallObserver> callObservers =
new ArrayList<CallObserver>();
public int nofObservers() {
return callObservers.size();
}
public void addCallObserver(CallObserver observer) {
callObservers.add(observer);
}
public void removeCallObserver(CallObserver observer) {
callObservers.remove(observer);
}
public boolean containsObserver(CallObserver observer) {
return (callObservers.contains(observer));
}
private void notifyCallObservers(CallInfo callInfo) {
for(CallObserver observer : callObservers) {
observer.callNotification(callInfo);
}
}
}
| true | true | public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
Log.d(TAG, "Call State=" + state);
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
Log.d(TAG, "Idle");
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
} else if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
String incomingNumber = intent
.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.d(TAG, "Incoming call " + incomingNumber);
if(filterAllCalls || BlackList.INSTANCE.containsContact(incomingNumber)) {
// Telephony actions
if (!killCall(context)) {
Log.e(TAG, "Unable to kill incoming call");
}
// Get relevant call info and notify observers
CallInfo.Builder callInfoBuilder = new CallInfo.Builder(getApplicationContext(), incomingNumber);
Contact contact = BlackList.INSTANCE.getContact(incomingNumber);
if (contact != null) {
callInfoBuilder.caller(contact.getName()).
emailAddresses(contact.getEmailAddresses());
}
notifyCallObservers(callInfoBuilder.build());
UserNotifier.INSTANCE.showCallScannerNotification(getApplicationContext(),
UserNotifier.CallScannerNotification.INCOMING_CALL);
} else {
am.setRingerMode(currentAudioMode);
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
Log.d(TAG, "Offhook");
}
} else if (intent.getAction().equals(
"android.intent.action.NEW_OUTGOING_CALL")) {
// Outgoing call: DO NOTHING at this time
// String outgoingNumber = intent
// .getStringExtra(Intent.EXTRA_PHONE_NUMBER);
// Log.d(TAG, "Outgoing call " + outgoingNumber);
// setResultData(null); // Kills the outgoing call
} else {
Log.e(TAG, "Unexpected intent.action=" + intent.getAction());
}
}
| public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
Log.d(TAG, "Call State=" + state);
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
Log.d(TAG, "Idle");
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
} else if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
String incomingNumber = intent
.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.d(TAG, "Incoming call " + incomingNumber);
if(filterAllCalls || BlackList.INSTANCE.containsContact(incomingNumber)) {
// Telephony actions
if (!killCall(context)) {
Log.e(TAG, "Unable to kill incoming call");
}
// Get relevant call info and notify observers
CallInfo.Builder callInfoBuilder = new CallInfo.Builder(getApplicationContext(), incomingNumber);
Contact contact = BlackList.INSTANCE.getContact(incomingNumber);
if (contact != null) {
callInfoBuilder.caller(contact.getName()).
emailAddresses(contact.getEmailAddresses());
}
notifyCallObservers(callInfoBuilder.build());
UserNotifier.INSTANCE.showCallScannerNotification(getApplicationContext(),
UserNotifier.CallScannerNotification.INCOMING_CALL);
} else {
am.setRingerMode(currentAudioMode);
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
Log.d(TAG, "Offhook");
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
} else if (intent.getAction().equals(
"android.intent.action.NEW_OUTGOING_CALL")) {
// Outgoing call: DO NOTHING at this time
// String outgoingNumber = intent
// .getStringExtra(Intent.EXTRA_PHONE_NUMBER);
// Log.d(TAG, "Outgoing call " + outgoingNumber);
// setResultData(null); // Kills the outgoing call
} else {
Log.e(TAG, "Unexpected intent.action=" + intent.getAction());
}
}
|
diff --git a/GnuBackgammon/src/it/alcacoop/gnubackgammon/layers/GameScreen.java b/GnuBackgammon/src/it/alcacoop/gnubackgammon/layers/GameScreen.java
index 88adced..ed0e3cd 100644
--- a/GnuBackgammon/src/it/alcacoop/gnubackgammon/layers/GameScreen.java
+++ b/GnuBackgammon/src/it/alcacoop/gnubackgammon/layers/GameScreen.java
@@ -1,103 +1,103 @@
package it.alcacoop.gnubackgammon.layers;
import it.alcacoop.gnubackgammon.GnuBackgammon;
import it.alcacoop.gnubackgammon.actors.Board;
import it.alcacoop.gnubackgammon.actors.IconButton;
import it.alcacoop.gnubackgammon.logic.AICalls;
import it.alcacoop.gnubackgammon.logic.AILevels;
import it.alcacoop.gnubackgammon.logic.FSM;
import it.alcacoop.gnubackgammon.logic.FSM.Events;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
public class GameScreen implements Screen {
private Stage stage;
private final Board board;
public static FSM fsm;
private SpriteBatch sb;
private TextureRegion bgRegion;
public GameScreen(GnuBackgammon bg){
sb = new SpriteBatch();
//STAGE DIM = SCREEN RES
stage = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
//VIEWPORT DIM = VIRTUAL RES (ON SELECTED TEXTURE BASIS)
stage.setViewport(GnuBackgammon.resolution[0], GnuBackgammon.resolution[1], false);
bgRegion = GnuBackgammon.atlas.findRegion("bg");
board = new Board();
stage.addActor(board);
IconButton undo = new IconButton("back", new InputListener() {
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
board.undoMove();
return true;
}
});
undo.setX(860);
- undo.setY(550);
+ undo.setY(570);
stage.addActor(undo);
fsm = new FSM(board);
fsm.start();
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
sb.begin();
sb.draw(bgRegion, 0,0 , Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
sb.end();
stage.act(delta);
stage.draw();
}
@Override
public void resize(int width, int height) {
System.out.println("DIMS: "+Gdx.graphics.getWidth()+"x"+Gdx.graphics.getHeight());
}
@Override
public void show() {
board.initBoard();
Gdx.input.setInputProcessor(stage);
AICalls.SetAILevel(AILevels.GRANDMASTER);
fsm.processEvent(Events.START, null);
}
@Override
public void hide() {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void dispose() {
}
}
| true | true | public GameScreen(GnuBackgammon bg){
sb = new SpriteBatch();
//STAGE DIM = SCREEN RES
stage = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
//VIEWPORT DIM = VIRTUAL RES (ON SELECTED TEXTURE BASIS)
stage.setViewport(GnuBackgammon.resolution[0], GnuBackgammon.resolution[1], false);
bgRegion = GnuBackgammon.atlas.findRegion("bg");
board = new Board();
stage.addActor(board);
IconButton undo = new IconButton("back", new InputListener() {
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
board.undoMove();
return true;
}
});
undo.setX(860);
undo.setY(550);
stage.addActor(undo);
fsm = new FSM(board);
fsm.start();
}
| public GameScreen(GnuBackgammon bg){
sb = new SpriteBatch();
//STAGE DIM = SCREEN RES
stage = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
//VIEWPORT DIM = VIRTUAL RES (ON SELECTED TEXTURE BASIS)
stage.setViewport(GnuBackgammon.resolution[0], GnuBackgammon.resolution[1], false);
bgRegion = GnuBackgammon.atlas.findRegion("bg");
board = new Board();
stage.addActor(board);
IconButton undo = new IconButton("back", new InputListener() {
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
board.undoMove();
return true;
}
});
undo.setX(860);
undo.setY(570);
stage.addActor(undo);
fsm = new FSM(board);
fsm.start();
}
|
diff --git a/pingpongnet/src/test/java/ping/pong/net/connection/io/IoUdpWriteRunnableTest.java b/pingpongnet/src/test/java/ping/pong/net/connection/io/IoUdpWriteRunnableTest.java
index 3703235..76b3f70 100644
--- a/pingpongnet/src/test/java/ping/pong/net/connection/io/IoUdpWriteRunnableTest.java
+++ b/pingpongnet/src/test/java/ping/pong/net/connection/io/IoUdpWriteRunnableTest.java
@@ -1,202 +1,202 @@
package ping.pong.net.connection.io;
import java.net.InetSocketAddress;
import ping.pong.net.connection.DisconnectState;
import java.net.SocketException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.DatagramSocket;
import ping.pong.net.connection.RunnableEventListener;
import ping.pong.net.connection.config.ConnectionConfiguration;
import ping.pong.net.connection.messaging.Envelope;
import ping.pong.net.connection.messaging.MessageProcessor;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import ping.pong.net.connection.config.ConnectionConfigFactory;
import static org.junit.Assert.*;
/**
*
* @author mfullen
*/
public class IoUdpWriteRunnableTest
{
private static final Logger logger = LoggerFactory.getLogger(IoUdpWriteRunnableTest.class);
public IoUdpWriteRunnableTest()
{
}
@BeforeClass
public static void setUpClass() throws Exception
{
}
@AfterClass
public static void tearDownClass() throws Exception
{
}
@Test
public void testSendByte() throws SocketException, InterruptedException
{
- ConnectionConfiguration config = ConnectionConfigFactory.createPPNConfig("localhost", 9007, 9009, false);
+ ConnectionConfiguration config = ConnectionConfigFactory.createPPNConfig("localhost", 9007, 9089, false);
final String message = "hello world";
DatagramSocket udpSocket = new DatagramSocket(config.getUdpPort());
ByteMessageProcessorImpl messageProcessorImpl = new ByteMessageProcessorImpl();
IoUdpReadRunnable<byte[]> ioUdpReadRunnable = new IoUdpReadRunnable<byte[]>(messageProcessorImpl, new RunnableEventListener()
{
@Override
public void onRunnableClosed(DisconnectState disconnectState)
{
logger.debug("Close called {}", disconnectState);
}
}, udpSocket);
Thread thread = new Thread(ioUdpReadRunnable);
thread.start();
DatagramSocket clientUdpSocket = new DatagramSocket();
IoUdpWriteRunnable<byte[]> ioUdpWriteRunnable = new IoUdpWriteRunnable<byte[]>(new InetSocketAddress(config.getIpAddress(), config.getUdpPort()), new RunnableEventListener()
{
@Override
public void onRunnableClosed(DisconnectState disconnectState)
{
logger.debug("Close called {}", disconnectState);
}
}, clientUdpSocket);
ioUdpWriteRunnable.enqueueMessage(message.getBytes());
Thread writethread = new Thread(ioUdpWriteRunnable);
writethread.start();
writethread.join(20);
thread.join(50);
assertEquals(messageProcessorImpl.myMessage, message);
ioUdpReadRunnable.close();
ioUdpWriteRunnable.close();
}
@Test
public void testSendObject() throws SocketException, InterruptedException
{
ConnectionConfiguration config = ConnectionConfigFactory.createPPNConfig("localhost", 9007, 9009, false);
final String message = "hello world2";
DatagramSocket udpSocket = new DatagramSocket(config.getUdpPort());
StringMessageProcessor messageProcessorImpl = new StringMessageProcessor();
IoUdpReadRunnable<String> ioUdpReadRunnable = new IoUdpReadRunnable<String>(messageProcessorImpl, new RunnableEventListener()
{
@Override
public void onRunnableClosed(DisconnectState disconnectState)
{
logger.debug("Close called {}", disconnectState);
}
}, udpSocket);
Thread thread = new Thread(ioUdpReadRunnable);
thread.start();
DatagramSocket clientUdpSocket = new DatagramSocket();
IoUdpWriteRunnable<String> ioUdpWriteRunnable = new IoUdpWriteRunnable<String>(new InetSocketAddress(config.getIpAddress(), config.getUdpPort()), new RunnableEventListener()
{
@Override
public void onRunnableClosed(DisconnectState disconnectState)
{
logger.debug("Close called {}", disconnectState);
}
}, clientUdpSocket);
ioUdpWriteRunnable.enqueueMessage(message);
Thread writethread = new Thread(ioUdpWriteRunnable);
writethread.start();
writethread.join(50);
thread.join(100);
assertEquals(messageProcessorImpl.myMessage, message);
ioUdpReadRunnable.close();
ioUdpWriteRunnable.close();
}
/**
* Test of close method, of class IoUdpWriteRunnable.
*/
@Test
public void testClose()
{
}
/**
* Test of isRunning method, of class IoUdpWriteRunnable.
*/
@Test
public void testIsRunning()
{
}
/**
* Test of enqueueMessage method, of class IoUdpWriteRunnable.
*/
@Test
public void testEnqueueMessage()
{
}
/**
* Test of run method, of class IoUdpWriteRunnable.
*/
@Test
public void testRun()
{
}
class ByteMessageProcessorImpl implements MessageProcessor<byte[]>
{
public ByteMessageProcessorImpl()
{
}
public String myMessage = null;
@Override
public void enqueueReceivedMessage(byte[] byteMessage)
{
// logger.info("byte received: {}", byteMessage);
String string = new String(byteMessage);
logger.debug("Message Received {}", string);
myMessage = string;
}
@Override
public void enqueueMessageToWrite(Envelope message)
{
throw new UnsupportedOperationException("Not supported yet.");
}
}
private class StringMessageProcessor implements MessageProcessor<String>
{
public StringMessageProcessor()
{
}
public String myMessage = null;
@Override
public void enqueueReceivedMessage(String message)
{
// logger.info("byte received: {}", byteMessage);
String string = message;
logger.debug("Message Received {}", string);
myMessage = string;
}
@Override
public void enqueueMessageToWrite(Envelope<String> message)
{
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
| true | true | public void testSendByte() throws SocketException, InterruptedException
{
ConnectionConfiguration config = ConnectionConfigFactory.createPPNConfig("localhost", 9007, 9009, false);
final String message = "hello world";
DatagramSocket udpSocket = new DatagramSocket(config.getUdpPort());
ByteMessageProcessorImpl messageProcessorImpl = new ByteMessageProcessorImpl();
IoUdpReadRunnable<byte[]> ioUdpReadRunnable = new IoUdpReadRunnable<byte[]>(messageProcessorImpl, new RunnableEventListener()
{
@Override
public void onRunnableClosed(DisconnectState disconnectState)
{
logger.debug("Close called {}", disconnectState);
}
}, udpSocket);
Thread thread = new Thread(ioUdpReadRunnable);
thread.start();
DatagramSocket clientUdpSocket = new DatagramSocket();
IoUdpWriteRunnable<byte[]> ioUdpWriteRunnable = new IoUdpWriteRunnable<byte[]>(new InetSocketAddress(config.getIpAddress(), config.getUdpPort()), new RunnableEventListener()
{
@Override
public void onRunnableClosed(DisconnectState disconnectState)
{
logger.debug("Close called {}", disconnectState);
}
}, clientUdpSocket);
ioUdpWriteRunnable.enqueueMessage(message.getBytes());
Thread writethread = new Thread(ioUdpWriteRunnable);
writethread.start();
writethread.join(20);
thread.join(50);
assertEquals(messageProcessorImpl.myMessage, message);
ioUdpReadRunnable.close();
ioUdpWriteRunnable.close();
}
| public void testSendByte() throws SocketException, InterruptedException
{
ConnectionConfiguration config = ConnectionConfigFactory.createPPNConfig("localhost", 9007, 9089, false);
final String message = "hello world";
DatagramSocket udpSocket = new DatagramSocket(config.getUdpPort());
ByteMessageProcessorImpl messageProcessorImpl = new ByteMessageProcessorImpl();
IoUdpReadRunnable<byte[]> ioUdpReadRunnable = new IoUdpReadRunnable<byte[]>(messageProcessorImpl, new RunnableEventListener()
{
@Override
public void onRunnableClosed(DisconnectState disconnectState)
{
logger.debug("Close called {}", disconnectState);
}
}, udpSocket);
Thread thread = new Thread(ioUdpReadRunnable);
thread.start();
DatagramSocket clientUdpSocket = new DatagramSocket();
IoUdpWriteRunnable<byte[]> ioUdpWriteRunnable = new IoUdpWriteRunnable<byte[]>(new InetSocketAddress(config.getIpAddress(), config.getUdpPort()), new RunnableEventListener()
{
@Override
public void onRunnableClosed(DisconnectState disconnectState)
{
logger.debug("Close called {}", disconnectState);
}
}, clientUdpSocket);
ioUdpWriteRunnable.enqueueMessage(message.getBytes());
Thread writethread = new Thread(ioUdpWriteRunnable);
writethread.start();
writethread.join(20);
thread.join(50);
assertEquals(messageProcessorImpl.myMessage, message);
ioUdpReadRunnable.close();
ioUdpWriteRunnable.close();
}
|
diff --git a/src/net/machinemuse/numina/recipe/SimpleItemMaker.java b/src/net/machinemuse/numina/recipe/SimpleItemMaker.java
index 3e4ee50..2728f0b 100644
--- a/src/net/machinemuse/numina/recipe/SimpleItemMaker.java
+++ b/src/net/machinemuse/numina/recipe/SimpleItemMaker.java
@@ -1,64 +1,65 @@
package net.machinemuse.numina.recipe;
import net.machinemuse.numina.general.MuseLogger;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.oredict.OreDictionary;
/**
* Author: MachineMuse (Claire Semple)
* Created: 2:55 PM, 11/4/13
*/
public class SimpleItemMaker implements IItemMaker {
public Integer id;
public Integer meta;
public Integer quantity;
public String unlocalizedName;
public String oredictName;
public NBTTagCompound nbt;
@Override
public ItemStack makeItem(InventoryCrafting i) {
return getRecipeOutput();
}
private int getOrElse(Integer input, int defaultval) {
if (input == null)
return defaultval;
else
return input;
}
@Override
public ItemStack getRecipeOutput() {
int newmeta = getOrElse(this.meta, 0);
int newquantity = getOrElse(this.quantity, 1);
if (id != null) {
ItemStack stack = new ItemStack(id, newquantity, newmeta);
if (nbt != null) stack.stackTagCompound = (NBTTagCompound) nbt.copy();
return stack;
} else if (oredictName != null) {
try {
ItemStack stack = OreDictionary.getOres(oredictName).get(0).copy();
stack.stackSize = newquantity;
return stack;
} catch (Exception e) {
MuseLogger.logError("Unable to load " + oredictName + " from oredict");
return null;
}
} else if (unlocalizedName != null) {
try {
- ItemStack stack = ItemNameMappings.getItem(unlocalizedName);
+ ItemStack stack = ItemNameMappings.getItem(unlocalizedName).copy();
+ newmeta = getOrElse(this.meta, stack.getItemDamage());
stack.setItemDamage(newmeta);
stack.stackSize = newquantity;
return stack;
} catch (Exception e) {
MuseLogger.logError("Unable to load " + unlocalizedName + " from unlocalized names");
return null;
}
} else {
return null;
}
}
}
| true | true | public ItemStack getRecipeOutput() {
int newmeta = getOrElse(this.meta, 0);
int newquantity = getOrElse(this.quantity, 1);
if (id != null) {
ItemStack stack = new ItemStack(id, newquantity, newmeta);
if (nbt != null) stack.stackTagCompound = (NBTTagCompound) nbt.copy();
return stack;
} else if (oredictName != null) {
try {
ItemStack stack = OreDictionary.getOres(oredictName).get(0).copy();
stack.stackSize = newquantity;
return stack;
} catch (Exception e) {
MuseLogger.logError("Unable to load " + oredictName + " from oredict");
return null;
}
} else if (unlocalizedName != null) {
try {
ItemStack stack = ItemNameMappings.getItem(unlocalizedName);
stack.setItemDamage(newmeta);
stack.stackSize = newquantity;
return stack;
} catch (Exception e) {
MuseLogger.logError("Unable to load " + unlocalizedName + " from unlocalized names");
return null;
}
} else {
return null;
}
}
| public ItemStack getRecipeOutput() {
int newmeta = getOrElse(this.meta, 0);
int newquantity = getOrElse(this.quantity, 1);
if (id != null) {
ItemStack stack = new ItemStack(id, newquantity, newmeta);
if (nbt != null) stack.stackTagCompound = (NBTTagCompound) nbt.copy();
return stack;
} else if (oredictName != null) {
try {
ItemStack stack = OreDictionary.getOres(oredictName).get(0).copy();
stack.stackSize = newquantity;
return stack;
} catch (Exception e) {
MuseLogger.logError("Unable to load " + oredictName + " from oredict");
return null;
}
} else if (unlocalizedName != null) {
try {
ItemStack stack = ItemNameMappings.getItem(unlocalizedName).copy();
newmeta = getOrElse(this.meta, stack.getItemDamage());
stack.setItemDamage(newmeta);
stack.stackSize = newquantity;
return stack;
} catch (Exception e) {
MuseLogger.logError("Unable to load " + unlocalizedName + " from unlocalized names");
return null;
}
} else {
return null;
}
}
|
diff --git a/osmdroid-android/src/main/java/org/osmdroid/views/overlay/SafeDrawOverlay.java b/osmdroid-android/src/main/java/org/osmdroid/views/overlay/SafeDrawOverlay.java
index 65ff35d..2496796 100644
--- a/osmdroid-android/src/main/java/org/osmdroid/views/overlay/SafeDrawOverlay.java
+++ b/osmdroid-android/src/main/java/org/osmdroid/views/overlay/SafeDrawOverlay.java
@@ -1,90 +1,86 @@
package org.osmdroid.views.overlay;
import org.osmdroid.ResourceProxy;
import org.osmdroid.views.MapView;
import org.osmdroid.views.safecanvas.ISafeCanvas;
import org.osmdroid.views.safecanvas.SafeTranslatedCanvas;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
/**
* An overlay class that uses the safe drawing canvas to draw itself and can be zoomed in to high
* levels without drawing issues.
*
* @see {@link ISafeCanvas}
*/
public abstract class SafeDrawOverlay extends Overlay {
private static final SafeTranslatedCanvas sSafeCanvas = new SafeTranslatedCanvas();
private static final Matrix sMatrix = new Matrix();
private static final float[] sMatrixValues = new float[9];
private boolean mUseSafeCanvas = true;
protected abstract void drawSafe(final ISafeCanvas c, final MapView osmv, final boolean shadow);
public SafeDrawOverlay(Context ctx) {
super(ctx);
}
public SafeDrawOverlay(ResourceProxy pResourceProxy) {
super(pResourceProxy);
}
protected void draw(final Canvas c, final MapView osmv, final boolean shadow) {
sSafeCanvas.setCanvas(c);
if (this.isUsingSafeCanvas()) {
// Find the screen offset
Rect screenRect = osmv.getProjection().getScreenRect();
sSafeCanvas.xOffset = -screenRect.left;
sSafeCanvas.yOffset = -screenRect.top;
// Save the canvas state
c.save();
// Get the matrix values
- c.getMatrix(sMatrix);
+ sMatrix.set(osmv.getMatrix());
sMatrix.getValues(sMatrixValues);
- // If we're rotating, then reverse the rotation for now.
+ // If we're rotating, then reverse the rotation
// This gets us proper MSCALE values in the matrix.
final double angrad = Math.atan2(sMatrixValues[Matrix.MSKEW_Y],
sMatrixValues[Matrix.MSCALE_X]);
sMatrix.preRotate((float) -Math.toDegrees(angrad), screenRect.centerX(),
screenRect.centerY());
// Get the new matrix values to find the scaling factor
sMatrix.getValues(sMatrixValues);
- // Adjust to remove scroll
- sMatrix.postTranslate(screenRect.left * sMatrixValues[Matrix.MSCALE_X], screenRect.top
+ // Shift the canvas to remove scroll, while accounting for scaling values
+ c.translate(screenRect.left * sMatrixValues[Matrix.MSCALE_X], screenRect.top
* sMatrixValues[Matrix.MSCALE_Y]);
- // Put back the rotation.
- sMatrix.preRotate((float) Math.toDegrees(angrad), screenRect.width() / 2,
- screenRect.height() / 2);
- c.setMatrix(sMatrix);
} else {
sSafeCanvas.xOffset = 0;
sSafeCanvas.yOffset = 0;
}
this.drawSafe(sSafeCanvas, osmv, shadow);
if (this.isUsingSafeCanvas()) {
c.restore();
}
}
public boolean isUsingSafeCanvas() {
return mUseSafeCanvas;
}
public void setUseSafeCanvas(boolean useSafeCanvas) {
mUseSafeCanvas = useSafeCanvas;
}
}
| false | true | protected void draw(final Canvas c, final MapView osmv, final boolean shadow) {
sSafeCanvas.setCanvas(c);
if (this.isUsingSafeCanvas()) {
// Find the screen offset
Rect screenRect = osmv.getProjection().getScreenRect();
sSafeCanvas.xOffset = -screenRect.left;
sSafeCanvas.yOffset = -screenRect.top;
// Save the canvas state
c.save();
// Get the matrix values
c.getMatrix(sMatrix);
sMatrix.getValues(sMatrixValues);
// If we're rotating, then reverse the rotation for now.
// This gets us proper MSCALE values in the matrix.
final double angrad = Math.atan2(sMatrixValues[Matrix.MSKEW_Y],
sMatrixValues[Matrix.MSCALE_X]);
sMatrix.preRotate((float) -Math.toDegrees(angrad), screenRect.centerX(),
screenRect.centerY());
// Get the new matrix values to find the scaling factor
sMatrix.getValues(sMatrixValues);
// Adjust to remove scroll
sMatrix.postTranslate(screenRect.left * sMatrixValues[Matrix.MSCALE_X], screenRect.top
* sMatrixValues[Matrix.MSCALE_Y]);
// Put back the rotation.
sMatrix.preRotate((float) Math.toDegrees(angrad), screenRect.width() / 2,
screenRect.height() / 2);
c.setMatrix(sMatrix);
} else {
sSafeCanvas.xOffset = 0;
sSafeCanvas.yOffset = 0;
}
this.drawSafe(sSafeCanvas, osmv, shadow);
if (this.isUsingSafeCanvas()) {
c.restore();
}
}
| protected void draw(final Canvas c, final MapView osmv, final boolean shadow) {
sSafeCanvas.setCanvas(c);
if (this.isUsingSafeCanvas()) {
// Find the screen offset
Rect screenRect = osmv.getProjection().getScreenRect();
sSafeCanvas.xOffset = -screenRect.left;
sSafeCanvas.yOffset = -screenRect.top;
// Save the canvas state
c.save();
// Get the matrix values
sMatrix.set(osmv.getMatrix());
sMatrix.getValues(sMatrixValues);
// If we're rotating, then reverse the rotation
// This gets us proper MSCALE values in the matrix.
final double angrad = Math.atan2(sMatrixValues[Matrix.MSKEW_Y],
sMatrixValues[Matrix.MSCALE_X]);
sMatrix.preRotate((float) -Math.toDegrees(angrad), screenRect.centerX(),
screenRect.centerY());
// Get the new matrix values to find the scaling factor
sMatrix.getValues(sMatrixValues);
// Shift the canvas to remove scroll, while accounting for scaling values
c.translate(screenRect.left * sMatrixValues[Matrix.MSCALE_X], screenRect.top
* sMatrixValues[Matrix.MSCALE_Y]);
} else {
sSafeCanvas.xOffset = 0;
sSafeCanvas.yOffset = 0;
}
this.drawSafe(sSafeCanvas, osmv, shadow);
if (this.isUsingSafeCanvas()) {
c.restore();
}
}
|
diff --git a/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/Cleaner.java b/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/Cleaner.java
index 97ea809..d5b718e 100644
--- a/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/Cleaner.java
+++ b/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/Cleaner.java
@@ -1,198 +1,198 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.buildTriggers.vcs.git;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.SimpleCommandLineProcessRunner;
import jetbrains.buildServer.log.Loggers;
import jetbrains.buildServer.serverSide.*;
import jetbrains.buildServer.util.EventDispatcher;
import jetbrains.buildServer.util.FileUtil;
import jetbrains.buildServer.vcs.SVcsRoot;
import jetbrains.buildServer.vcs.VcsException;
import jetbrains.buildServer.vcs.VcsRoot;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Cleans unused git repositories
* @author dmitry.neverov
*/
public class Cleaner extends BuildServerAdapter {
private static Logger LOG = Loggers.CLEANUP;
private final SBuildServer myServer;
private final ServerPaths myPaths;
private final GitVcsSupport myGitVcsSupport;
public Cleaner(@NotNull final SBuildServer server,
@NotNull final EventDispatcher<BuildServerListener> dispatcher,
@NotNull final ServerPaths paths,
@NotNull final GitVcsSupport gitSupport) {
myServer = server;
myPaths = paths;
myGitVcsSupport = gitSupport;
dispatcher.addListener(this);
}
@Override
public void cleanupStarted() {
super.cleanupFinished();
myServer.getExecutor().submit(new Runnable() {
public void run() {
clean();
}
});
}
private void clean() {
LOG.debug("Clean started");
removeUnusedRepositories();
if (isRunNativeGC()) {
runNativeGC();
}
LOG.debug("Clean finished");
}
private void removeUnusedRepositories() {
Collection<? extends SVcsRoot> gitRoots = getAllGitRoots();
List<File> unusedDirs = getUnusedDirs(gitRoots);
LOG.debug("Remove unused repositories started");
for (File dir : unusedDirs) {
LOG.info("Remove unused dir " + dir.getAbsolutePath());
synchronized (myGitVcsSupport.getRepositoryLock(dir)) {
FileUtil.delete(dir);
}
LOG.debug("Remove unused dir " + dir.getAbsolutePath() + " finished");
}
LOG.debug("Remove unused repositories finished");
}
private Collection<? extends SVcsRoot> getAllGitRoots() {
return myServer.getVcsManager().findRootsByVcsName(Constants.VCS_NAME);
}
private List<File> getUnusedDirs(Collection<? extends SVcsRoot> roots) {
List<File> repositoryDirs = getAllRepositoryDirs();
File cacheDir = new File(myPaths.getCachesDir());
for (VcsRoot root : roots) {
try {
File usedRootDir = Settings.getRepositoryPath(cacheDir, root);
repositoryDirs.remove(usedRootDir);
} catch (Exception e) {
LOG.warn("Get repository path error", e);
}
}
return repositoryDirs;
}
private List<File> getAllRepositoryDirs() {
String teamcityCachesPath = myPaths.getCachesDir();
File gitCacheDir = new File(teamcityCachesPath, "git");
return new ArrayList<File>(FileUtil.getSubDirectories(gitCacheDir));
}
private boolean isRunNativeGC() {
return TeamCityProperties.getBoolean("teamcity.server.git.gc.enabled");
}
private String getPathToGit() {
return TeamCityProperties.getProperty("teamcity.server.git.executable.path", "git");
}
private long getNativeGCQuotaMilliseconds() {
int quotaInMinutes = TeamCityProperties.getInteger("teamcity.server.git.gc.quota.minutes", 60);
return minutes2Milliseconds(quotaInMinutes);
}
private long minutes2Milliseconds(int quotaInMinutes) {
return quotaInMinutes * 60 * 1000L;
}
private void runNativeGC() {
final long start = System.currentTimeMillis();
final long gcTimeQuota = getNativeGCQuotaMilliseconds();
LOG.info("Garbage collection started");
List<File> allDirs = getAllRepositoryDirs();
int runGCCounter = 0;
for (File gitDir : allDirs) {
synchronized (myGitVcsSupport.getRepositoryLock(gitDir)) {
runNativeGC(gitDir);
}
runGCCounter++;
final long repositoryFinish = System.currentTimeMillis();
if ((repositoryFinish - start) > gcTimeQuota) {
final int restRepositories = allDirs.size() - runGCCounter;
if (restRepositories > 0) {
LOG.info("Garbage collection quota exceeded, skip " + restRepositories + " repositories");
break;
}
}
}
final long finish = System.currentTimeMillis();
LOG.info("Garbage collection finished, it took " + (finish - start) + "ms");
}
private void runNativeGC(final File bareGitDir) {
String pathToGit = getPathToGit();
try {
final long start = System.currentTimeMillis();
GeneralCommandLine cl = new GeneralCommandLine();
cl.setWorkingDirectory(bareGitDir.getParentFile());
cl.setExePath(pathToGit);
cl.addParameter("--git-dir="+bareGitDir.getCanonicalPath());
cl.addParameter("gc");
cl.addParameter("--auto");
cl.addParameter("--quiet");
ExecResult result = SimpleCommandLineProcessRunner.runCommand(cl, null, new SimpleCommandLineProcessRunner.RunCommandEvents() {
public void onProcessStarted(Process ps) {
if (LOG.isDebugEnabled()) {
LOG.info("Start 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'");
}
}
public void onProcessFinished(Process ps) {
if (LOG.isDebugEnabled()) {
final long finish = System.currentTimeMillis();
LOG.info("Finish 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc', it took " + (finish - start) + "ms");
}
}
public Integer getOutputIdleSecondsTimeout() {
return 3 * 60 * 60;//3 hours
}
});
VcsException commandError = CommandLineUtil.getCommandLineError("'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", result);
if (commandError != null) {
LOG.error("Error while running 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", commandError);
}
if (result.getStderr().length() > 0) {
- LOG.warn("Error output produced by 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'");
- LOG.warn(result.getStderr());
+ LOG.debug("Output produced by 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'");
+ LOG.debug(result.getStderr());
}
} catch (Exception e) {
LOG.error("Error while running 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", e);
}
}
}
| true | true | private void runNativeGC(final File bareGitDir) {
String pathToGit = getPathToGit();
try {
final long start = System.currentTimeMillis();
GeneralCommandLine cl = new GeneralCommandLine();
cl.setWorkingDirectory(bareGitDir.getParentFile());
cl.setExePath(pathToGit);
cl.addParameter("--git-dir="+bareGitDir.getCanonicalPath());
cl.addParameter("gc");
cl.addParameter("--auto");
cl.addParameter("--quiet");
ExecResult result = SimpleCommandLineProcessRunner.runCommand(cl, null, new SimpleCommandLineProcessRunner.RunCommandEvents() {
public void onProcessStarted(Process ps) {
if (LOG.isDebugEnabled()) {
LOG.info("Start 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'");
}
}
public void onProcessFinished(Process ps) {
if (LOG.isDebugEnabled()) {
final long finish = System.currentTimeMillis();
LOG.info("Finish 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc', it took " + (finish - start) + "ms");
}
}
public Integer getOutputIdleSecondsTimeout() {
return 3 * 60 * 60;//3 hours
}
});
VcsException commandError = CommandLineUtil.getCommandLineError("'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", result);
if (commandError != null) {
LOG.error("Error while running 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", commandError);
}
if (result.getStderr().length() > 0) {
LOG.warn("Error output produced by 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'");
LOG.warn(result.getStderr());
}
} catch (Exception e) {
LOG.error("Error while running 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", e);
}
}
| private void runNativeGC(final File bareGitDir) {
String pathToGit = getPathToGit();
try {
final long start = System.currentTimeMillis();
GeneralCommandLine cl = new GeneralCommandLine();
cl.setWorkingDirectory(bareGitDir.getParentFile());
cl.setExePath(pathToGit);
cl.addParameter("--git-dir="+bareGitDir.getCanonicalPath());
cl.addParameter("gc");
cl.addParameter("--auto");
cl.addParameter("--quiet");
ExecResult result = SimpleCommandLineProcessRunner.runCommand(cl, null, new SimpleCommandLineProcessRunner.RunCommandEvents() {
public void onProcessStarted(Process ps) {
if (LOG.isDebugEnabled()) {
LOG.info("Start 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'");
}
}
public void onProcessFinished(Process ps) {
if (LOG.isDebugEnabled()) {
final long finish = System.currentTimeMillis();
LOG.info("Finish 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc', it took " + (finish - start) + "ms");
}
}
public Integer getOutputIdleSecondsTimeout() {
return 3 * 60 * 60;//3 hours
}
});
VcsException commandError = CommandLineUtil.getCommandLineError("'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", result);
if (commandError != null) {
LOG.error("Error while running 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", commandError);
}
if (result.getStderr().length() > 0) {
LOG.debug("Output produced by 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'");
LOG.debug(result.getStderr());
}
} catch (Exception e) {
LOG.error("Error while running 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", e);
}
}
|
diff --git a/test/com/github/manasg/logging/test/MultipleLogMsg.java b/test/com/github/manasg/logging/test/MultipleLogMsg.java
index c10c1a6..942f88c 100644
--- a/test/com/github/manasg/logging/test/MultipleLogMsg.java
+++ b/test/com/github/manasg/logging/test/MultipleLogMsg.java
@@ -1,39 +1,39 @@
package com.github.manasg.logging.test;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class MultipleLogMsg {
public static long multipleLogs(int number) {
Logger logger = Logger.getLogger("multi");
PropertyConfigurator.configure("conf/log4j.properties");
/*
* Just doing this via Code. Log4.properties has the same effect!
- EasilydoAppender a4 = new EasilydoAppender();
+ RemoteAppender a4 = new RemoteAppender();
a4.setEnvironment("load-test");
a4.setDestination("192.168.100.8:2464");
logger.addAppender(a4);
logger.setAdditivity(false);
*/
long start = System.currentTimeMillis();
for(int i=0;i<number;i++) {
logger.fatal("Oh boy!");
}
long end = System.currentTimeMillis();
return end-start;
}
public static void main(String[] args) {
int n = 30;
long time = multipleLogs(n);
System.out.println("It took "+ time/1000.0 +" seconds - for "+n+" messages");
}
}
| true | true | public static long multipleLogs(int number) {
Logger logger = Logger.getLogger("multi");
PropertyConfigurator.configure("conf/log4j.properties");
/*
* Just doing this via Code. Log4.properties has the same effect!
EasilydoAppender a4 = new EasilydoAppender();
a4.setEnvironment("load-test");
a4.setDestination("192.168.100.8:2464");
logger.addAppender(a4);
logger.setAdditivity(false);
*/
long start = System.currentTimeMillis();
for(int i=0;i<number;i++) {
logger.fatal("Oh boy!");
}
long end = System.currentTimeMillis();
return end-start;
}
| public static long multipleLogs(int number) {
Logger logger = Logger.getLogger("multi");
PropertyConfigurator.configure("conf/log4j.properties");
/*
* Just doing this via Code. Log4.properties has the same effect!
RemoteAppender a4 = new RemoteAppender();
a4.setEnvironment("load-test");
a4.setDestination("192.168.100.8:2464");
logger.addAppender(a4);
logger.setAdditivity(false);
*/
long start = System.currentTimeMillis();
for(int i=0;i<number;i++) {
logger.fatal("Oh boy!");
}
long end = System.currentTimeMillis();
return end-start;
}
|
diff --git a/monopoly/src/ch/bfh/monopoly/gui/BoardTile.java b/monopoly/src/ch/bfh/monopoly/gui/BoardTile.java
index 35b5a1f..7d19c68 100644
--- a/monopoly/src/ch/bfh/monopoly/gui/BoardTile.java
+++ b/monopoly/src/ch/bfh/monopoly/gui/BoardTile.java
@@ -1,571 +1,571 @@
package ch.bfh.monopoly.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ResourceBundle;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import ch.bfh.monopoly.common.BoardController;
import ch.bfh.monopoly.common.GameController;
import ch.bfh.monopoly.common.Token;
import ch.bfh.monopoly.observer.PlayerListener;
import ch.bfh.monopoly.observer.PlayerStateEvent;
import ch.bfh.monopoly.observer.TileListener;
import ch.bfh.monopoly.observer.TileStateEvent;
import ch.bfh.monopoly.tile.TileInfo;
/**
* This class represent a tile on the board
* @author snake
*
*/
public class BoardTile extends JPanel{
private static final long serialVersionUID = 3335141445010622095L;
private int numberOfTokens = 0;
private int houseCount = 0;
private boolean isHotel = false;
private Set<Token> tokens = new HashSet<Token>();
private TileInfo ti;
private JPanel tab;
private boolean displayInfo = false;
private BoardController bc;
private GameController gc;
private ResourceBundle res;
private JLabel owner;
private ButtonListener btnListener;
//used when we right click on a tile
private PerformActionMenu ac;
//used to update the tile
private InformationUpdate iu = new InformationUpdate();
private JMenuItem buyHouse, buyHouseRow, buyHotel, buyHotelRow, sellHouse, sellHotel, sellHouseRow,
sellHotelRow, mortgage, unmortgage;
private JPanel color;
/**
* Construct a new BoardTile
* @param ti the TileInfo used to passed the information
*/
public BoardTile(TileInfo ti, JPanel tab, BoardController bc, GameController gc, ResourceBundle res){
this.ti = ti;
this.tab = tab;
this.bc = bc;
this.gc = gc;
this.res = res;
setBorder(BorderFactory.createEtchedBorder());
setLayout(new GridLayout(3,1));
color = new JPanel();
color.setLayout(new BoxLayout(color, BoxLayout.LINE_AXIS));
btnListener = new ButtonListener();
ac = new PerformActionMenu();
if(ti.getGroup() != null &&
(!ti.getGroup().equals("cornersAndTax") || !ti.getGroup().equals("Community Chest")
|| !ti.getGroup().equals("Chance"))){
//we want a pop-up menu only on the properties where
//we can build something and we are the owner
//TODO remove if for test
this.addMouseListener(btnListener);
bc.getSubjectForPlayer().addListener(new OwnerUpdater());
displayInfo = true;
}
//check if there is a color and add the menu
if(ti.getRGB() != null){
color.setBackground(Color.decode(ti.getRGB()));
btnListener.addPopUp(popMenu());
}
add(color);
Font f = new Font(getFont().getName(), Font.PLAIN, getFont().getSize()-1);
JLabel name = new JLabel(ti.getName());
name.setFont(f);
setMaximumSize(new Dimension(75, 75));
add(name);
}
/**
* Get the X coordinate of this tile
* @return an int that correspond to the X coordinate
*/
public int getTileInfoX(){
return ti.getCoordX();
}
/**
* Get the Y coordinate of this tile
* @return an int that correspond to the Y coordinate
*/
public int getTileInfoY(){
return ti.getCoordY();
}
/**
* Remove a token from this tile
* @param index the index of the token to be removed
*/
public void removeToken(Token t){
this.tokens.remove(t);
}
/**
* Add a token to this tile
* @param t the token to be added
*/
public void addToken(Token t){
this.tokens.add(t);
}
/**
* Add the information of a tile (rent, name,costs, etc.) to
* the tabbed pane
*/
private void addInformationOnTab(){
if(displayInfo){
//clean the panel
tab.removeAll();
Font f = new Font(getFont().getName(), Font.PLAIN, getFont().getSize());
Font f2 = new Font(getFont().getName(), Font.BOLD, getFont().getSize());
JLabel name = new JLabel(ti.getName());
name.setAlignmentX(Component.CENTER_ALIGNMENT);
name.setFont(f2);
JPanel color = new JPanel();
color.setBorder(BorderFactory.createEtchedBorder());
color.setMaximumSize(new Dimension(tab.getWidth(), getHeight()/3));
if(ti.getRGB() != null)
color.setBackground(Color.decode(ti.getRGB()));
else
color.setBackground(Color.WHITE);
color.add(name);
JLabel price = new JLabel(res.getString("label-price") + Integer.toString(ti.getPrice()));
price.setAlignmentX(Component.CENTER_ALIGNMENT);
price.setFont(f);
tab.add(color);
tab.add(price);
if(ti.getRent() != -1){
JLabel rent = new JLabel(res.getString("label-rent") + Integer.toString(ti.getRent()));
rent.setAlignmentX(Component.CENTER_ALIGNMENT);
rent.setFont(f);
tab.add(rent);
JLabel rent1 = new JLabel(res.getString("label-onehouse") + Integer.toString(ti.getRent1house()));
rent1.setAlignmentX(Component.CENTER_ALIGNMENT);
rent1.setFont(f);
JLabel rent2 = new JLabel(res.getString("label-twohouses") + Integer.toString(ti.getRent2house()));
rent2.setAlignmentX(Component.CENTER_ALIGNMENT);
rent2.setFont(f);
JLabel rent3 = new JLabel(res.getString("label-threehouses") + Integer.toString(ti.getRent3house()));
rent3.setAlignmentX(Component.CENTER_ALIGNMENT);
rent3.setFont(f);
JLabel rent4 = new JLabel(res.getString("label-fourhouses") + Integer.toString(ti.getRent4house()));
rent4.setAlignmentX(Component.CENTER_ALIGNMENT);
rent4.setFont(f);
JLabel hotel = new JLabel(res.getString("label-hotel") + Integer.toString(ti.getRenthotel()));
hotel.setAlignmentX(Component.CENTER_ALIGNMENT);
hotel.setFont(f);
JLabel houseCost = new JLabel(res.getString("label-houseprice") + Integer.toString(ti.getHouseCost()));
houseCost.setAlignmentX(Component.CENTER_ALIGNMENT);
houseCost.setFont(f);
JLabel hotelCost = new JLabel(res.getString("label-hotelprice") + Integer.toString(ti.getHotelCost()));
hotelCost.setAlignmentX(Component.CENTER_ALIGNMENT);
hotelCost.setFont(f);
- owner = new JLabel(res.getString("label-owner") + ti.getOwner());
+ owner = new JLabel(res.getString("label-owner") + bc.getTileInfoById(ti.getTileId()).getOwner());
owner.setAlignmentX(Component.CENTER_ALIGNMENT);
owner.setFont(f);
tab.add(rent1);
tab.add(rent2);
tab.add(rent3);
tab.add(rent4);
tab.add(hotel);
tab.add(houseCost);
tab.add(hotelCost);
tab.add(owner);
}
JLabel mortgage = new JLabel(res.getString("label-mortgagevalue") + Integer.toString(ti.getMortgageValue()));
mortgage.setAlignmentX(Component.CENTER_ALIGNMENT);
mortgage.setFont(f);
tab.add(mortgage);
tab.revalidate();
tab.repaint();
}
}
/**
* Creates a popup menu for this tile
* @return a JPopupMenu with the actions possible for this tile
*/
private JPopupMenu popMenu(){
JPopupMenu pop = new JPopupMenu();
buyHouse = new JMenuItem(res.getString("label-buyhouse"));
buyHouse.addActionListener(ac);
buyHouseRow = new JMenuItem(res.getString("label-buyhouserow"));
buyHouseRow.addActionListener(ac);
buyHotel = new JMenuItem(res.getString("label-buyhotel"));
buyHotel.addActionListener(ac);
buyHotelRow = new JMenuItem(res.getString("label-buyhotelrow"));
buyHotelRow.addActionListener(ac);
sellHouse = new JMenuItem(res.getString("label-sellhouse"));
sellHouse.addActionListener(ac);
sellHotel = new JMenuItem(res.getString("label-sellhotel"));
sellHotel.addActionListener(ac);
sellHouseRow = new JMenuItem(res.getString("label-sellhouserow"));
sellHouseRow.addActionListener(ac);
sellHotelRow = new JMenuItem(res.getString("label-sellhotelrow"));
sellHotelRow.addActionListener(ac);
mortgage = new JMenuItem(res.getString("label-mortgage"));
mortgage.addActionListener(ac);
unmortgage = new JMenuItem(res.getString("label-unmortgage"));
unmortgage.addActionListener(ac);
pop.add(buyHouse);
pop.add(buyHouseRow);
pop.add(buyHotel);
pop.add(buyHotelRow);
pop.addSeparator();
pop.add(sellHouse);
pop.add(sellHouseRow);
pop.add(sellHotel);
pop.add(sellHotelRow);
pop.addSeparator();
pop.add(mortgage);
pop.add(unmortgage);
return pop;
}
/**
* Show tile's information in card's box
*/
public void showCard(){
addInformationOnTab();
}
/**
* Draw the tokens on this tile
*/
@Override
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
this.numberOfTokens = tokens.size();
if(this.numberOfTokens >= 1 && this.numberOfTokens <= 8){
for(int i = 0 ; i < this.numberOfTokens ; i++){
Iterator<Token> itr = this.tokens.iterator();
while(itr.hasNext()){
Token t = itr.next();
g2.setColor(t.getColor());
g2.fillOval((int)(getWidth()*t.getXRatio()), (int)(getHeight()*t.getYRatio()), (int)(getHeight()*0.25), (int)(getHeight()*0.25));
}
}
}
}
/**
* Draw an house
* @return JPanel
* a JPanel representing an house
*/
private JPanel drawHouse(){
JPanel building = new JPanel();
building.setBorder(BorderFactory.createRaisedBevelBorder());
building.setBackground(Color.RED);
building.setMaximumSize(new Dimension((int)getWidth()/6, getHeight()));
return building;
}
/**
* Draw an hotel
* @return JPanel
* a JPanel representing an hotel
*/
private JPanel drawHotel(){
JPanel building = new JPanel();
building.setBorder(BorderFactory.createRaisedBevelBorder());
building.setBackground(Color.GREEN);
building.setMaximumSize(new Dimension((int)getWidth()/3, getHeight()));
return building;
}
/**
* Draw a building
* @param type boolean true == hotel ; false == house
*/
public void drawBuilding(boolean type){
//if true is hotel
if(type && !isHotel && houseCount == 4){
color.removeAll();
//we have drawn an hotel
isHotel = true;
color.add(drawHotel());
}
else if(!type && houseCount < 4){
houseCount++;
color.add(drawHouse());
}
revalidate();
repaint();
}
/**
* Remove a building from this tile
* @param type boolean
* a boolean representing the type of building
* true == hotel, false = house
*/
public void removeBuilding(boolean type){
//remove house
if(!type && houseCount > 0 && houseCount <= 4){
color.remove(0);
houseCount--;
System.out.println("REMOVED HOUSE INSIDE REMOVE BUILDING");
}
//remove hotel
else if(type && isHotel && houseCount == 4){
color.remove(0);
color.add(drawHouse());
color.add(drawHouse());
color.add(drawHouse());
color.add(drawHouse());
isHotel = false;
}
revalidate();
repaint();
}
/**
* Change the color of the background to show that is mortgaged
*/
private void mortgagePanel(){
System.out.println("INSIDE MORTGAGA PENAL");
color.setBackground(Color.BLACK);
repaint();
revalidate();
}
/**
* Unmortgage the terrain by change the color to
* the initial one
*/
private void unmortgagePanel(){
color.setBackground(Color.decode(ti.getRGB()));
revalidate();
repaint();
}
/**
* Inner class used to show the popup menu
* @author snake, shrevek
*/
private class ButtonListener extends MouseAdapter{
JPopupMenu popup;
boolean owner = false;
public void addPopUp(JPopupMenu pop){
this.popup = pop;
}
public void mousePressed(MouseEvent e) {
//left click
System.out.println(e.getButton() + " CONTROL DOWN: " + e.isControlDown());
if(e.getButton() == MouseEvent.BUTTON1 && !e.isControlDown()){
addInformationOnTab();
}
//right click, isControlDown is for a macintosh personal computer
else if(e.getButton() == MouseEvent.BUTTON3 || (e.isControlDown() && e.getButton() == 1)){
if(owner){
showPopup(e);
}
}
}
public void setOwner(){
owner = true;
}
private void showPopup(MouseEvent e) {
if (e.isPopupTrigger() && popup != null) {
popup.show(e.getComponent(),
e.getX(), e.getY());
}
}
}
/**
* Inner class used to manage the mouse click on the menu
* @author snake, shrevek
*
*/
private class PerformActionMenu implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(buyHouse)){
gc.buyHouse(ti.getTileId());
}
else if(e.getSource().equals(buyHotel)){
gc.buyHotel(ti.getTileId());
}
else if(e.getSource().equals(buyHouseRow)){
gc.buyHouseRow(ti.getTileId());
}
else if(e.getSource().equals(buyHotelRow)){
gc.buyHotelRow(ti.getTileId());
}
else if(e.getSource().equals(sellHouse)){
gc.sellHouse(ti.getTileId());
}
else if(e.getSource().equals(sellHotel)){
gc.sellHotel(ti.getTileId());
}
else if(e.getSource().equals(sellHouseRow)){
gc.sellHouseRow(ti.getTileId());
}
else if(e.getSource().equals(sellHotelRow)){
gc.sellHotelRow(ti.getTileId());
}
else if(e.getSource().equals(mortgage)){
System.out.println("INSIDE MORTGAGE");
gc.toggleMortgageStatus(ti.getTileId());
}
else if(e.getSource().equals(unmortgage)){
gc.toggleMortgageStatus(ti.getTileId());
}
}
}
/**
* Inner class used to update the information on this tile
* @author snake, shrevek
*/
private class InformationUpdate implements TileListener{
@Override
public void updateTile(TileStateEvent tsi) {
System.out.println("HOUSES : " + tsi.getHouseCount());
System.out.println("HOTELS : " + tsi.getHotelsCount());
if(tsi.getHouseCount() > houseCount){
drawBuilding(false);
}
else if(tsi.getHouseCount() < houseCount){
removeBuilding(false);
}
else if(tsi.getHotelsCount() == 1){
drawBuilding(true);
}
else if(tsi.getHotelsCount() == 0){
removeBuilding(true);
}
else if(tsi.isMortgageActive()){
mortgagePanel();
}
else if(!tsi.isMortgageActive()){
unmortgagePanel();
}
}
}
class OwnerUpdater implements PlayerListener{
@Override
public void updatePlayer(ArrayList<PlayerStateEvent> playerStates) {
if(ti.getTileId() != -1 &&
bc.getTileInfoById(ti.getTileId()).getOwner() != null && bc.getTileInfoById(ti.getTileId()).getOwner().equals(gc.getLocalPlayerName())){
btnListener.setOwner();
owner.setText(res.getString("label-owner") + bc.getTileInfoById(ti.getTileId()).getOwner());
}
}
}
/**
* This method is called by an external
* class to update the information on this tile
* @param tsi
*/
public void updateTile(TileStateEvent tse){
iu.updateTile(tse);
}
public TileListener getTileListener(){
return this.iu;
}
}
| true | true | private void addInformationOnTab(){
if(displayInfo){
//clean the panel
tab.removeAll();
Font f = new Font(getFont().getName(), Font.PLAIN, getFont().getSize());
Font f2 = new Font(getFont().getName(), Font.BOLD, getFont().getSize());
JLabel name = new JLabel(ti.getName());
name.setAlignmentX(Component.CENTER_ALIGNMENT);
name.setFont(f2);
JPanel color = new JPanel();
color.setBorder(BorderFactory.createEtchedBorder());
color.setMaximumSize(new Dimension(tab.getWidth(), getHeight()/3));
if(ti.getRGB() != null)
color.setBackground(Color.decode(ti.getRGB()));
else
color.setBackground(Color.WHITE);
color.add(name);
JLabel price = new JLabel(res.getString("label-price") + Integer.toString(ti.getPrice()));
price.setAlignmentX(Component.CENTER_ALIGNMENT);
price.setFont(f);
tab.add(color);
tab.add(price);
if(ti.getRent() != -1){
JLabel rent = new JLabel(res.getString("label-rent") + Integer.toString(ti.getRent()));
rent.setAlignmentX(Component.CENTER_ALIGNMENT);
rent.setFont(f);
tab.add(rent);
JLabel rent1 = new JLabel(res.getString("label-onehouse") + Integer.toString(ti.getRent1house()));
rent1.setAlignmentX(Component.CENTER_ALIGNMENT);
rent1.setFont(f);
JLabel rent2 = new JLabel(res.getString("label-twohouses") + Integer.toString(ti.getRent2house()));
rent2.setAlignmentX(Component.CENTER_ALIGNMENT);
rent2.setFont(f);
JLabel rent3 = new JLabel(res.getString("label-threehouses") + Integer.toString(ti.getRent3house()));
rent3.setAlignmentX(Component.CENTER_ALIGNMENT);
rent3.setFont(f);
JLabel rent4 = new JLabel(res.getString("label-fourhouses") + Integer.toString(ti.getRent4house()));
rent4.setAlignmentX(Component.CENTER_ALIGNMENT);
rent4.setFont(f);
JLabel hotel = new JLabel(res.getString("label-hotel") + Integer.toString(ti.getRenthotel()));
hotel.setAlignmentX(Component.CENTER_ALIGNMENT);
hotel.setFont(f);
JLabel houseCost = new JLabel(res.getString("label-houseprice") + Integer.toString(ti.getHouseCost()));
houseCost.setAlignmentX(Component.CENTER_ALIGNMENT);
houseCost.setFont(f);
JLabel hotelCost = new JLabel(res.getString("label-hotelprice") + Integer.toString(ti.getHotelCost()));
hotelCost.setAlignmentX(Component.CENTER_ALIGNMENT);
hotelCost.setFont(f);
owner = new JLabel(res.getString("label-owner") + ti.getOwner());
owner.setAlignmentX(Component.CENTER_ALIGNMENT);
owner.setFont(f);
tab.add(rent1);
tab.add(rent2);
tab.add(rent3);
tab.add(rent4);
tab.add(hotel);
tab.add(houseCost);
tab.add(hotelCost);
tab.add(owner);
}
JLabel mortgage = new JLabel(res.getString("label-mortgagevalue") + Integer.toString(ti.getMortgageValue()));
mortgage.setAlignmentX(Component.CENTER_ALIGNMENT);
mortgage.setFont(f);
tab.add(mortgage);
tab.revalidate();
tab.repaint();
}
}
| private void addInformationOnTab(){
if(displayInfo){
//clean the panel
tab.removeAll();
Font f = new Font(getFont().getName(), Font.PLAIN, getFont().getSize());
Font f2 = new Font(getFont().getName(), Font.BOLD, getFont().getSize());
JLabel name = new JLabel(ti.getName());
name.setAlignmentX(Component.CENTER_ALIGNMENT);
name.setFont(f2);
JPanel color = new JPanel();
color.setBorder(BorderFactory.createEtchedBorder());
color.setMaximumSize(new Dimension(tab.getWidth(), getHeight()/3));
if(ti.getRGB() != null)
color.setBackground(Color.decode(ti.getRGB()));
else
color.setBackground(Color.WHITE);
color.add(name);
JLabel price = new JLabel(res.getString("label-price") + Integer.toString(ti.getPrice()));
price.setAlignmentX(Component.CENTER_ALIGNMENT);
price.setFont(f);
tab.add(color);
tab.add(price);
if(ti.getRent() != -1){
JLabel rent = new JLabel(res.getString("label-rent") + Integer.toString(ti.getRent()));
rent.setAlignmentX(Component.CENTER_ALIGNMENT);
rent.setFont(f);
tab.add(rent);
JLabel rent1 = new JLabel(res.getString("label-onehouse") + Integer.toString(ti.getRent1house()));
rent1.setAlignmentX(Component.CENTER_ALIGNMENT);
rent1.setFont(f);
JLabel rent2 = new JLabel(res.getString("label-twohouses") + Integer.toString(ti.getRent2house()));
rent2.setAlignmentX(Component.CENTER_ALIGNMENT);
rent2.setFont(f);
JLabel rent3 = new JLabel(res.getString("label-threehouses") + Integer.toString(ti.getRent3house()));
rent3.setAlignmentX(Component.CENTER_ALIGNMENT);
rent3.setFont(f);
JLabel rent4 = new JLabel(res.getString("label-fourhouses") + Integer.toString(ti.getRent4house()));
rent4.setAlignmentX(Component.CENTER_ALIGNMENT);
rent4.setFont(f);
JLabel hotel = new JLabel(res.getString("label-hotel") + Integer.toString(ti.getRenthotel()));
hotel.setAlignmentX(Component.CENTER_ALIGNMENT);
hotel.setFont(f);
JLabel houseCost = new JLabel(res.getString("label-houseprice") + Integer.toString(ti.getHouseCost()));
houseCost.setAlignmentX(Component.CENTER_ALIGNMENT);
houseCost.setFont(f);
JLabel hotelCost = new JLabel(res.getString("label-hotelprice") + Integer.toString(ti.getHotelCost()));
hotelCost.setAlignmentX(Component.CENTER_ALIGNMENT);
hotelCost.setFont(f);
owner = new JLabel(res.getString("label-owner") + bc.getTileInfoById(ti.getTileId()).getOwner());
owner.setAlignmentX(Component.CENTER_ALIGNMENT);
owner.setFont(f);
tab.add(rent1);
tab.add(rent2);
tab.add(rent3);
tab.add(rent4);
tab.add(hotel);
tab.add(houseCost);
tab.add(hotelCost);
tab.add(owner);
}
JLabel mortgage = new JLabel(res.getString("label-mortgagevalue") + Integer.toString(ti.getMortgageValue()));
mortgage.setAlignmentX(Component.CENTER_ALIGNMENT);
mortgage.setFont(f);
tab.add(mortgage);
tab.revalidate();
tab.repaint();
}
}
|
diff --git a/webofneeds/won-owner-webapp/src/main/java/won/owner/web/need/NeedController.java b/webofneeds/won-owner-webapp/src/main/java/won/owner/web/need/NeedController.java
index 24b509248..ff2581b8a 100644
--- a/webofneeds/won-owner-webapp/src/main/java/won/owner/web/need/NeedController.java
+++ b/webofneeds/won-owner-webapp/src/main/java/won/owner/web/need/NeedController.java
@@ -1,345 +1,345 @@
package won.owner.web.need;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import won.owner.pojo.NeedPojo;
import won.owner.protocol.impl.OwnerProtocolNeedServiceClient;
import won.owner.service.impl.DataReloadService;
import won.owner.service.impl.URIService;
import won.protocol.exception.ConnectionAlreadyExistsException;
import won.protocol.exception.IllegalMessageForNeedStateException;
import won.protocol.exception.IllegalNeedContentException;
import won.protocol.exception.NoSuchNeedException;
import won.protocol.model.Match;
import won.protocol.model.Need;
import won.protocol.model.NeedState;
import won.protocol.owner.OwnerProtocolNeedService;
import won.protocol.repository.ConnectionRepository;
import won.protocol.repository.MatchRepository;
import won.protocol.repository.NeedRepository;
import won.protocol.rest.LinkedDataRestClient;
import won.protocol.util.DateTimeUtils;
import won.protocol.vocabulary.GEO;
import won.protocol.vocabulary.GR;
import won.protocol.vocabulary.WON;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: Gabriel
* Date: 17.12.12
* Time: 13:38
*/
@Controller
public class NeedController
{
final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private OwnerProtocolNeedService ownerService;
@Autowired
private NeedRepository needRepository;
@Autowired
private MatchRepository matchRepository;
@Autowired
private ConnectionRepository connectionRepository;
@Autowired
private URIService uriService;
@Autowired
private DataReloadService dataReloadService;
public void setDataReloadService(DataReloadService dataReloadService)
{
this.dataReloadService = dataReloadService;
}
public URIService getUriService()
{
return uriService;
}
public void setUriService(final URIService uriService)
{
this.uriService = uriService;
}
public void setOwnerService(OwnerProtocolNeedService ownerService)
{
this.ownerService = ownerService;
}
public void setConnectionRepository(ConnectionRepository connectionRepository)
{
this.connectionRepository = connectionRepository;
}
public void setMatchRepository(MatchRepository matchRepository)
{
this.matchRepository = matchRepository;
}
public void setNeedRepository(NeedRepository needRepository)
{
this.needRepository = needRepository;
}
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String createNeedGet(Model model)
{
model.addAttribute("command", new NeedPojo());
return "createNeed";
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String createNeedPost(@ModelAttribute("SpringWeb") NeedPojo needPojo, Model model)
{
URI needURI;
try {
URI ownerURI = this.uriService.getOwnerProtocolOwnerServiceEndpointURI();
com.hp.hpl.jena.rdf.model.Model needModel = ModelFactory.createDefaultModel();
Resource needResource = needModel.createResource(WON.NEED);
//TODO: add this after it is saved to the DB for the first time
// .addProperty(WON.NEED_CREATION_DATE, DateTimeUtils.getCurrentDateTimeStamp(), XSDDatatype.XSDdateTime);
// need type
needModel.add(needModel.createStatement(needResource, WON.HAS_BASIC_NEED_TYPE, WON.toResource(needPojo.getBasicNeedType())));
// need content
Resource needContent = needModel.createResource(WON.NEED_CONTENT);
if (!needPojo.getTitle().isEmpty())
needContent.addProperty(WON.TITLE, needPojo.getTitle(), XSDDatatype.XSDstring);
if (!needPojo.getTextDescription().isEmpty())
needContent.addProperty(WON.TEXT_DESCRIPTION, needPojo.getTextDescription(), XSDDatatype.XSDstring);
needModel.add(needModel.createStatement(needResource, WON.HAS_CONTENT, needContent));
// owner
if (needPojo.isAnonymize()) {
needModel.add(needModel.createStatement(needResource, WON.HAS_OWNER, WON.ANONYMIZED_OWNER));
}
// need modalities
Resource needModality = needModel.createResource(WON.NEED_MODALITY);
needModel.add(needModel.createStatement(needModality, WON.AVAILABLE_DELIVERY_METHOD, GR.toResource(needPojo.getDeliveryMethod())));
// TODO: store need modalities in separate objects to enable easier checking and multiple instances
//price and currency
if (needPojo.getUpperPriceLimit() != null || needPojo.getLowerPriceLimit() != null) {
Resource priceSpecification = needModel.createResource(WON.PRICE_SPECIFICATION);
if (needPojo.getLowerPriceLimit() != null)
priceSpecification.addProperty(WON.HAS_LOWER_PRICE_LIMIT, Double.toString(needPojo.getLowerPriceLimit()), XSDDatatype.XSDdouble);
if (needPojo.getUpperPriceLimit() != null)
priceSpecification.addProperty(WON.HAS_UPPER_PRICE_LIMIT, Double.toString(needPojo.getUpperPriceLimit()), XSDDatatype.XSDdouble);
if (!needPojo.getCurrency().isEmpty())
priceSpecification.addProperty(WON.HAS_CURRENCY, needPojo.getCurrency(), XSDDatatype.XSDstring);
needModel.add(needModel.createStatement(needModality, WON.HAS_PRICE_SPECIFICATION, priceSpecification));
}
if (needPojo.getLatitude() != null && needPojo.getLongitude() != null) {
Resource location = needModel.createResource(GEO.POINT)
.addProperty(GEO.LATITUDE, Double.toString(needPojo.getLatitude()))
.addProperty(GEO.LONGITUDE, Double.toString(needPojo.getLongitude()));
needModel.add(needModel.createStatement(needModality, WON.AVAILABLE_AT_LOCATION, location));
}
// time constraint
if (!needPojo.getStartTime().isEmpty() || !needPojo.getEndTime().isEmpty()) {
Resource timeConstraint = needModel.createResource(WON.TIME_CONSTRAINT)
.addProperty(WON.RECUR_INFINITE_TIMES, Boolean.toString(needPojo.getRecurInfiniteTimes()), XSDDatatype.XSDboolean);
if (!needPojo.getStartTime().isEmpty())
timeConstraint.addProperty(WON.START_TIME, needPojo.getStartTime(), XSDDatatype.XSDdateTime);
- if (!needPojo.getStartTime().isEmpty())
+ if (!needPojo.getEndTime().isEmpty())
timeConstraint.addProperty(WON.END_TIME, needPojo.getEndTime(), XSDDatatype.XSDdateTime);
if (needPojo.getRecurIn() != null)
timeConstraint.addProperty(WON.RECUR_IN, Long.toString(needPojo.getRecurIn()));
if (needPojo.getRecurTimes() != null)
timeConstraint.addProperty(WON.RECUR_TIMES, Integer.toString(needPojo.getRecurTimes()));
needModel.add(needModel.createStatement(needModality, WON.AVAILABLE_AT_TIME, timeConstraint));
}
needModel.add(needModel.createStatement(needResource, WON.HAS_NEED_MODALITY, needModality));
if (needPojo.getWonNode().equals("")) {
//TODO: this is a temporary hack, please fix. The protocol expects boolean and we have an enum for needState
needURI = ownerService.createNeed(ownerURI, needModel, needPojo.getState() == NeedState.ACTIVE);
} else {
needURI = ((OwnerProtocolNeedServiceClient) ownerService).createNeed(ownerURI, needModel, needPojo.getState() == NeedState.ACTIVE, needPojo.getWonNode());
}
List<Need> needs = needRepository.findByNeedURI(needURI);
if (needs.size() == 1)
return "redirect:/need/" + needs.get(0).getId().toString();
// return viewNeed(need.getId().toString(), model);
} catch (IllegalNeedContentException e) {
e.printStackTrace();
}
model.addAttribute("command", new NeedPojo());
return "createNeed";
}
@RequestMapping(value = "", method = RequestMethod.GET)
public String listNeeds(Model model)
{
model.addAttribute("needs", needRepository.findAll());
return "listNeeds";
}
@RequestMapping(value = "reload", method = RequestMethod.GET)
public String reload(Model model)
{
dataReloadService.reload();
return "redirect:/need/";
}
@RequestMapping(value = "/{needId}", method = RequestMethod.GET)
public String viewNeed(@PathVariable String needId, Model model)
{
model.addAttribute("needId", needId);
List<Need> needs = needRepository.findById(Long.valueOf(needId));
if (needs.isEmpty())
return "noNeedFound";
Need need = needs.get(0);
model.addAttribute("active", (need.getState() != NeedState.ACTIVE ? "activate" : "deactivate"));
model.addAttribute("needURI", need.getNeedURI());
model.addAttribute("command", new NeedPojo());
LinkedDataRestClient linkedDataRestClient = new LinkedDataRestClient();
NeedPojo pojo = new NeedPojo(need.getNeedURI(), linkedDataRestClient.readResourceData(need.getNeedURI()));
model.addAttribute("pojo", pojo);
return "viewNeed";
}
@RequestMapping(value = "/{needId}/listMatches", method = RequestMethod.GET)
public String listMatches(@PathVariable String needId, Model model)
{
List<Need> needs = needRepository.findById(Long.valueOf(needId));
if (needs.isEmpty())
return "noNeedFound";
Need need = needs.get(0);
model.addAttribute("matches", matchRepository.findByFromNeed(need.getNeedURI()));
return "listMatches";
}
@RequestMapping(value = "/{needId}/listConnections", method = RequestMethod.GET)
public String listConnections(@PathVariable String needId, Model model)
{
List<Need> needs = needRepository.findById(Long.valueOf(needId));
if (needs.isEmpty())
return "noNeedFound";
Need need = needs.get(0);
model.addAttribute("connections", connectionRepository.findByNeedURI(need.getNeedURI()));
return "listConnections";
}
@RequestMapping(value = "/{needId}/connect", method = RequestMethod.POST)
public String connect2Need(@PathVariable String needId, @ModelAttribute("SpringWeb") NeedPojo needPojo, Model model)
{
try {
List<Need> needs = needRepository.findById(Long.valueOf(needId));
if (needs.isEmpty())
return "noNeedFound";
Need need1 = needs.get(0);
ownerService.connectTo(need1.getNeedURI(), new URI(needPojo.getNeedURI()), "");
return "redirect:/need/" + need1.getId().toString();//viewNeed(need1.getId().toString(), model);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ConnectionAlreadyExistsException e) {
e.printStackTrace();
} catch (IllegalMessageForNeedStateException e) {
e.printStackTrace();
} catch (NoSuchNeedException e) {
e.printStackTrace();
}
return "noNeedFound";
}
@RequestMapping(value = "/{needId}/toggle", method = RequestMethod.POST)
public String toggleNeed(@PathVariable String needId, Model model)
{
List<Need> needs = needRepository.findById(Long.valueOf(needId));
if (needs.isEmpty())
return "noNeedFound";
Need need = needs.get(0);
try {
if (need.getState() == NeedState.ACTIVE) {
ownerService.deactivate(need.getNeedURI());
} else {
ownerService.activate(need.getNeedURI());
}
} catch (NoSuchNeedException e) {
e.printStackTrace();
}
return "redirect:/need/" + need.getId().toString();
//return viewNeed(need.getId().toString(), model);
}
@RequestMapping(value = "/match/{matchId}/connect", method = RequestMethod.POST)
public String connect(@PathVariable String matchId, Model model)
{
String ret = "noNeedFound";
try {
List<Match> matches = matchRepository.findById(Long.valueOf(matchId));
if (!matches.isEmpty()) {
Match match = matches.get(0);
List<Need> needs = needRepository.findByNeedURI(match.getFromNeed());
if (!needs.isEmpty())
ret = "redirect:/need/" + needs.get(0).getId().toString();//viewNeed(needs.get(0).getId().toString(), model);
ownerService.connectTo(match.getFromNeed(), match.getToNeed(), "");
}
} catch (ConnectionAlreadyExistsException e) {
e.printStackTrace();
} catch (IllegalMessageForNeedStateException e) {
e.printStackTrace();
} catch (NoSuchNeedException e) {
e.printStackTrace();
}
return ret;
}
}
| true | true | public String createNeedPost(@ModelAttribute("SpringWeb") NeedPojo needPojo, Model model)
{
URI needURI;
try {
URI ownerURI = this.uriService.getOwnerProtocolOwnerServiceEndpointURI();
com.hp.hpl.jena.rdf.model.Model needModel = ModelFactory.createDefaultModel();
Resource needResource = needModel.createResource(WON.NEED);
//TODO: add this after it is saved to the DB for the first time
// .addProperty(WON.NEED_CREATION_DATE, DateTimeUtils.getCurrentDateTimeStamp(), XSDDatatype.XSDdateTime);
// need type
needModel.add(needModel.createStatement(needResource, WON.HAS_BASIC_NEED_TYPE, WON.toResource(needPojo.getBasicNeedType())));
// need content
Resource needContent = needModel.createResource(WON.NEED_CONTENT);
if (!needPojo.getTitle().isEmpty())
needContent.addProperty(WON.TITLE, needPojo.getTitle(), XSDDatatype.XSDstring);
if (!needPojo.getTextDescription().isEmpty())
needContent.addProperty(WON.TEXT_DESCRIPTION, needPojo.getTextDescription(), XSDDatatype.XSDstring);
needModel.add(needModel.createStatement(needResource, WON.HAS_CONTENT, needContent));
// owner
if (needPojo.isAnonymize()) {
needModel.add(needModel.createStatement(needResource, WON.HAS_OWNER, WON.ANONYMIZED_OWNER));
}
// need modalities
Resource needModality = needModel.createResource(WON.NEED_MODALITY);
needModel.add(needModel.createStatement(needModality, WON.AVAILABLE_DELIVERY_METHOD, GR.toResource(needPojo.getDeliveryMethod())));
// TODO: store need modalities in separate objects to enable easier checking and multiple instances
//price and currency
if (needPojo.getUpperPriceLimit() != null || needPojo.getLowerPriceLimit() != null) {
Resource priceSpecification = needModel.createResource(WON.PRICE_SPECIFICATION);
if (needPojo.getLowerPriceLimit() != null)
priceSpecification.addProperty(WON.HAS_LOWER_PRICE_LIMIT, Double.toString(needPojo.getLowerPriceLimit()), XSDDatatype.XSDdouble);
if (needPojo.getUpperPriceLimit() != null)
priceSpecification.addProperty(WON.HAS_UPPER_PRICE_LIMIT, Double.toString(needPojo.getUpperPriceLimit()), XSDDatatype.XSDdouble);
if (!needPojo.getCurrency().isEmpty())
priceSpecification.addProperty(WON.HAS_CURRENCY, needPojo.getCurrency(), XSDDatatype.XSDstring);
needModel.add(needModel.createStatement(needModality, WON.HAS_PRICE_SPECIFICATION, priceSpecification));
}
if (needPojo.getLatitude() != null && needPojo.getLongitude() != null) {
Resource location = needModel.createResource(GEO.POINT)
.addProperty(GEO.LATITUDE, Double.toString(needPojo.getLatitude()))
.addProperty(GEO.LONGITUDE, Double.toString(needPojo.getLongitude()));
needModel.add(needModel.createStatement(needModality, WON.AVAILABLE_AT_LOCATION, location));
}
// time constraint
if (!needPojo.getStartTime().isEmpty() || !needPojo.getEndTime().isEmpty()) {
Resource timeConstraint = needModel.createResource(WON.TIME_CONSTRAINT)
.addProperty(WON.RECUR_INFINITE_TIMES, Boolean.toString(needPojo.getRecurInfiniteTimes()), XSDDatatype.XSDboolean);
if (!needPojo.getStartTime().isEmpty())
timeConstraint.addProperty(WON.START_TIME, needPojo.getStartTime(), XSDDatatype.XSDdateTime);
if (!needPojo.getStartTime().isEmpty())
timeConstraint.addProperty(WON.END_TIME, needPojo.getEndTime(), XSDDatatype.XSDdateTime);
if (needPojo.getRecurIn() != null)
timeConstraint.addProperty(WON.RECUR_IN, Long.toString(needPojo.getRecurIn()));
if (needPojo.getRecurTimes() != null)
timeConstraint.addProperty(WON.RECUR_TIMES, Integer.toString(needPojo.getRecurTimes()));
needModel.add(needModel.createStatement(needModality, WON.AVAILABLE_AT_TIME, timeConstraint));
}
needModel.add(needModel.createStatement(needResource, WON.HAS_NEED_MODALITY, needModality));
if (needPojo.getWonNode().equals("")) {
//TODO: this is a temporary hack, please fix. The protocol expects boolean and we have an enum for needState
needURI = ownerService.createNeed(ownerURI, needModel, needPojo.getState() == NeedState.ACTIVE);
} else {
needURI = ((OwnerProtocolNeedServiceClient) ownerService).createNeed(ownerURI, needModel, needPojo.getState() == NeedState.ACTIVE, needPojo.getWonNode());
}
List<Need> needs = needRepository.findByNeedURI(needURI);
if (needs.size() == 1)
return "redirect:/need/" + needs.get(0).getId().toString();
// return viewNeed(need.getId().toString(), model);
} catch (IllegalNeedContentException e) {
e.printStackTrace();
}
model.addAttribute("command", new NeedPojo());
return "createNeed";
}
| public String createNeedPost(@ModelAttribute("SpringWeb") NeedPojo needPojo, Model model)
{
URI needURI;
try {
URI ownerURI = this.uriService.getOwnerProtocolOwnerServiceEndpointURI();
com.hp.hpl.jena.rdf.model.Model needModel = ModelFactory.createDefaultModel();
Resource needResource = needModel.createResource(WON.NEED);
//TODO: add this after it is saved to the DB for the first time
// .addProperty(WON.NEED_CREATION_DATE, DateTimeUtils.getCurrentDateTimeStamp(), XSDDatatype.XSDdateTime);
// need type
needModel.add(needModel.createStatement(needResource, WON.HAS_BASIC_NEED_TYPE, WON.toResource(needPojo.getBasicNeedType())));
// need content
Resource needContent = needModel.createResource(WON.NEED_CONTENT);
if (!needPojo.getTitle().isEmpty())
needContent.addProperty(WON.TITLE, needPojo.getTitle(), XSDDatatype.XSDstring);
if (!needPojo.getTextDescription().isEmpty())
needContent.addProperty(WON.TEXT_DESCRIPTION, needPojo.getTextDescription(), XSDDatatype.XSDstring);
needModel.add(needModel.createStatement(needResource, WON.HAS_CONTENT, needContent));
// owner
if (needPojo.isAnonymize()) {
needModel.add(needModel.createStatement(needResource, WON.HAS_OWNER, WON.ANONYMIZED_OWNER));
}
// need modalities
Resource needModality = needModel.createResource(WON.NEED_MODALITY);
needModel.add(needModel.createStatement(needModality, WON.AVAILABLE_DELIVERY_METHOD, GR.toResource(needPojo.getDeliveryMethod())));
// TODO: store need modalities in separate objects to enable easier checking and multiple instances
//price and currency
if (needPojo.getUpperPriceLimit() != null || needPojo.getLowerPriceLimit() != null) {
Resource priceSpecification = needModel.createResource(WON.PRICE_SPECIFICATION);
if (needPojo.getLowerPriceLimit() != null)
priceSpecification.addProperty(WON.HAS_LOWER_PRICE_LIMIT, Double.toString(needPojo.getLowerPriceLimit()), XSDDatatype.XSDdouble);
if (needPojo.getUpperPriceLimit() != null)
priceSpecification.addProperty(WON.HAS_UPPER_PRICE_LIMIT, Double.toString(needPojo.getUpperPriceLimit()), XSDDatatype.XSDdouble);
if (!needPojo.getCurrency().isEmpty())
priceSpecification.addProperty(WON.HAS_CURRENCY, needPojo.getCurrency(), XSDDatatype.XSDstring);
needModel.add(needModel.createStatement(needModality, WON.HAS_PRICE_SPECIFICATION, priceSpecification));
}
if (needPojo.getLatitude() != null && needPojo.getLongitude() != null) {
Resource location = needModel.createResource(GEO.POINT)
.addProperty(GEO.LATITUDE, Double.toString(needPojo.getLatitude()))
.addProperty(GEO.LONGITUDE, Double.toString(needPojo.getLongitude()));
needModel.add(needModel.createStatement(needModality, WON.AVAILABLE_AT_LOCATION, location));
}
// time constraint
if (!needPojo.getStartTime().isEmpty() || !needPojo.getEndTime().isEmpty()) {
Resource timeConstraint = needModel.createResource(WON.TIME_CONSTRAINT)
.addProperty(WON.RECUR_INFINITE_TIMES, Boolean.toString(needPojo.getRecurInfiniteTimes()), XSDDatatype.XSDboolean);
if (!needPojo.getStartTime().isEmpty())
timeConstraint.addProperty(WON.START_TIME, needPojo.getStartTime(), XSDDatatype.XSDdateTime);
if (!needPojo.getEndTime().isEmpty())
timeConstraint.addProperty(WON.END_TIME, needPojo.getEndTime(), XSDDatatype.XSDdateTime);
if (needPojo.getRecurIn() != null)
timeConstraint.addProperty(WON.RECUR_IN, Long.toString(needPojo.getRecurIn()));
if (needPojo.getRecurTimes() != null)
timeConstraint.addProperty(WON.RECUR_TIMES, Integer.toString(needPojo.getRecurTimes()));
needModel.add(needModel.createStatement(needModality, WON.AVAILABLE_AT_TIME, timeConstraint));
}
needModel.add(needModel.createStatement(needResource, WON.HAS_NEED_MODALITY, needModality));
if (needPojo.getWonNode().equals("")) {
//TODO: this is a temporary hack, please fix. The protocol expects boolean and we have an enum for needState
needURI = ownerService.createNeed(ownerURI, needModel, needPojo.getState() == NeedState.ACTIVE);
} else {
needURI = ((OwnerProtocolNeedServiceClient) ownerService).createNeed(ownerURI, needModel, needPojo.getState() == NeedState.ACTIVE, needPojo.getWonNode());
}
List<Need> needs = needRepository.findByNeedURI(needURI);
if (needs.size() == 1)
return "redirect:/need/" + needs.get(0).getId().toString();
// return viewNeed(need.getId().toString(), model);
} catch (IllegalNeedContentException e) {
e.printStackTrace();
}
model.addAttribute("command", new NeedPojo());
return "createNeed";
}
|
diff --git a/src/test/java/org/nebulostore/appcore/NebuloFileTest.java b/src/test/java/org/nebulostore/appcore/NebuloFileTest.java
index c91335e..6687876 100644
--- a/src/test/java/org/nebulostore/appcore/NebuloFileTest.java
+++ b/src/test/java/org/nebulostore/appcore/NebuloFileTest.java
@@ -1,52 +1,52 @@
package org.nebulostore.appcore;
import java.math.BigInteger;
import java.util.Arrays;
import org.junit.Test;
import org.nebulostore.addressing.AppKey;
import org.nebulostore.addressing.ObjectId;
import org.nebulostore.appcore.exceptions.NebuloException;
import static org.junit.Assert.assertTrue;
/**
* Simple unit test for NebuloFile.
*/
public final class NebuloFileTest {
@Test
public void testWriteMultipleChunks() {
- NebuloFile file = new NebuloFile(new AppKey(BigInteger.ONE), new ObjectId(BigInteger.ONE), 10);
+ NebuloFile file = new NebuloFile(new AppKey(BigInteger.ONE), new ObjectId(BigInteger.ONE));
// Do three writes.
byte[] as = new byte[35];
Arrays.fill(as, (byte) 'a');
byte[] bs = new byte[38];
Arrays.fill(bs, (byte) 'b');
byte[] cs = new byte[13];
Arrays.fill(cs, (byte) 'c');
byte[] sum = new byte[53];
System.arraycopy(as, 0, sum, 0, 35);
System.arraycopy(bs, 0, sum, 15, 38);
System.arraycopy(cs, 0, sum, 19, 13);
try {
file.write(as, 0);
file.write(bs, 15);
file.write(cs, 19);
} catch (NebuloException exception) {
assertTrue(false);
}
assertTrue(file.getSize() == 53);
try {
byte[] check = file.read(0, file.getSize());
assertTrue(check.length == 53);
assertTrue(Arrays.equals(check, sum));
} catch (NebuloException exception) {
assertTrue(false);
}
}
}
| true | true | public void testWriteMultipleChunks() {
NebuloFile file = new NebuloFile(new AppKey(BigInteger.ONE), new ObjectId(BigInteger.ONE), 10);
// Do three writes.
byte[] as = new byte[35];
Arrays.fill(as, (byte) 'a');
byte[] bs = new byte[38];
Arrays.fill(bs, (byte) 'b');
byte[] cs = new byte[13];
Arrays.fill(cs, (byte) 'c');
byte[] sum = new byte[53];
System.arraycopy(as, 0, sum, 0, 35);
System.arraycopy(bs, 0, sum, 15, 38);
System.arraycopy(cs, 0, sum, 19, 13);
try {
file.write(as, 0);
file.write(bs, 15);
file.write(cs, 19);
} catch (NebuloException exception) {
assertTrue(false);
}
assertTrue(file.getSize() == 53);
try {
byte[] check = file.read(0, file.getSize());
assertTrue(check.length == 53);
assertTrue(Arrays.equals(check, sum));
} catch (NebuloException exception) {
assertTrue(false);
}
}
| public void testWriteMultipleChunks() {
NebuloFile file = new NebuloFile(new AppKey(BigInteger.ONE), new ObjectId(BigInteger.ONE));
// Do three writes.
byte[] as = new byte[35];
Arrays.fill(as, (byte) 'a');
byte[] bs = new byte[38];
Arrays.fill(bs, (byte) 'b');
byte[] cs = new byte[13];
Arrays.fill(cs, (byte) 'c');
byte[] sum = new byte[53];
System.arraycopy(as, 0, sum, 0, 35);
System.arraycopy(bs, 0, sum, 15, 38);
System.arraycopy(cs, 0, sum, 19, 13);
try {
file.write(as, 0);
file.write(bs, 15);
file.write(cs, 19);
} catch (NebuloException exception) {
assertTrue(false);
}
assertTrue(file.getSize() == 53);
try {
byte[] check = file.read(0, file.getSize());
assertTrue(check.length == 53);
assertTrue(Arrays.equals(check, sum));
} catch (NebuloException exception) {
assertTrue(false);
}
}
|
diff --git a/profiling/org.eclipse.linuxtools.profiling.snapshot/src/org/eclipse/linuxtools/profiling/snapshot/SnapshotOptionsTab.java b/profiling/org.eclipse.linuxtools.profiling.snapshot/src/org/eclipse/linuxtools/profiling/snapshot/SnapshotOptionsTab.java
index a42e8d51f..b83bc1469 100644
--- a/profiling/org.eclipse.linuxtools.profiling.snapshot/src/org/eclipse/linuxtools/profiling/snapshot/SnapshotOptionsTab.java
+++ b/profiling/org.eclipse.linuxtools.profiling.snapshot/src/org/eclipse/linuxtools/profiling/snapshot/SnapshotOptionsTab.java
@@ -1,136 +1,137 @@
/*******************************************************************************
* Copyright (c) 2012 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat initial API and implementation
*******************************************************************************/
package org.eclipse.linuxtools.profiling.snapshot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
import org.eclipse.debug.ui.ILaunchConfigurationTab;
import org.eclipse.linuxtools.profiling.launch.ProfileLaunchConfigurationTab;
import org.eclipse.linuxtools.profiling.launch.ProfileLaunchConfigurationTabGroup;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
public class SnapshotOptionsTab extends ProfileLaunchConfigurationTab {
Composite top;
Combo providerCombo;
AbstractLaunchConfigurationTab[] tabs;
ILaunchConfiguration initial;
String providerId = "";
public void createControl(Composite parent) {
top = new Composite(parent, SWT.NONE);
setControl(top);
top.setLayout(new GridLayout(1, true));
providerCombo = new Combo(top, SWT.READ_ONLY);
providerCombo.setItems(ProfileLaunchConfigurationTabGroup
.getTabGroupIdsForType("snapshot"));
final CTabFolder tabgroup = new CTabFolder(top, SWT.NONE);
providerCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
// dispose of old tabs
for (CTabItem item : tabgroup.getItems()) {
item.dispose();
}
providerId = providerCombo.getText();
// get the tabs associated with the selected ID
tabs = ProfileLaunchConfigurationTabGroup
.getTabGroupProviderFromId(providerId)
.getProfileTabs();
// create the tab item, and load the specified tab inside
for (ILaunchConfigurationTab tab : tabs) {
+ tab.setLaunchConfigurationDialog(getLaunchConfigurationDialog());
CTabItem item = new CTabItem(tabgroup, SWT.NONE);
item.setText(tab.getName());
item.setImage(tab.getImage());
tab.createControl(tabgroup);
item.setControl(tab.getControl());
}
// initialize all tab widgets based on the configuration
initializeFrom(initial);
top.layout();
}
});
}
public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
if (providerCombo != null && !providerCombo.getText().equals("")) {
for (AbstractLaunchConfigurationTab tab : tabs) {
tab.setDefaults(configuration);
}
}
}
public void initializeFrom(ILaunchConfiguration configuration) {
/**
* First time the configuration is selected.
*
* This is a cheap way to get access to the launch configuration.
* Our tabs are loaded dynamically, so the tab group doesn't "know"
* about them. We get access to this launch configuration to ensure
* that we can properly load the widgets the first time.
*/
// store current provider id in the configuration
if (configuration != null) {
setProvider(configuration);
}
if (initial == null){
initial = configuration;
}
if (providerCombo != null && !providerCombo.getText().equals("")) {
for (AbstractLaunchConfigurationTab tab : tabs) {
tab.initializeFrom(configuration);
}
}
}
public void performApply(ILaunchConfigurationWorkingCopy configuration) {
if (providerCombo != null && !providerCombo.getText().equals("")) {
for (AbstractLaunchConfigurationTab tab : tabs) {
tab.performApply(configuration);
}
}
}
public String getName() {
return "Snapshot";
}
/**
* Set the provider attribute in the specified configuration.
* @param configuration a configuration
*/
public void setProvider(ILaunchConfiguration configuration) {
try {
ILaunchConfigurationWorkingCopy wc = configuration.getWorkingCopy();
wc.setAttribute("provider", providerId);
configuration = wc.doSave();
} catch (CoreException e1) {
e1.printStackTrace();
}
}
}
| true | true | public void createControl(Composite parent) {
top = new Composite(parent, SWT.NONE);
setControl(top);
top.setLayout(new GridLayout(1, true));
providerCombo = new Combo(top, SWT.READ_ONLY);
providerCombo.setItems(ProfileLaunchConfigurationTabGroup
.getTabGroupIdsForType("snapshot"));
final CTabFolder tabgroup = new CTabFolder(top, SWT.NONE);
providerCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
// dispose of old tabs
for (CTabItem item : tabgroup.getItems()) {
item.dispose();
}
providerId = providerCombo.getText();
// get the tabs associated with the selected ID
tabs = ProfileLaunchConfigurationTabGroup
.getTabGroupProviderFromId(providerId)
.getProfileTabs();
// create the tab item, and load the specified tab inside
for (ILaunchConfigurationTab tab : tabs) {
CTabItem item = new CTabItem(tabgroup, SWT.NONE);
item.setText(tab.getName());
item.setImage(tab.getImage());
tab.createControl(tabgroup);
item.setControl(tab.getControl());
}
// initialize all tab widgets based on the configuration
initializeFrom(initial);
top.layout();
}
});
}
| public void createControl(Composite parent) {
top = new Composite(parent, SWT.NONE);
setControl(top);
top.setLayout(new GridLayout(1, true));
providerCombo = new Combo(top, SWT.READ_ONLY);
providerCombo.setItems(ProfileLaunchConfigurationTabGroup
.getTabGroupIdsForType("snapshot"));
final CTabFolder tabgroup = new CTabFolder(top, SWT.NONE);
providerCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
// dispose of old tabs
for (CTabItem item : tabgroup.getItems()) {
item.dispose();
}
providerId = providerCombo.getText();
// get the tabs associated with the selected ID
tabs = ProfileLaunchConfigurationTabGroup
.getTabGroupProviderFromId(providerId)
.getProfileTabs();
// create the tab item, and load the specified tab inside
for (ILaunchConfigurationTab tab : tabs) {
tab.setLaunchConfigurationDialog(getLaunchConfigurationDialog());
CTabItem item = new CTabItem(tabgroup, SWT.NONE);
item.setText(tab.getName());
item.setImage(tab.getImage());
tab.createControl(tabgroup);
item.setControl(tab.getControl());
}
// initialize all tab widgets based on the configuration
initializeFrom(initial);
top.layout();
}
});
}
|
diff --git a/torquebox-core/src/main/java/org/torquebox/ruby/core/runtime/DefaultRubyRuntimeFactory.java b/torquebox-core/src/main/java/org/torquebox/ruby/core/runtime/DefaultRubyRuntimeFactory.java
index b29703f64..6c7be4a89 100644
--- a/torquebox-core/src/main/java/org/torquebox/ruby/core/runtime/DefaultRubyRuntimeFactory.java
+++ b/torquebox-core/src/main/java/org/torquebox/ruby/core/runtime/DefaultRubyRuntimeFactory.java
@@ -1,174 +1,174 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.torquebox.ruby.core.runtime;
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.jboss.Version;
import org.jboss.beans.metadata.api.annotations.Create;
import org.jboss.kernel.Kernel;
import org.jboss.logging.Logger;
import org.jruby.Ruby;
import org.jruby.RubyInstanceConfig;
import org.jruby.RubyModule;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.util.ClassCache;
import org.torquebox.ruby.core.runtime.spi.RubyDynamicClassLoader;
import org.torquebox.ruby.core.runtime.spi.RubyRuntimeFactory;
import org.torquebox.ruby.core.runtime.spi.RuntimeInitializer;
public class DefaultRubyRuntimeFactory implements RubyRuntimeFactory {
private static final Logger log = Logger.getLogger( DefaultRubyRuntimeFactory.class );
private Kernel kernel;
private RuntimeInitializer initializer;
private DefaultRubyDynamicClassLoader classLoader;
private ClassCache<?> classCache;
private String applicationName;
public DefaultRubyRuntimeFactory() {
this(null);
}
public DefaultRubyRuntimeFactory(RuntimeInitializer initializer) {
this.initializer = initializer;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public String getApplicationName() {
return this.applicationName;
}
public void setKernel(Kernel kernel) {
this.kernel = kernel;
}
public Kernel getKernel() {
return this.kernel;
}
public void setClassLoader(DefaultRubyDynamicClassLoader classLoader) {
this.classLoader = classLoader;
}
public RubyDynamicClassLoader getClassLoader() {
return this.classLoader;
}
@Create(ignored=true)
public synchronized Ruby create() throws Exception {
- log.error( "CREATING RUBY RUNTIME HERE: ", new Exception() );
+// log.error( "CREATING RUBY RUNTIME HERE: ", new Exception() );
RubyInstanceConfig config = new RubyInstanceConfig();
DefaultRubyDynamicClassLoader childLoader = this.classLoader
.createChild();
config.setLoader(childLoader);
if (this.classCache == null) {
this.classCache = new ClassCache<Object>(this.classLoader);
}
config.setClassCache(classCache);
String jrubyHome = null;
jrubyHome = System.getProperty("jruby.home");
if (jrubyHome == null) {
jrubyHome = System.getenv("JRUBY_HOME");
}
if ( jrubyHome == null ) {
String jbossHome = System.getProperty( "jboss.home" );
if ( jbossHome != null ) {
File candidatePath = new File( jbossHome, "../jruby" );
if ( candidatePath.exists() && candidatePath.isDirectory() ) {
jrubyHome = candidatePath.getAbsolutePath();
}
}
}
if ( jrubyHome == null ) {
String binJruby = RubyInstanceConfig.class.getResource( "/META-INF/jruby.home/bin/jruby").toURI() .getSchemeSpecificPart();
jrubyHome = binJruby.substring(0, binJruby.length() - 10);
}
if ( jrubyHome != null ) {
config.setJRubyHome( jrubyHome );
}
config.setEnvironment(getEnvironment());
config.setOutput(getOutput());
config.setError(getError());
List<String> loadPath = new ArrayList<String>();
loadPath.add("META-INF/jruby.home/lib/ruby/site_ruby/1.8");
Ruby runtime = JavaEmbedUtils.initialize(loadPath, config);
if (this.initializer != null) {
this.initializer.initialize(childLoader, runtime);
}
injectKernel(runtime);
setUpConstants(runtime, this.applicationName);
return runtime;
}
private void setUpConstants(Ruby runtime, String applicationName) {
runtime
.evalScriptlet("require %q(org/torquebox/ruby/core/runtime/runtime_constants)\n");
RubyModule jbossModule = runtime.getClassFromPath("JBoss");
JavaEmbedUtils.invokeMethod(runtime, jbossModule, "setup_constants",
new Object[] { Version.getInstance(), applicationName },
void.class);
}
private void injectKernel(Ruby runtime) {
runtime
.evalScriptlet("require %q(org/torquebox/ruby/core/runtime/kernel)");
RubyModule jbossKernel = runtime.getClassFromPath("TorqueBox::Kernel");
JavaEmbedUtils.invokeMethod(runtime, jbossKernel, "kernel=",
new Object[] { this.kernel }, void.class);
}
public Map<Object, Object> getEnvironment() {
return Collections.emptyMap();
}
public PrintStream getOutput() {
return System.out;
}
public PrintStream getError() {
return System.err;
}
}
| true | true | public synchronized Ruby create() throws Exception {
log.error( "CREATING RUBY RUNTIME HERE: ", new Exception() );
RubyInstanceConfig config = new RubyInstanceConfig();
DefaultRubyDynamicClassLoader childLoader = this.classLoader
.createChild();
config.setLoader(childLoader);
if (this.classCache == null) {
this.classCache = new ClassCache<Object>(this.classLoader);
}
config.setClassCache(classCache);
String jrubyHome = null;
jrubyHome = System.getProperty("jruby.home");
if (jrubyHome == null) {
jrubyHome = System.getenv("JRUBY_HOME");
}
if ( jrubyHome == null ) {
String jbossHome = System.getProperty( "jboss.home" );
if ( jbossHome != null ) {
File candidatePath = new File( jbossHome, "../jruby" );
if ( candidatePath.exists() && candidatePath.isDirectory() ) {
jrubyHome = candidatePath.getAbsolutePath();
}
}
}
if ( jrubyHome == null ) {
String binJruby = RubyInstanceConfig.class.getResource( "/META-INF/jruby.home/bin/jruby").toURI() .getSchemeSpecificPart();
jrubyHome = binJruby.substring(0, binJruby.length() - 10);
}
if ( jrubyHome != null ) {
config.setJRubyHome( jrubyHome );
}
config.setEnvironment(getEnvironment());
config.setOutput(getOutput());
config.setError(getError());
List<String> loadPath = new ArrayList<String>();
loadPath.add("META-INF/jruby.home/lib/ruby/site_ruby/1.8");
Ruby runtime = JavaEmbedUtils.initialize(loadPath, config);
if (this.initializer != null) {
this.initializer.initialize(childLoader, runtime);
}
injectKernel(runtime);
setUpConstants(runtime, this.applicationName);
return runtime;
}
| public synchronized Ruby create() throws Exception {
// log.error( "CREATING RUBY RUNTIME HERE: ", new Exception() );
RubyInstanceConfig config = new RubyInstanceConfig();
DefaultRubyDynamicClassLoader childLoader = this.classLoader
.createChild();
config.setLoader(childLoader);
if (this.classCache == null) {
this.classCache = new ClassCache<Object>(this.classLoader);
}
config.setClassCache(classCache);
String jrubyHome = null;
jrubyHome = System.getProperty("jruby.home");
if (jrubyHome == null) {
jrubyHome = System.getenv("JRUBY_HOME");
}
if ( jrubyHome == null ) {
String jbossHome = System.getProperty( "jboss.home" );
if ( jbossHome != null ) {
File candidatePath = new File( jbossHome, "../jruby" );
if ( candidatePath.exists() && candidatePath.isDirectory() ) {
jrubyHome = candidatePath.getAbsolutePath();
}
}
}
if ( jrubyHome == null ) {
String binJruby = RubyInstanceConfig.class.getResource( "/META-INF/jruby.home/bin/jruby").toURI() .getSchemeSpecificPart();
jrubyHome = binJruby.substring(0, binJruby.length() - 10);
}
if ( jrubyHome != null ) {
config.setJRubyHome( jrubyHome );
}
config.setEnvironment(getEnvironment());
config.setOutput(getOutput());
config.setError(getError());
List<String> loadPath = new ArrayList<String>();
loadPath.add("META-INF/jruby.home/lib/ruby/site_ruby/1.8");
Ruby runtime = JavaEmbedUtils.initialize(loadPath, config);
if (this.initializer != null) {
this.initializer.initialize(childLoader, runtime);
}
injectKernel(runtime);
setUpConstants(runtime, this.applicationName);
return runtime;
}
|
diff --git a/src/main/com/trendrr/oss/cache/TrendrrCache.java b/src/main/com/trendrr/oss/cache/TrendrrCache.java
index 0713e62..83b1c77 100644
--- a/src/main/com/trendrr/oss/cache/TrendrrCache.java
+++ b/src/main/com/trendrr/oss/cache/TrendrrCache.java
@@ -1,386 +1,389 @@
/**
*
*/
package com.trendrr.oss.cache;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.trendrr.oss.DynMap;
import com.trendrr.oss.StringHelper;
import com.trendrr.oss.TypeCast;
import com.trendrr.oss.concurrent.LazyInit;
import com.trendrr.oss.exceptions.TrendrrParseException;
/**
*
* A cache wrapper. should be be easily adapted for in memory caching as
* well as many other datastores.
*
* @author Dustin Norlander
* @created Dec 29, 2011
*
*/
public abstract class TrendrrCache {
protected static Log log = LogFactory.getLog(TrendrrCache.class);
/**
* initialize the connection. called exactly once the first time the cache is accessed.
*/
protected abstract void _init(DynMap config);
/**
* Set a key - value pair
*
* @param key
* @param obj
* @param expires
*/
protected abstract void _set(String key, Object obj, Date expires);
/**
* Deletes the key value pair
* @param key
*/
protected abstract void _del(String key);
/**
* get the value at a key
* @param key
* @return
*/
protected abstract Object _get(String key);
/**
* returns the values at the given set of keys
* @param keys
* @return
*/
protected abstract Map<String, Object> _getMulti(Set<String> keys);
/**
* increment a key.
* @param key
* @param value
* @param expire when this key should expire. null for forever (if available)
*/
protected abstract long _inc(String key, int value, Date expire);
/**
* increments multiple keys in a map.
* @param key
* @param values
* @param expire
*/
protected abstract void _incMulti(String key, Map<String, Integer> values, Date expire);
/**
* gets the map from an incMulti call.
* @param key
* @return
*/
protected abstract Map<String,Long> _getIncMulti(String key);
/**
* Add these items into a set add the given key.
* @param str
* @return
*/
protected abstract Set<String> _addToSet(String key, Collection<String> str, Date expire);
/**
* loads a previous created set.
* @param key
* @return
*/
protected abstract Set<String> _getSet(String key);
/**
* Remove from a set
* @param str
* @return
*/
protected abstract Set<String> _removeFromSet(String key, Collection<String> str);
/**
* should set the key if and only if the value doesn't already exist. Should return whether the item was inserted or not.
* @param key
* @param value
* @param expires
*/
protected abstract boolean _setIfAbsent(String key, Object value, Date expires);
/**
* initialize a new cache. should be passed any config params that the specific implementation should need.
*
* @param config
*/
public TrendrrCache(DynMap config) {
this.config = config;
}
protected DynMap config = new DynMap();
private LazyInit initLock = new LazyInit();
/**
* initializes the cache. this is called exactly once. is not required to explicitly call this, as it will be called the
* first time the cache is accessed.
*/
public void init() {
if (initLock.start()) {
try {
this._init(this.config);
} finally {
initLock.end();
}
}
}
/**
* reinitializes.
*/
protected void reinit() {
this.initLock.reset();
this.init();
}
/**
* sets a key given the requested namespace.
* @param namespace
* @param key
* @param obj
* @param expires
*/
public void set(String namespace, String key, Object obj, Date expires) {
this.init();
this._set(this.getKey(namespace, key), obj, expires);
}
/**
* atomically adds the values to a Set (a collection with no duplicates).
*
* This is meant for record keeping, for small collections. definitly do not use for
* queues, or any set with many items.
*
* @param namespace
* @param key
* @param values
* @param expires
*/
public void addToSet(String namespace, String key, Collection<String> values, Date expire) {
this.init();
this._addToSet(this.getKey(namespace, key), values, expire);
}
/**
* loads a Set
* @param namespace
* @param key
* @return
*/
public Set<String> getSet(String namespace, String key) {
this.init();
return this._getSet(this.getKey(namespace, key));
}
public Set<String> getSet(String key) {
return this.getSet(null, key);
}
/**
* sets the key with the default namespace
* @param namespace
* @param key
* @param obj
* @param expires
*/
public void set(String key, Object obj, Date expires) {
this.set(null, key, obj, expires);
}
protected String getKey(String namespace, String key){
// log.info("Getting key from: " + namespace + " " + key );
if (namespace != null) {
key = namespace + key;
}
if (key.length() > 24) {
try {
key = StringHelper.sha1Hex(key.getBytes("utf8"));
} catch (UnsupportedEncodingException e) {
log.warn("Invalid key: " + key, e);
}
}
// log.info("key: " + key);
return key;
}
/**
* sets the key if and only if the key does not already exist
* @param namespace
* @param key
* @param value
* @param expires
* @return
*/
public boolean setIfAbsent(String namespace, String key, Object value, Date expires) {
this.init();
return this._setIfAbsent(this.getKey(namespace, key), value, expires);
}
/**
* uses the default namespace
* @param key
* @param value
* @param expires
* @return
*/
public boolean setIfAbsent(String key, Object value, Date expires) {
return this.setIfAbsent(null, key, value, expires);
}
/**
* Gets the value at the specified namespace and key.
* @param namespace
* @param key
* @return
*/
public Object get(String namespace, String key) {
this.init();
return this._get(this.getKey(namespace, key));
}
/**
* gets the value from the default namespace.
* @param key
* @return
*/
public Object get(String key) {
return this.get(null, key);
}
/**
* gets a typed value
* @param cls
* @param namespace
* @param key
* @return
*/
public <T> T get(Class<T> cls, String namespace, String key) {
return TypeCast.cast(cls, this.get(namespace, key));
}
public Map<String, Long> getIncMulti(String namespace, String key) {
this.init();
return this._getIncMulti(this.getKey(namespace, key));
}
public Map<String, Long> getIncMulti(String key) {
return this.getIncMulti(null, key);
}
/**
* returns a map of
* @param namespace
* @param keys
* @return
*/
public DynMap getMulti(String namespace, Collection<String> keys) {
this.init();
/*
* does some copying around here in order to keep with our namespaced keys.
*/
HashSet<String> k = new HashSet<String>();
HashMap<String, String> newKeys = new HashMap<String,String>();
for (String key : keys) {
String newKey = this.getKey(namespace, key);
newKeys.put(newKey, key);
k.add(newKey);
}
Map<String, Object> results = this._getMulti(k);
DynMap newResults = new DynMap();
+ if (results == null){
+ return newResults;
+ }
for (String key : results.keySet()) {
newResults.put(newKeys.get(key), results.get(key));
}
return newResults;
}
public Map<String, Object> getMulti(Collection<String> keys) {
return this.getMulti(null, keys);
}
/**
* deletes the specified key
* @param namespace
* @param key
*/
public void delete(String namespace, String key) {
this.init();
this._del(this.getKey(namespace, key));
}
/**
*
* @param key
*/
public void delete(String key) {
this.delete(null, key);
}
/**
* increments the specified key
* @param namespace
* @param key
* @param value
*/
public long inc(String namespace, String key, int value, Date expire) {
this.init();
return this._inc(this.getKey(namespace, key), value, expire);
}
/**
*
* @param namespace
* @param key
* @param value
*/
public long inc(String key, int value, Date expire) {
return this.inc(null, key, value, expire);
}
/**
* increments multiple keys in a map (ex: a redis hashmap).
* @param namespace
* @param key
* @param values
* @param expire
*/
public void incMulti(String namespace, String key, Map<String, Integer> values, Date expire) {
this.init();
this._incMulti(this.getKey(namespace, key), values, expire);
}
/**
* increments multiple keys in a map (ex: a redis hashmap).
* @param namespace
* @param key
* @param values
* @param expire
*/
public void incMulti(String key, Map<String, Integer> values, Date expire) {
this.incMulti(null, key, values, expire);
}
}
| true | true | public DynMap getMulti(String namespace, Collection<String> keys) {
this.init();
/*
* does some copying around here in order to keep with our namespaced keys.
*/
HashSet<String> k = new HashSet<String>();
HashMap<String, String> newKeys = new HashMap<String,String>();
for (String key : keys) {
String newKey = this.getKey(namespace, key);
newKeys.put(newKey, key);
k.add(newKey);
}
Map<String, Object> results = this._getMulti(k);
DynMap newResults = new DynMap();
for (String key : results.keySet()) {
newResults.put(newKeys.get(key), results.get(key));
}
return newResults;
}
| public DynMap getMulti(String namespace, Collection<String> keys) {
this.init();
/*
* does some copying around here in order to keep with our namespaced keys.
*/
HashSet<String> k = new HashSet<String>();
HashMap<String, String> newKeys = new HashMap<String,String>();
for (String key : keys) {
String newKey = this.getKey(namespace, key);
newKeys.put(newKey, key);
k.add(newKey);
}
Map<String, Object> results = this._getMulti(k);
DynMap newResults = new DynMap();
if (results == null){
return newResults;
}
for (String key : results.keySet()) {
newResults.put(newKeys.get(key), results.get(key));
}
return newResults;
}
|
diff --git a/gdx/src/com/badlogic/gdx/graphics/OrthographicCamera.java b/gdx/src/com/badlogic/gdx/graphics/OrthographicCamera.java
index 8d3857515..d4a7f2594 100644
--- a/gdx/src/com/badlogic/gdx/graphics/OrthographicCamera.java
+++ b/gdx/src/com/badlogic/gdx/graphics/OrthographicCamera.java
@@ -1,62 +1,62 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
/**
* A camera with orthographic projection.
*
* @author mzechner
*
*/
public class OrthographicCamera extends Camera {
/** the zoom of the camera **/
public float zoom = 1;
public OrthographicCamera() {
this.near = 0;
}
/**
* Constructs a new OrthographicCamera, using the given viewport
* width and height. For pixel perfect 2D rendering just supply
* the screen size, for other unit scales (e.g. meters for box2d)
* proceed accordingly.
*
* @param viewportWidth the viewport width
* @param viewportHeight the viewport height
*/
public OrthographicCamera(float viewportWidth, float viewportHeight) {
this.viewportWidth = viewportWidth;
this.viewportHeight = viewportHeight;
this.near = 0;
update();
}
private final Vector3 tmp = new Vector3();
@Override
public void update() {
projection.setToOrtho(zoom * -viewportWidth / 2, zoom * viewportWidth / 2, zoom * -viewportHeight / 2, zoom * viewportHeight / 2, Math.abs(near), Math.abs(far));
view.setToLookAt(position, tmp.set(position).add(direction), up);
combined.set(projection);
Matrix4.mul(combined.val, view.val);
invProjectionView.set(combined);
Matrix4.inv(invProjectionView.val);
- frustum.update(combined);
+ frustum.update(invProjectionView);
}
}
| true | true | public void update() {
projection.setToOrtho(zoom * -viewportWidth / 2, zoom * viewportWidth / 2, zoom * -viewportHeight / 2, zoom * viewportHeight / 2, Math.abs(near), Math.abs(far));
view.setToLookAt(position, tmp.set(position).add(direction), up);
combined.set(projection);
Matrix4.mul(combined.val, view.val);
invProjectionView.set(combined);
Matrix4.inv(invProjectionView.val);
frustum.update(combined);
}
| public void update() {
projection.setToOrtho(zoom * -viewportWidth / 2, zoom * viewportWidth / 2, zoom * -viewportHeight / 2, zoom * viewportHeight / 2, Math.abs(near), Math.abs(far));
view.setToLookAt(position, tmp.set(position).add(direction), up);
combined.set(projection);
Matrix4.mul(combined.val, view.val);
invProjectionView.set(combined);
Matrix4.inv(invProjectionView.val);
frustum.update(invProjectionView);
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskEditorBloatMonitor.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskEditorBloatMonitor.java
index e914d1253..8778600d0 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskEditorBloatMonitor.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskEditorBloatMonitor.java
@@ -1,71 +1,72 @@
/*******************************************************************************
* Copyright (c) 2004, 2009 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditor;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
/**
* @author Mik Kersten
* @author Steffen Pingel
*/
public class TaskEditorBloatMonitor {
private final static int MAX_EDITORS = 12;
public static void editorOpened(IEditorPart editorPartOpened) {
IWorkbenchPage page = editorPartOpened.getSite().getPage();
List<IEditorReference> toClose = new ArrayList<IEditorReference>();
int totalTaskEditors = 0;
for (IEditorReference editorReference : page.getEditorReferences()) {
if (TaskEditor.ID_EDITOR.equals(editorReference.getId())) {
totalTaskEditors++;
}
}
if (totalTaskEditors > MAX_EDITORS) {
for (IEditorReference editorReference : page.getEditorReferences()) {
try {
- if (TaskEditor.ID_EDITOR.equals(editorReference.getId())) {
+ if (editorPartOpened != editorReference.getPart(false)
+ && TaskEditor.ID_EDITOR.equals(editorReference.getId())) {
TaskEditorInput taskEditorInput = (TaskEditorInput) editorReference.getEditorInput();
TaskEditor taskEditor = (TaskEditor) editorReference.getEditor(false);
if (taskEditor == null) {
toClose.add(editorReference);
} else if (!taskEditor.equals(editorPartOpened) && !taskEditor.isDirty()
&& taskEditorInput.getTask() != null
&& taskEditorInput.getTask().getSynchronizationState().isSynchronized()) {
toClose.add(editorReference);
}
}
if ((totalTaskEditors - toClose.size()) <= MAX_EDITORS) {
break;
}
} catch (PartInitException e) {
// ignore
}
}
}
if (toClose.size() > 0) {
page.closeEditors(toClose.toArray(new IEditorReference[toClose.size()]), true);
}
}
}
| true | true | public static void editorOpened(IEditorPart editorPartOpened) {
IWorkbenchPage page = editorPartOpened.getSite().getPage();
List<IEditorReference> toClose = new ArrayList<IEditorReference>();
int totalTaskEditors = 0;
for (IEditorReference editorReference : page.getEditorReferences()) {
if (TaskEditor.ID_EDITOR.equals(editorReference.getId())) {
totalTaskEditors++;
}
}
if (totalTaskEditors > MAX_EDITORS) {
for (IEditorReference editorReference : page.getEditorReferences()) {
try {
if (TaskEditor.ID_EDITOR.equals(editorReference.getId())) {
TaskEditorInput taskEditorInput = (TaskEditorInput) editorReference.getEditorInput();
TaskEditor taskEditor = (TaskEditor) editorReference.getEditor(false);
if (taskEditor == null) {
toClose.add(editorReference);
} else if (!taskEditor.equals(editorPartOpened) && !taskEditor.isDirty()
&& taskEditorInput.getTask() != null
&& taskEditorInput.getTask().getSynchronizationState().isSynchronized()) {
toClose.add(editorReference);
}
}
if ((totalTaskEditors - toClose.size()) <= MAX_EDITORS) {
break;
}
} catch (PartInitException e) {
// ignore
}
}
}
if (toClose.size() > 0) {
page.closeEditors(toClose.toArray(new IEditorReference[toClose.size()]), true);
}
}
| public static void editorOpened(IEditorPart editorPartOpened) {
IWorkbenchPage page = editorPartOpened.getSite().getPage();
List<IEditorReference> toClose = new ArrayList<IEditorReference>();
int totalTaskEditors = 0;
for (IEditorReference editorReference : page.getEditorReferences()) {
if (TaskEditor.ID_EDITOR.equals(editorReference.getId())) {
totalTaskEditors++;
}
}
if (totalTaskEditors > MAX_EDITORS) {
for (IEditorReference editorReference : page.getEditorReferences()) {
try {
if (editorPartOpened != editorReference.getPart(false)
&& TaskEditor.ID_EDITOR.equals(editorReference.getId())) {
TaskEditorInput taskEditorInput = (TaskEditorInput) editorReference.getEditorInput();
TaskEditor taskEditor = (TaskEditor) editorReference.getEditor(false);
if (taskEditor == null) {
toClose.add(editorReference);
} else if (!taskEditor.equals(editorPartOpened) && !taskEditor.isDirty()
&& taskEditorInput.getTask() != null
&& taskEditorInput.getTask().getSynchronizationState().isSynchronized()) {
toClose.add(editorReference);
}
}
if ((totalTaskEditors - toClose.size()) <= MAX_EDITORS) {
break;
}
} catch (PartInitException e) {
// ignore
}
}
}
if (toClose.size() > 0) {
page.closeEditors(toClose.toArray(new IEditorReference[toClose.size()]), true);
}
}
|
diff --git a/test/org/red5/io/mp4/MP4FrameTest.java b/test/org/red5/io/mp4/MP4FrameTest.java
index 34ee3e50..a9e449e9 100644
--- a/test/org/red5/io/mp4/MP4FrameTest.java
+++ b/test/org/red5/io/mp4/MP4FrameTest.java
@@ -1,81 +1,81 @@
package org.red5.io.mp4;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import junit.framework.TestCase;
import org.junit.Test;
import org.red5.io.mp4.MP4Frame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MP4FrameTest extends TestCase {
private static Logger log = LoggerFactory.getLogger(MP4FrameTest.class);
@Test
public void testSort() {
log.debug("Test sort");
List<MP4Frame> frames = new ArrayList<MP4Frame>(6);
//create some frames
MP4Frame frame1 = new MP4Frame();
frame1.setTime(1);
frame1.setOffset(1);
frames.add(frame1);
MP4Frame frame2 = new MP4Frame();
frame2.setTime(6);
frame2.setOffset(6);
frames.add(frame2);
MP4Frame frame3 = new MP4Frame();
frame3.setTime(660);
frame3.setOffset(660);
frames.add(frame3);
MP4Frame frame4 = new MP4Frame();
frame4.setTime(3);
frame4.setOffset(3);
frames.add(frame4);
MP4Frame frame5 = new MP4Frame();
frame5.setTime(400);
frame5.setOffset(400);
frames.add(frame5);
MP4Frame frame6 = new MP4Frame();
frame6.setTime(1000);
frame6.setOffset(1010);
frames.add(frame6);
MP4Frame frame7 = new MP4Frame();
frame7.setTime(1000);
frame7.setOffset(1000);
frames.add(frame7);
MP4Frame frame8 = new MP4Frame();
frame8.setTime(1000);
frame8.setOffset(900);
frames.add(frame8);
- System.out.printf("Frame 1 - time: %d (should be 660)\n", frames.get(2).getTime());
+ System.out.printf("Frame 1 - time: %s (should be 660)\n", frames.get(2).getTime());
Collections.sort(frames);
System.out.println("After sorting");
int f = 1;
for (MP4Frame frame : frames) {
- System.out.printf("Frame %d - time: %d offset: %d\n", f++, frame.getTime(), frame.getOffset());
+ System.out.printf("Frame %s - time: %s offset: %s\n", f++, frame.getTime(), frame.getOffset());
}
}
}
| false | true | public void testSort() {
log.debug("Test sort");
List<MP4Frame> frames = new ArrayList<MP4Frame>(6);
//create some frames
MP4Frame frame1 = new MP4Frame();
frame1.setTime(1);
frame1.setOffset(1);
frames.add(frame1);
MP4Frame frame2 = new MP4Frame();
frame2.setTime(6);
frame2.setOffset(6);
frames.add(frame2);
MP4Frame frame3 = new MP4Frame();
frame3.setTime(660);
frame3.setOffset(660);
frames.add(frame3);
MP4Frame frame4 = new MP4Frame();
frame4.setTime(3);
frame4.setOffset(3);
frames.add(frame4);
MP4Frame frame5 = new MP4Frame();
frame5.setTime(400);
frame5.setOffset(400);
frames.add(frame5);
MP4Frame frame6 = new MP4Frame();
frame6.setTime(1000);
frame6.setOffset(1010);
frames.add(frame6);
MP4Frame frame7 = new MP4Frame();
frame7.setTime(1000);
frame7.setOffset(1000);
frames.add(frame7);
MP4Frame frame8 = new MP4Frame();
frame8.setTime(1000);
frame8.setOffset(900);
frames.add(frame8);
System.out.printf("Frame 1 - time: %d (should be 660)\n", frames.get(2).getTime());
Collections.sort(frames);
System.out.println("After sorting");
int f = 1;
for (MP4Frame frame : frames) {
System.out.printf("Frame %d - time: %d offset: %d\n", f++, frame.getTime(), frame.getOffset());
}
}
| public void testSort() {
log.debug("Test sort");
List<MP4Frame> frames = new ArrayList<MP4Frame>(6);
//create some frames
MP4Frame frame1 = new MP4Frame();
frame1.setTime(1);
frame1.setOffset(1);
frames.add(frame1);
MP4Frame frame2 = new MP4Frame();
frame2.setTime(6);
frame2.setOffset(6);
frames.add(frame2);
MP4Frame frame3 = new MP4Frame();
frame3.setTime(660);
frame3.setOffset(660);
frames.add(frame3);
MP4Frame frame4 = new MP4Frame();
frame4.setTime(3);
frame4.setOffset(3);
frames.add(frame4);
MP4Frame frame5 = new MP4Frame();
frame5.setTime(400);
frame5.setOffset(400);
frames.add(frame5);
MP4Frame frame6 = new MP4Frame();
frame6.setTime(1000);
frame6.setOffset(1010);
frames.add(frame6);
MP4Frame frame7 = new MP4Frame();
frame7.setTime(1000);
frame7.setOffset(1000);
frames.add(frame7);
MP4Frame frame8 = new MP4Frame();
frame8.setTime(1000);
frame8.setOffset(900);
frames.add(frame8);
System.out.printf("Frame 1 - time: %s (should be 660)\n", frames.get(2).getTime());
Collections.sort(frames);
System.out.println("After sorting");
int f = 1;
for (MP4Frame frame : frames) {
System.out.printf("Frame %s - time: %s offset: %s\n", f++, frame.getTime(), frame.getOffset());
}
}
|
diff --git a/n3phele/src/n3phele/service/actions/FileTransferAction.java b/n3phele/src/n3phele/service/actions/FileTransferAction.java
index 3237ec0..a2e0023 100644
--- a/n3phele/src/n3phele/service/actions/FileTransferAction.java
+++ b/n3phele/src/n3phele/service/actions/FileTransferAction.java
@@ -1,506 +1,506 @@
package n3phele.service.actions;
/**
* (C) Copyright 2010-2013. Nigel Cook. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Licensed under the terms described in LICENSE file that accompanied this code, (the "License"); you may not use this file
* except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
import java.net.URI;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Level;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import n3phele.service.core.Resource;
import n3phele.service.core.UnprocessableEntityException;
import n3phele.service.model.Action;
import n3phele.service.model.Command;
import n3phele.service.model.Context;
import n3phele.service.model.Origin;
import n3phele.service.model.ParameterType;
import n3phele.service.model.SignalKind;
import n3phele.service.model.TypedParameter;
import n3phele.service.model.core.Credential;
import n3phele.service.model.core.Helpers;
import n3phele.service.model.core.Task;
import n3phele.service.model.core.User;
import n3phele.service.model.repository.Repository;
import n3phele.service.rest.impl.ActionResource;
import n3phele.service.rest.impl.RepositoryResource;
import n3phele.service.rest.impl.UserResource;
import com.googlecode.objectify.annotation.Cache;
import com.googlecode.objectify.annotation.Embed;
import com.googlecode.objectify.annotation.EntitySubclass;
import com.googlecode.objectify.annotation.Unindex;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import com.sun.jersey.api.representation.Form;
/** Runs a command on a cloud server
*
* @author Nigel Cook
*
*/
@EntitySubclass
@XmlRootElement(name = "FileTransferAction")
@XmlType(name = "FileTransferAction", propOrder = {})
@Unindex
@Cache
public class FileTransferAction extends Action {
final private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(FileTransferAction.class.getName());
@XmlTransient private ActionLogger logger;
private String target;
@XmlTransient
@Embed
private Credential clientCredential=null;
private String instance;
private Long epoch = 0L;
private Long clientUnresponsive = null;
public FileTransferAction() {}
protected FileTransferAction(User owner, String name,
Context context) {
super(owner.getUri(), name, context);
}
/* (non-Javadoc)
* @see n3phele.service.model.Action#getDescription()
*/
@Override
public String getDescription() {
return "File transfer";
}
/*
* (non-Javadoc)
* @see n3phele.service.model.Action#getPrototype()
*/
@Override
public Command getPrototype() {
Command command = new Command();
command.setUri(UriBuilder.fromUri(ActionResource.dao.path).path("history").path(this.getClass().getSimpleName()).build());
command.setName("FileTransfer");
command.setOwner(this.getOwner());
command.setOwnerName(this.getOwner().toString());
command.setPublic(false);
command.setDescription("Transfer a file between a VM and Cloud repository");
command.setPreferred(true);
command.setVersion("1");
command.setIcon(URI.create("https://www.n3phele.com/icons/fileTransfer"));
List<TypedParameter> myParameters = new ArrayList<TypedParameter>();
command.setExecutionParameters(myParameters);
myParameters.add(new TypedParameter("target", "VM action URI", ParameterType.String, "", ""));
myParameters.add(new TypedParameter("source", "source file", ParameterType.String, "", ""));
myParameters.add(new TypedParameter("destination", "destination file", ParameterType.String, "", ""));
for(TypedParameter param : command.getExecutionParameters()) {
param.setDefaultValue(this.context.getValue(param.getName()));
}
return command;
}
@Override
public void init() throws Exception {
logger = new ActionLogger(this);
log.info(this.getContext().getValue("arg"));
this.target = this.getContext().getValue("target");
Action vm = ActionResource.dao.load(URI.create(this.target));
VMAction targetVM = null;
if(!(vm instanceof VMAction)) {
logger.error(this.target+" is not a VM. Got "+vm.getClass().getSimpleName());
log.warning(this.target+" is not a VM. Got "+vm.getClass().getSimpleName());
throw new IllegalArgumentException(this.target+" is not a VM. Got "+vm.getClass().getSimpleName());
} else {
targetVM = (VMAction) vm;
}
if(this.clientCredential == null) {
this.clientCredential = new Credential(
targetVM.getContext().getValue("agentUser"),
targetVM.getContext().getValue("agentSecret")).encrypt();
}
Client client = ClientFactory.create();
try {
Credential plain = this.clientCredential.decrypt();
client.addFilter(new HTTPBasicAuthFilter(plain.getAccount(), plain.getSecret()));
client.setReadTimeout(30000);
client.setConnectTimeout(5000);
URI src = this.context.getFileValue("source");
URI dest = this.context.getFileValue("destination");
if(epoch == 0) {
epoch = Calendar.getInstance().getTimeInMillis();
}
Form form = new Form();
String srcRepoName = src.getScheme();
if("file".equals(srcRepoName)) {
form.add("srcRoot", ".");
- form.add("srcKey", src.getPath());
+ form.add("srcKey", src.getPath().substring(1));
form.add("srcKind", "File");
} else {
Repository repo = RepositoryResource.dao.load(srcRepoName, UserResource.dao.load(this.getOwner()));
form.add("source", repo.getTarget());
form.add("srcRoot", repo.getRoot());
form.add("srcKind", repo.getKind());
- form.add("srcKey", src.getPath());
+ form.add("srcKey", src.getPath().substring(1));
Credential credential;
credential = Credential.reencrypt(repo.getCredential(), plain.getSecret());
form.add("srcAccount", credential.getAccount());
form.add("srcSecret", credential.getSecret());
}
String destRepoName = dest.getScheme();
if("file".equals(destRepoName)) {
form.add("destRoot", ".");
- form.add("destKey", dest.getPath());
+ form.add("destKey", dest.getPath().substring(1));
form.add("destKind", "File");
} else {
Repository repo = RepositoryResource.dao.load(destRepoName, UserResource.dao.load(this.getOwner()));
form.add("destination", repo.getTarget());
form.add("destRoot", repo.getRoot());
form.add("destKind", repo.getKind());
- form.add("destKey", dest.getPath());
+ form.add("destKey", dest.getPath().substring(1));
Credential credential;
credential = Credential.reencrypt(repo.getCredential(), plain.getSecret());
form.add("destAccount", credential.getAccount());
form.add("destSecret", credential.getSecret());
}
form.add("tag", this.context.getValue("fileTableId"));
form.add("notification", this.getContext().getValue("notification"));
try {
URI location = sendRequest(client, targetVM.getContext().getURIValue("agentURI"), form);
if(location != null) {
this.instance = location.toString();
}
} catch (UnprocessableEntityException e) {
throw e;
} catch (Exception e) {
long now = Calendar.getInstance().getTimeInMillis();
long timeout = Long.valueOf(Resource.get("agentStartupGracePeriodInSeconds", "600"))*1000;
// Give the agent a grace period to respond
if((now - epoch) > timeout) {
logger.error("file copy initiation FAILED with exception "+e.getMessage());
log.log(Level.SEVERE, this.name+" file copy initiation FAILED with exception ", e);
throw new UnprocessableEntityException("file copy initiation FAILED with exception "+e.getMessage());
}
}
} finally {
ClientFactory.give(client);
}
}
@Override
public boolean call() throws Exception {
Client client = ClientFactory.create();
Credential plain = this.clientCredential.decrypt();
client.addFilter(new HTTPBasicAuthFilter(plain.getAccount(), plain.getSecret()));
client.setReadTimeout(30000);
client.setConnectTimeout(5000);
try {
Task t;
try {
t = getTask(client, this.instance);
clientUnresponsive = null;
} catch (ClientHandlerException e) {
if(clientUnresponsive == null) {
clientUnresponsive = Calendar.getInstance().getTimeInMillis();
return false;
} else {
long now = Calendar.getInstance().getTimeInMillis();
long timeout = Long.valueOf(Resource.get("agentStartupGracePeriodInSeconds", "600"))*1000;
// Give the agent a grace period to respond
if((now - clientUnresponsive) > timeout) {
log.log(Level.SEVERE, name+" file copy monitoring "+this.instance+" failed", e);
logger.error("Copy monitoring failed with exception "+e.getMessage());
throw new UnprocessableEntityException("Copy monitoring failed with exception "+e.getMessage());
}
}
return false;
} catch (UniformInterfaceException e) {
if(clientUnresponsive == null) {
clientUnresponsive = Calendar.getInstance().getTimeInMillis();
} else {
long now = Calendar.getInstance().getTimeInMillis();
long timeout = Long.valueOf(Resource.get("agentStartupGracePeriodInSeconds", "600"))*1000;
// Give the agent a grace period to respond
if((now - clientUnresponsive) > timeout) {
log.log(Level.SEVERE, name+" file copy monitoring "+this.instance+" failed", e);
logger.error("Copy monitoring failed with exception "+e.getMessage());
throw new UnprocessableEntityException("Copy monitoring failed with exception "+e.getMessage());
}
}
return false;
}
this.context.putValue("stdout", t.getStdout());
this.context.putValue("stderr", t.getStderr());
if(t.getFinished() != null) {
this.context.putValue("exitCode", Integer.toString(t.getExitcode()));
if(t.getStdout() != null && t.getStdout().length() > 0)
logger.info(t.getStdout());
if(t.getStderr() != null && t.getStderr().length() > 0)
logger.warning(t.getStderr());
if(t.getExitcode() == 0) {
Calendar time = Calendar.getInstance();
Calendar begin = Calendar.getInstance();
time.setTime(t.getFinished());
begin.setTime(t.getStarted());
long interval = time.getTimeInMillis() - begin.getTimeInMillis();
String durationText;
if(interval < 1000) {
durationText = Long.toString(interval)+" milliseconds";
} else {
interval = interval/1000;
durationText = Long.toString(interval)+(interval>1?" seconds":"second");
}
log.fine(this.name+" file copy completed successfully. Elapsed time "+durationText);
logger.info("File copy completed successfully. Elapsed time "+durationText);
if(t.getManifest() != null) {
log.info("File copy manifest length "+t.getManifest().length);
Origin.updateOrigin(this.getProcess(), t.getManifest()); // FIXME should be the On command process. Not sure i agree with this now
}
return true;
} else {
logger.error("File copy "+this.instance+" failed with exit status "+t.getExitcode());
log.severe(name+" file copy "+this.instance+" failed with exit status "+t.getExitcode());
log.severe("Stdout: "+t.getStdout());
log.severe("Stderr: "+t.getStderr());
throw new UnprocessableEntityException("File copy "+this.instance+" failed with exit status "+t.getExitcode());
}
}
return false;
} finally {
ClientFactory.give(client);
}
}
@Override
public void cancel() {
log.warning("Cancel");
}
@Override
public void dump() {
log.warning("Dump");
}
@Override
public void signal(SignalKind kind, String assertion) {
log.warning("Signal "+assertion);
}
/*
* Getters and Setters
*/
/**
* @return the target
*/
public URI getTarget() {
return Helpers.stringToURI(target);
}
/**
* @param target the target to set
*/
public void setTarget(URI target) {
this.target = Helpers.URItoString(target);
}
/**
* @return the instance
*/
public URI getInstance() {
return Helpers.stringToURI(instance);
}
/**
* @param instance the instance to set
*/
public void setInstance(URI instance) {
this.instance = Helpers.URItoString(instance);
}
/**
* @return the epoch
*/
public Long getEpoch() {
return epoch;
}
/**
* @param epoch the epoch to set
*/
public void setEpoch(Long epoch) {
this.epoch = epoch;
}
/**
* @return the clientUnresponsive
*/
public Long getClientUnresponsive() {
return clientUnresponsive;
}
/**
* @param clientUnresponsive the clientUnresponsive to set
*/
public void setClientUnresponsive(Long clientUnresponsive) {
this.clientUnresponsive = clientUnresponsive;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String
.format("OnAction [logger=%s, target=%s, instance=%s, epoch=%s, clientUnresponsive=%s, toString()=%s]",
logger, target, instance, epoch, clientUnresponsive,
super.toString());
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime
* result
+ ((clientCredential == null) ? 0 : clientCredential.hashCode());
result = prime
* result
+ ((clientUnresponsive == null) ? 0 : clientUnresponsive
.hashCode());
result = prime * result + ((epoch == null) ? 0 : epoch.hashCode());
result = prime * result
+ ((instance == null) ? 0 : instance.hashCode());
result = prime * result + ((logger == null) ? 0 : logger.hashCode());
result = prime * result + ((target == null) ? 0 : target.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
FileTransferAction other = (FileTransferAction) obj;
if (clientCredential == null) {
if (other.clientCredential != null)
return false;
} else if (!clientCredential.equals(other.clientCredential))
return false;
if (clientUnresponsive == null) {
if (other.clientUnresponsive != null)
return false;
} else if (!clientUnresponsive.equals(other.clientUnresponsive))
return false;
if (epoch == null) {
if (other.epoch != null)
return false;
} else if (!epoch.equals(other.epoch))
return false;
if (instance == null) {
if (other.instance != null)
return false;
} else if (!instance.equals(other.instance))
return false;
if (logger == null) {
if (other.logger != null)
return false;
} else if (!logger.equals(other.logger))
return false;
if (target == null) {
if (other.target != null)
return false;
} else if (!target.equals(other.target))
return false;
return true;
}
/*
* Unit testing
* ============
*/
protected Task getTask(Client client, String target) {
WebResource resource = client.resource(target);
return resource.get(Task.class);
}
protected URI sendRequest(Client client, URI target, Form form) {
WebResource resource;
resource = client.resource(target);
ClientResponse response = resource.path("xfer").type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form);
URI location = response.getLocation();
if(location != null) {
log.fine(this.name+" file copy epoch. Factory "+location.toString()+" initiating status "+response.getStatus());
logger.info("file copy epoch.");
} else {
log.log(Level.SEVERE, this.name+" file copy initiation FAILED with status "+response.getStatus());
logger.error("file copy initiation FAILED with status "+response.getStatus());
throw new UnprocessableEntityException(this.name+" file copy initiation FAILED with status "+response.getStatus());
}
return location;
}
}
| false | true | public void init() throws Exception {
logger = new ActionLogger(this);
log.info(this.getContext().getValue("arg"));
this.target = this.getContext().getValue("target");
Action vm = ActionResource.dao.load(URI.create(this.target));
VMAction targetVM = null;
if(!(vm instanceof VMAction)) {
logger.error(this.target+" is not a VM. Got "+vm.getClass().getSimpleName());
log.warning(this.target+" is not a VM. Got "+vm.getClass().getSimpleName());
throw new IllegalArgumentException(this.target+" is not a VM. Got "+vm.getClass().getSimpleName());
} else {
targetVM = (VMAction) vm;
}
if(this.clientCredential == null) {
this.clientCredential = new Credential(
targetVM.getContext().getValue("agentUser"),
targetVM.getContext().getValue("agentSecret")).encrypt();
}
Client client = ClientFactory.create();
try {
Credential plain = this.clientCredential.decrypt();
client.addFilter(new HTTPBasicAuthFilter(plain.getAccount(), plain.getSecret()));
client.setReadTimeout(30000);
client.setConnectTimeout(5000);
URI src = this.context.getFileValue("source");
URI dest = this.context.getFileValue("destination");
if(epoch == 0) {
epoch = Calendar.getInstance().getTimeInMillis();
}
Form form = new Form();
String srcRepoName = src.getScheme();
if("file".equals(srcRepoName)) {
form.add("srcRoot", ".");
form.add("srcKey", src.getPath());
form.add("srcKind", "File");
} else {
Repository repo = RepositoryResource.dao.load(srcRepoName, UserResource.dao.load(this.getOwner()));
form.add("source", repo.getTarget());
form.add("srcRoot", repo.getRoot());
form.add("srcKind", repo.getKind());
form.add("srcKey", src.getPath());
Credential credential;
credential = Credential.reencrypt(repo.getCredential(), plain.getSecret());
form.add("srcAccount", credential.getAccount());
form.add("srcSecret", credential.getSecret());
}
String destRepoName = dest.getScheme();
if("file".equals(destRepoName)) {
form.add("destRoot", ".");
form.add("destKey", dest.getPath());
form.add("destKind", "File");
} else {
Repository repo = RepositoryResource.dao.load(destRepoName, UserResource.dao.load(this.getOwner()));
form.add("destination", repo.getTarget());
form.add("destRoot", repo.getRoot());
form.add("destKind", repo.getKind());
form.add("destKey", dest.getPath());
Credential credential;
credential = Credential.reencrypt(repo.getCredential(), plain.getSecret());
form.add("destAccount", credential.getAccount());
form.add("destSecret", credential.getSecret());
}
form.add("tag", this.context.getValue("fileTableId"));
form.add("notification", this.getContext().getValue("notification"));
try {
URI location = sendRequest(client, targetVM.getContext().getURIValue("agentURI"), form);
if(location != null) {
this.instance = location.toString();
}
} catch (UnprocessableEntityException e) {
throw e;
} catch (Exception e) {
long now = Calendar.getInstance().getTimeInMillis();
long timeout = Long.valueOf(Resource.get("agentStartupGracePeriodInSeconds", "600"))*1000;
// Give the agent a grace period to respond
if((now - epoch) > timeout) {
logger.error("file copy initiation FAILED with exception "+e.getMessage());
log.log(Level.SEVERE, this.name+" file copy initiation FAILED with exception ", e);
throw new UnprocessableEntityException("file copy initiation FAILED with exception "+e.getMessage());
}
}
} finally {
ClientFactory.give(client);
}
}
| public void init() throws Exception {
logger = new ActionLogger(this);
log.info(this.getContext().getValue("arg"));
this.target = this.getContext().getValue("target");
Action vm = ActionResource.dao.load(URI.create(this.target));
VMAction targetVM = null;
if(!(vm instanceof VMAction)) {
logger.error(this.target+" is not a VM. Got "+vm.getClass().getSimpleName());
log.warning(this.target+" is not a VM. Got "+vm.getClass().getSimpleName());
throw new IllegalArgumentException(this.target+" is not a VM. Got "+vm.getClass().getSimpleName());
} else {
targetVM = (VMAction) vm;
}
if(this.clientCredential == null) {
this.clientCredential = new Credential(
targetVM.getContext().getValue("agentUser"),
targetVM.getContext().getValue("agentSecret")).encrypt();
}
Client client = ClientFactory.create();
try {
Credential plain = this.clientCredential.decrypt();
client.addFilter(new HTTPBasicAuthFilter(plain.getAccount(), plain.getSecret()));
client.setReadTimeout(30000);
client.setConnectTimeout(5000);
URI src = this.context.getFileValue("source");
URI dest = this.context.getFileValue("destination");
if(epoch == 0) {
epoch = Calendar.getInstance().getTimeInMillis();
}
Form form = new Form();
String srcRepoName = src.getScheme();
if("file".equals(srcRepoName)) {
form.add("srcRoot", ".");
form.add("srcKey", src.getPath().substring(1));
form.add("srcKind", "File");
} else {
Repository repo = RepositoryResource.dao.load(srcRepoName, UserResource.dao.load(this.getOwner()));
form.add("source", repo.getTarget());
form.add("srcRoot", repo.getRoot());
form.add("srcKind", repo.getKind());
form.add("srcKey", src.getPath().substring(1));
Credential credential;
credential = Credential.reencrypt(repo.getCredential(), plain.getSecret());
form.add("srcAccount", credential.getAccount());
form.add("srcSecret", credential.getSecret());
}
String destRepoName = dest.getScheme();
if("file".equals(destRepoName)) {
form.add("destRoot", ".");
form.add("destKey", dest.getPath().substring(1));
form.add("destKind", "File");
} else {
Repository repo = RepositoryResource.dao.load(destRepoName, UserResource.dao.load(this.getOwner()));
form.add("destination", repo.getTarget());
form.add("destRoot", repo.getRoot());
form.add("destKind", repo.getKind());
form.add("destKey", dest.getPath().substring(1));
Credential credential;
credential = Credential.reencrypt(repo.getCredential(), plain.getSecret());
form.add("destAccount", credential.getAccount());
form.add("destSecret", credential.getSecret());
}
form.add("tag", this.context.getValue("fileTableId"));
form.add("notification", this.getContext().getValue("notification"));
try {
URI location = sendRequest(client, targetVM.getContext().getURIValue("agentURI"), form);
if(location != null) {
this.instance = location.toString();
}
} catch (UnprocessableEntityException e) {
throw e;
} catch (Exception e) {
long now = Calendar.getInstance().getTimeInMillis();
long timeout = Long.valueOf(Resource.get("agentStartupGracePeriodInSeconds", "600"))*1000;
// Give the agent a grace period to respond
if((now - epoch) > timeout) {
logger.error("file copy initiation FAILED with exception "+e.getMessage());
log.log(Level.SEVERE, this.name+" file copy initiation FAILED with exception ", e);
throw new UnprocessableEntityException("file copy initiation FAILED with exception "+e.getMessage());
}
}
} finally {
ClientFactory.give(client);
}
}
|
diff --git a/src/no/runsafe/creativetoolbox/PlotList.java b/src/no/runsafe/creativetoolbox/PlotList.java
index 77cb7e4..b841a91 100644
--- a/src/no/runsafe/creativetoolbox/PlotList.java
+++ b/src/no/runsafe/creativetoolbox/PlotList.java
@@ -1,78 +1,81 @@
package no.runsafe.creativetoolbox;
import com.google.common.collect.Lists;
import no.runsafe.framework.api.player.IPlayer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class PlotList
{
public void set(IPlayer player, List<String> list)
{
lists.put(player.getName(), list);
}
public int current(IPlayer player)
{
return lists.get(player.getName()).indexOf(pointer.get(player.getName())) + 1;
}
public void wind(IPlayer player, String to)
{
pointer.put(player.getName(), to);
}
public int count(IPlayer player)
{
return lists.get(player.getName()).size();
}
public void remove(String plot)
{
for (Map.Entry<String, List<String>> list : lists.entrySet())
{
if (list.getValue().contains(plot))
{
ArrayList<String> plots = Lists.newArrayList(list.getValue());
int i = plots.indexOf(plot);
plots.remove(plot);
lists.put(list.getKey(), plots);
- pointer.put(list.getKey(), plots.get(i));
+ if (plots.size() > i)
+ pointer.put(list.getKey(), plots.get(i));
+ else
+ pointer.put(list.getKey(), plots.get(0));
}
}
}
public String previous(IPlayer player)
{
if (lists.containsKey(player.getName()))
{
List<String> list = lists.get(player.getName());
if (list == null || list.isEmpty())
return null;
int i = list.indexOf(pointer.get(player.getName()));
pointer.put(player.getName(), list.get(i > 0 ? i - 1 : list.size() - 1));
return pointer.get(player.getName());
}
return null;
}
public String next(IPlayer player)
{
if (lists.containsKey(player.getName()))
{
List<String> list = lists.get(player.getName());
if (list == null || list.isEmpty())
return null;
int i = list.indexOf(pointer.get(player.getName()));
pointer.put(player.getName(), list.get(i + 1 >= list.size() ? 0 : i + 1));
return pointer.get(player.getName());
}
return null;
}
private final ConcurrentHashMap<String, String> pointer = new ConcurrentHashMap<String, String>();
private final ConcurrentHashMap<String, List<String>> lists = new ConcurrentHashMap<String, List<String>>();
}
| true | true | public void remove(String plot)
{
for (Map.Entry<String, List<String>> list : lists.entrySet())
{
if (list.getValue().contains(plot))
{
ArrayList<String> plots = Lists.newArrayList(list.getValue());
int i = plots.indexOf(plot);
plots.remove(plot);
lists.put(list.getKey(), plots);
pointer.put(list.getKey(), plots.get(i));
}
}
}
| public void remove(String plot)
{
for (Map.Entry<String, List<String>> list : lists.entrySet())
{
if (list.getValue().contains(plot))
{
ArrayList<String> plots = Lists.newArrayList(list.getValue());
int i = plots.indexOf(plot);
plots.remove(plot);
lists.put(list.getKey(), plots);
if (plots.size() > i)
pointer.put(list.getKey(), plots.get(i));
else
pointer.put(list.getKey(), plots.get(0));
}
}
}
|
diff --git a/com/buglabs/bug/base/BUGBaseControl.java b/com/buglabs/bug/base/BUGBaseControl.java
index 36bbfb1..fbca71e 100644
--- a/com/buglabs/bug/base/BUGBaseControl.java
+++ b/com/buglabs/bug/base/BUGBaseControl.java
@@ -1,130 +1,130 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Bug Labs, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of Bug Labs, Inc. nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
package com.buglabs.bug.base;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import com.buglabs.bug.base.pub.IBUG20BaseControl;
/**
* Impl of IBUG20BaseControl that uses sysfs file API to controle BUGbase LEDs.
* @author kgilmer
*
*/
public class BUGBaseControl implements IBUG20BaseControl {
/*
* LEDs in sysfs look like this:
* omap3bug:blue:battery omap3bug:blue:wlan omap3bug:red:battery
* omap3bug:blue:bt omap3bug:green:battery omap3bug:red:wlan
* omap3bug:blue:power omap3bug:green:wlan
*/
private static final String LED_ROOT = "/sys/class/leds/";
private static final String BRIGHTNESS = "/brightness";
private static final String BATTERY_BLUE_CONTROL_FILE = LED_ROOT + "omap3bug:blue:battery" + BRIGHTNESS;
private static final String BATTERY_RED_CONTROL_FILE = LED_ROOT + "omap3bug:red:battery" + BRIGHTNESS;
private static final String BATTERY_GREEN_CONTROL_FILE = LED_ROOT + "omap3bug:green:battery" + BRIGHTNESS;
private static final String POWER_BLUE_CONTROL_FILE = LED_ROOT + "omap3bug:blue:power" + BRIGHTNESS;
private static final String WLAN_GREEN_CONTROL_FILE = LED_ROOT + "omap3bug:green:wlan" + BRIGHTNESS;
private static final String WLAN_RED_CONTROL_FILE = LED_ROOT + "omap3bug:red:wlan" + BRIGHTNESS;
private static final String WLAN_BLUE_CONTROL_FILE = LED_ROOT + "omap3bug:blue:wlan" + BRIGHTNESS;
private static final String BT_BLUE_CONTROL_FILE = LED_ROOT + "omap3bug:blue:bt" + BRIGHTNESS;
private OutputStream batteryFH[];
private OutputStream powerFH[];
private FileOutputStream wlanFH[];
private FileOutputStream btFH[];
public BUGBaseControl() throws FileNotFoundException {
batteryFH = new FileOutputStream[3];
batteryFH[COLOR_BLUE] = new FileOutputStream(BATTERY_BLUE_CONTROL_FILE);
batteryFH[COLOR_RED] = new FileOutputStream(BATTERY_RED_CONTROL_FILE);
batteryFH[COLOR_GREEN] = new FileOutputStream(BATTERY_GREEN_CONTROL_FILE);
powerFH = new FileOutputStream[1];
powerFH[COLOR_BLUE] = new FileOutputStream(POWER_BLUE_CONTROL_FILE);
wlanFH = new FileOutputStream[3];
wlanFH[COLOR_BLUE] = new FileOutputStream(WLAN_BLUE_CONTROL_FILE);
wlanFH[COLOR_RED] = new FileOutputStream(WLAN_RED_CONTROL_FILE);
wlanFH[COLOR_GREEN] = new FileOutputStream(WLAN_GREEN_CONTROL_FILE);
- btFH = new FileOutputStream[0];
+ btFH = new FileOutputStream[1];
btFH[COLOR_BLUE] = new FileOutputStream(BT_BLUE_CONTROL_FILE);
}
public void setLEDBrightness(int led, int brightness) throws IOException {
if (brightness > 255 || led > 3) {
throw new IOException("Invalid LED or brightness parameter value.");
}
OutputStream [] os = getOutputStream(led);
if (os.length > 1) {
throw new IOException("LED " + led + " does not support brightness");
}
writeBrightness(os[0], brightness);
}
public void setLEDColor(int led, int color, boolean on) throws IOException {
if (color < 0 || color > 3) {
throw new IOException("Color " + color + " is not valid.");
}
OutputStream [] os = getOutputStream(led);
if (os.length != 3) {
throw new IOException("LED " + led + " does not allow color to be set.");
}
writeBrightness(os[color], on ? 1 : 0);
}
private void writeBrightness(OutputStream outputStream, int i) throws IOException {
outputStream.write(("" + i).getBytes());
outputStream.flush();
}
private OutputStream[] getOutputStream(int index) throws IOException {
switch (index) {
case 0:
return batteryFH;
case 1:
return powerFH;
case 2:
return wlanFH;
case 3:
return btFH;
default:
throw new IOException("LED index out of bounds: " + index);
}
}
}
| true | true | public BUGBaseControl() throws FileNotFoundException {
batteryFH = new FileOutputStream[3];
batteryFH[COLOR_BLUE] = new FileOutputStream(BATTERY_BLUE_CONTROL_FILE);
batteryFH[COLOR_RED] = new FileOutputStream(BATTERY_RED_CONTROL_FILE);
batteryFH[COLOR_GREEN] = new FileOutputStream(BATTERY_GREEN_CONTROL_FILE);
powerFH = new FileOutputStream[1];
powerFH[COLOR_BLUE] = new FileOutputStream(POWER_BLUE_CONTROL_FILE);
wlanFH = new FileOutputStream[3];
wlanFH[COLOR_BLUE] = new FileOutputStream(WLAN_BLUE_CONTROL_FILE);
wlanFH[COLOR_RED] = new FileOutputStream(WLAN_RED_CONTROL_FILE);
wlanFH[COLOR_GREEN] = new FileOutputStream(WLAN_GREEN_CONTROL_FILE);
btFH = new FileOutputStream[0];
btFH[COLOR_BLUE] = new FileOutputStream(BT_BLUE_CONTROL_FILE);
}
| public BUGBaseControl() throws FileNotFoundException {
batteryFH = new FileOutputStream[3];
batteryFH[COLOR_BLUE] = new FileOutputStream(BATTERY_BLUE_CONTROL_FILE);
batteryFH[COLOR_RED] = new FileOutputStream(BATTERY_RED_CONTROL_FILE);
batteryFH[COLOR_GREEN] = new FileOutputStream(BATTERY_GREEN_CONTROL_FILE);
powerFH = new FileOutputStream[1];
powerFH[COLOR_BLUE] = new FileOutputStream(POWER_BLUE_CONTROL_FILE);
wlanFH = new FileOutputStream[3];
wlanFH[COLOR_BLUE] = new FileOutputStream(WLAN_BLUE_CONTROL_FILE);
wlanFH[COLOR_RED] = new FileOutputStream(WLAN_RED_CONTROL_FILE);
wlanFH[COLOR_GREEN] = new FileOutputStream(WLAN_GREEN_CONTROL_FILE);
btFH = new FileOutputStream[1];
btFH[COLOR_BLUE] = new FileOutputStream(BT_BLUE_CONTROL_FILE);
}
|
diff --git a/src/planets/src/se/exuvo/planets/systems/VelocitySystem.java b/src/planets/src/se/exuvo/planets/systems/VelocitySystem.java
index e91c92c..6c4e351 100644
--- a/src/planets/src/se/exuvo/planets/systems/VelocitySystem.java
+++ b/src/planets/src/se/exuvo/planets/systems/VelocitySystem.java
@@ -1,56 +1,56 @@
package se.exuvo.planets.systems;
import se.exuvo.planets.components.Position;
import se.exuvo.planets.components.Velocity;
import se.exuvo.settings.Settings;
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Mapper;
import com.artemis.systems.IntervalEntityProcessingSystem;
import com.badlogic.gdx.Gdx;
public class VelocitySystem extends IntervalEntityProcessingSystem {
@Mapper ComponentMapper<Velocity> vm;
@Mapper ComponentMapper<Position> pm;
private float maxX, maxY, minX, minY;
private boolean paused;
public VelocitySystem() {
super(Aspect.getAspectForAll(Velocity.class, Position.class), Settings.getFloat("PhysicsStep"));
maxX = Gdx.graphics.getWidth()/2;
maxY = Gdx.graphics.getHeight()/2;
minX = -maxX;
minY = -maxY;
}
@Override
protected void process(Entity e) {
Position p = pm.get(e);
Velocity v = vm.get(e);
// apply speed to position
p.vec.add(v.vec);
if(p.vec.x < minX) p.vec.x = minX;
if(p.vec.y < minY) p.vec.y = minY;
if(p.vec.x > maxX) p.vec.x = maxX;
- if(p.vec.y > maxY) p.vec.x = maxY;
+ if(p.vec.y > maxY) p.vec.y = maxY;
}
@Override
protected boolean checkProcessing() {
if(paused){
return false;
}else{
return super.checkProcessing();
}
}
public void setPaused(boolean newState){
paused = newState;
}
}
| true | true | protected void process(Entity e) {
Position p = pm.get(e);
Velocity v = vm.get(e);
// apply speed to position
p.vec.add(v.vec);
if(p.vec.x < minX) p.vec.x = minX;
if(p.vec.y < minY) p.vec.y = minY;
if(p.vec.x > maxX) p.vec.x = maxX;
if(p.vec.y > maxY) p.vec.x = maxY;
}
| protected void process(Entity e) {
Position p = pm.get(e);
Velocity v = vm.get(e);
// apply speed to position
p.vec.add(v.vec);
if(p.vec.x < minX) p.vec.x = minX;
if(p.vec.y < minY) p.vec.y = minY;
if(p.vec.x > maxX) p.vec.x = maxX;
if(p.vec.y > maxY) p.vec.y = maxY;
}
|
diff --git a/src/main/java/net/cubespace/RegionShop/Data/Tasks/PriceRecalculateTask.java b/src/main/java/net/cubespace/RegionShop/Data/Tasks/PriceRecalculateTask.java
index 1c94779..209aa1e 100644
--- a/src/main/java/net/cubespace/RegionShop/Data/Tasks/PriceRecalculateTask.java
+++ b/src/main/java/net/cubespace/RegionShop/Data/Tasks/PriceRecalculateTask.java
@@ -1,235 +1,235 @@
package net.cubespace.RegionShop.Data.Tasks;
import net.cubespace.RegionShop.Bukkit.Plugin;
import net.cubespace.RegionShop.Config.ConfigManager;
import net.cubespace.RegionShop.Config.Files.Sub.Item;
import net.cubespace.RegionShop.Config.Files.Sub.ServerShop;
import net.cubespace.RegionShop.Database.Database;
import net.cubespace.RegionShop.Database.Repository.ItemRepository;
import net.cubespace.RegionShop.Database.Table.CustomerSign;
import net.cubespace.RegionShop.Database.Table.ItemMeta;
import net.cubespace.RegionShop.Database.Table.ItemStorage;
import net.cubespace.RegionShop.Database.Table.Items;
import net.cubespace.RegionShop.Database.Table.Region;
import net.cubespace.RegionShop.Util.ItemName;
import net.cubespace.RegionShop.Util.Logger;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class PriceRecalculateTask extends BukkitRunnable {
private HashMap<Integer, HashMap<String, ArrayList<Integer>>> recalcCache = new HashMap<Integer, HashMap<String, ArrayList<Integer>>>();
private List<Item> items = new ArrayList<Item>();
public PriceRecalculateTask(List<Item> items) {
this.items = items;
}
private void prepareCache(Integer id) {
if (!recalcCache.containsKey(id)) {
HashMap<String, ArrayList<Integer>> newArrayList = new HashMap<String, ArrayList<Integer>>();
newArrayList.put("buy", new ArrayList<Integer>());
newArrayList.put("sell", new ArrayList<Integer>());
for (Integer i = 0; i < 720; i++) {
newArrayList.get("buy").add(0);
newArrayList.get("sell").add(0);
}
recalcCache.put(id, newArrayList);
}
}
private void addToCache(Integer id, Integer buy, Integer sell) {
if (recalcCache.containsKey(id)) {
HashMap<String, ArrayList<Integer>> newArrayList = recalcCache.get(id);
if (newArrayList.get("buy").size() > 720) {
newArrayList.get("buy").remove(0);
}
if (newArrayList.get("sell").size() > 720) {
newArrayList.get("sell").remove(0);
}
newArrayList.get("sell").add(sell);
newArrayList.get("buy").add(buy);
}
}
private Integer getAverage(Integer id, String key) {
if (recalcCache.containsKey(id)) {
Integer amount = 0;
ArrayList<Integer> newArrayList = recalcCache.get(id).get(key);
for (Integer curAmount : newArrayList) {
amount += curAmount;
}
return Math.round(amount / 720);
}
return 0;
}
@Override
public void run() {
int lastItemStorageId = 0;
for (Item item : items) {
Items itemInShop = null;
try {
itemInShop = Database.getDAO(Items.class).queryForId(item.databaseID);
} catch (SQLException e) {
Logger.error("Could not get Item", e);
}
if (itemInShop == null) {
Logger.info("No item found to update");
continue;
}
Logger.debug("Item recalc for Item: " + itemInShop.getMeta().getId() + ":" + itemInShop.getMeta().getDataValue());
prepareCache(itemInShop.getId());
- Integer sold = (itemInShop.getSold()) * 720;
- Integer bought = (itemInShop.getBought()) * 720;
+ Integer sold = (itemInShop.getSold());
+ Integer bought = (itemInShop.getBought());
addToCache(itemInShop.getId(), bought, sold);
sold = getAverage(itemInShop.getId(), "sell");
bought = getAverage(itemInShop.getId(), "buy");
Logger.debug("Item Recalc: " + bought + " / " + sold);
Float sellPriceDiff = (float) sold / item.maxItemRecalc;
Float buyPriceDiff;
if (bought > 0) {
buyPriceDiff = (float) bought / item.maxItemRecalc;
} else {
buyPriceDiff = 2.0F;
}
if (sellPriceDiff > 1.0) {
//Preis geht rauf
if (sellPriceDiff > item.limitSellPriceFactor) {
sellPriceDiff = item.limitSellPriceFactor;
}
} else {
//Preis geht runter
if (sellPriceDiff < item.limitSellPriceUnderFactor) {
sellPriceDiff = item.limitSellPriceUnderFactor;
}
}
if (buyPriceDiff > 1.0) {
//Abgabe geht rauf
buyPriceDiff = buyPriceDiff * item.limitBuyPriceFactor;
if(buyPriceDiff > item.limitBuyPriceFactor) {
buyPriceDiff = item.limitBuyPriceFactor;
}
} else {
//Abgabe geht runter
if (buyPriceDiff < item.limitBuyPriceUnderFactor) {
buyPriceDiff = item.limitBuyPriceUnderFactor;
}
}
Logger.debug("Diffs: " + buyPriceDiff + " / " + sellPriceDiff);
Float newSellPrice = Math.round(item.sell * sellPriceDiff * 100) / 100.0F;
Float newBuyPrice = Math.round(item.buy * buyPriceDiff * 100) / 100.0F;
itemInShop.setBuy(newBuyPrice);
itemInShop.setSell(newSellPrice);
itemInShop.setCurrentAmount(99999);
itemInShop.setBought(0);
itemInShop.setSold(0);
Logger.debug("New Price: " + newBuyPrice + " / " + newSellPrice);
try {
Database.getDAO(Items.class).update(itemInShop);
} catch (SQLException e) {
Logger.error("Could not update Item", e);
}
//Check if Item has a Sign
CustomerSign customerSign = null;
try {
customerSign = Database.getDAO(CustomerSign.class).queryBuilder().
where().
eq("item_id", itemInShop.getId()).
queryForFirst();
} catch (SQLException e) {
Logger.error("Could not get Customer Sign", e);
}
final Items items = itemInShop;
if (customerSign != null) {
final CustomerSign syncCustomerSign = customerSign;
Plugin.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(Plugin.getInstance(), new Runnable() {
@Override
public void run() {
Block block = Plugin.getInstance().getServer().getWorld(syncCustomerSign.getRegion().getWorld()).getBlockAt(syncCustomerSign.getX(), syncCustomerSign.getY(), syncCustomerSign.getZ());
if (block.getType().equals(Material.SIGN_POST) || block.getType().equals(Material.WALL_SIGN)) {
Sign sign = (Sign) block.getState();
//Get the nice name
ItemStack itemStack = ItemRepository.fromDBItem(items);
String dataName = ItemName.getDataName(itemStack);
String niceItemName;
if (dataName.endsWith(" ")) {
niceItemName = dataName + ItemName.nicer(itemStack.getType().toString());
} else if (!dataName.equals("")) {
niceItemName = dataName;
} else {
niceItemName = ItemName.nicer(itemStack.getType().toString());
}
if (itemStack.getItemMeta().hasDisplayName()) {
niceItemName = "(" + itemStack.getItemMeta().getDisplayName() + ")";
}
for (Integer line = 0; line < 4; line++) {
sign.setLine(line, ConfigManager.language.Sign_Customer_SignText.get(line).
replace("%id", items.getId().toString()).
replace("%itemname", ItemName.nicer(niceItemName)).
replace("%amount", items.getUnitAmount().toString()).
replace("%sell", items.getSell().toString()).
replace("%buy", items.getBuy().toString()));
}
sign.update();
}
}
});
}
if (lastItemStorageId != itemInShop.getItemStorage().getId()) {
//Reset the ItemStorage to avoid "Shop is full you cant sell"
try {
itemInShop.getItemStorage().setItemAmount(0);
Database.getDAO(ItemStorage.class).update(itemInShop.getItemStorage());
} catch (SQLException e) {
Logger.error("Could not reset ItemStorage", e);
}
lastItemStorageId = itemInShop.getItemStorage().getId();
}
}
}
}
| true | true | public void run() {
int lastItemStorageId = 0;
for (Item item : items) {
Items itemInShop = null;
try {
itemInShop = Database.getDAO(Items.class).queryForId(item.databaseID);
} catch (SQLException e) {
Logger.error("Could not get Item", e);
}
if (itemInShop == null) {
Logger.info("No item found to update");
continue;
}
Logger.debug("Item recalc for Item: " + itemInShop.getMeta().getId() + ":" + itemInShop.getMeta().getDataValue());
prepareCache(itemInShop.getId());
Integer sold = (itemInShop.getSold()) * 720;
Integer bought = (itemInShop.getBought()) * 720;
addToCache(itemInShop.getId(), bought, sold);
sold = getAverage(itemInShop.getId(), "sell");
bought = getAverage(itemInShop.getId(), "buy");
Logger.debug("Item Recalc: " + bought + " / " + sold);
Float sellPriceDiff = (float) sold / item.maxItemRecalc;
Float buyPriceDiff;
if (bought > 0) {
buyPriceDiff = (float) bought / item.maxItemRecalc;
} else {
buyPriceDiff = 2.0F;
}
if (sellPriceDiff > 1.0) {
//Preis geht rauf
if (sellPriceDiff > item.limitSellPriceFactor) {
sellPriceDiff = item.limitSellPriceFactor;
}
} else {
//Preis geht runter
if (sellPriceDiff < item.limitSellPriceUnderFactor) {
sellPriceDiff = item.limitSellPriceUnderFactor;
}
}
if (buyPriceDiff > 1.0) {
//Abgabe geht rauf
buyPriceDiff = buyPriceDiff * item.limitBuyPriceFactor;
if(buyPriceDiff > item.limitBuyPriceFactor) {
buyPriceDiff = item.limitBuyPriceFactor;
}
} else {
//Abgabe geht runter
if (buyPriceDiff < item.limitBuyPriceUnderFactor) {
buyPriceDiff = item.limitBuyPriceUnderFactor;
}
}
Logger.debug("Diffs: " + buyPriceDiff + " / " + sellPriceDiff);
Float newSellPrice = Math.round(item.sell * sellPriceDiff * 100) / 100.0F;
Float newBuyPrice = Math.round(item.buy * buyPriceDiff * 100) / 100.0F;
itemInShop.setBuy(newBuyPrice);
itemInShop.setSell(newSellPrice);
itemInShop.setCurrentAmount(99999);
itemInShop.setBought(0);
itemInShop.setSold(0);
Logger.debug("New Price: " + newBuyPrice + " / " + newSellPrice);
try {
Database.getDAO(Items.class).update(itemInShop);
} catch (SQLException e) {
Logger.error("Could not update Item", e);
}
//Check if Item has a Sign
CustomerSign customerSign = null;
try {
customerSign = Database.getDAO(CustomerSign.class).queryBuilder().
where().
eq("item_id", itemInShop.getId()).
queryForFirst();
} catch (SQLException e) {
Logger.error("Could not get Customer Sign", e);
}
final Items items = itemInShop;
if (customerSign != null) {
final CustomerSign syncCustomerSign = customerSign;
Plugin.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(Plugin.getInstance(), new Runnable() {
@Override
public void run() {
Block block = Plugin.getInstance().getServer().getWorld(syncCustomerSign.getRegion().getWorld()).getBlockAt(syncCustomerSign.getX(), syncCustomerSign.getY(), syncCustomerSign.getZ());
if (block.getType().equals(Material.SIGN_POST) || block.getType().equals(Material.WALL_SIGN)) {
Sign sign = (Sign) block.getState();
//Get the nice name
ItemStack itemStack = ItemRepository.fromDBItem(items);
String dataName = ItemName.getDataName(itemStack);
String niceItemName;
if (dataName.endsWith(" ")) {
niceItemName = dataName + ItemName.nicer(itemStack.getType().toString());
} else if (!dataName.equals("")) {
niceItemName = dataName;
} else {
niceItemName = ItemName.nicer(itemStack.getType().toString());
}
if (itemStack.getItemMeta().hasDisplayName()) {
niceItemName = "(" + itemStack.getItemMeta().getDisplayName() + ")";
}
for (Integer line = 0; line < 4; line++) {
sign.setLine(line, ConfigManager.language.Sign_Customer_SignText.get(line).
replace("%id", items.getId().toString()).
replace("%itemname", ItemName.nicer(niceItemName)).
replace("%amount", items.getUnitAmount().toString()).
replace("%sell", items.getSell().toString()).
replace("%buy", items.getBuy().toString()));
}
sign.update();
}
}
});
}
if (lastItemStorageId != itemInShop.getItemStorage().getId()) {
//Reset the ItemStorage to avoid "Shop is full you cant sell"
try {
itemInShop.getItemStorage().setItemAmount(0);
Database.getDAO(ItemStorage.class).update(itemInShop.getItemStorage());
} catch (SQLException e) {
Logger.error("Could not reset ItemStorage", e);
}
lastItemStorageId = itemInShop.getItemStorage().getId();
}
}
}
| public void run() {
int lastItemStorageId = 0;
for (Item item : items) {
Items itemInShop = null;
try {
itemInShop = Database.getDAO(Items.class).queryForId(item.databaseID);
} catch (SQLException e) {
Logger.error("Could not get Item", e);
}
if (itemInShop == null) {
Logger.info("No item found to update");
continue;
}
Logger.debug("Item recalc for Item: " + itemInShop.getMeta().getId() + ":" + itemInShop.getMeta().getDataValue());
prepareCache(itemInShop.getId());
Integer sold = (itemInShop.getSold());
Integer bought = (itemInShop.getBought());
addToCache(itemInShop.getId(), bought, sold);
sold = getAverage(itemInShop.getId(), "sell");
bought = getAverage(itemInShop.getId(), "buy");
Logger.debug("Item Recalc: " + bought + " / " + sold);
Float sellPriceDiff = (float) sold / item.maxItemRecalc;
Float buyPriceDiff;
if (bought > 0) {
buyPriceDiff = (float) bought / item.maxItemRecalc;
} else {
buyPriceDiff = 2.0F;
}
if (sellPriceDiff > 1.0) {
//Preis geht rauf
if (sellPriceDiff > item.limitSellPriceFactor) {
sellPriceDiff = item.limitSellPriceFactor;
}
} else {
//Preis geht runter
if (sellPriceDiff < item.limitSellPriceUnderFactor) {
sellPriceDiff = item.limitSellPriceUnderFactor;
}
}
if (buyPriceDiff > 1.0) {
//Abgabe geht rauf
buyPriceDiff = buyPriceDiff * item.limitBuyPriceFactor;
if(buyPriceDiff > item.limitBuyPriceFactor) {
buyPriceDiff = item.limitBuyPriceFactor;
}
} else {
//Abgabe geht runter
if (buyPriceDiff < item.limitBuyPriceUnderFactor) {
buyPriceDiff = item.limitBuyPriceUnderFactor;
}
}
Logger.debug("Diffs: " + buyPriceDiff + " / " + sellPriceDiff);
Float newSellPrice = Math.round(item.sell * sellPriceDiff * 100) / 100.0F;
Float newBuyPrice = Math.round(item.buy * buyPriceDiff * 100) / 100.0F;
itemInShop.setBuy(newBuyPrice);
itemInShop.setSell(newSellPrice);
itemInShop.setCurrentAmount(99999);
itemInShop.setBought(0);
itemInShop.setSold(0);
Logger.debug("New Price: " + newBuyPrice + " / " + newSellPrice);
try {
Database.getDAO(Items.class).update(itemInShop);
} catch (SQLException e) {
Logger.error("Could not update Item", e);
}
//Check if Item has a Sign
CustomerSign customerSign = null;
try {
customerSign = Database.getDAO(CustomerSign.class).queryBuilder().
where().
eq("item_id", itemInShop.getId()).
queryForFirst();
} catch (SQLException e) {
Logger.error("Could not get Customer Sign", e);
}
final Items items = itemInShop;
if (customerSign != null) {
final CustomerSign syncCustomerSign = customerSign;
Plugin.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(Plugin.getInstance(), new Runnable() {
@Override
public void run() {
Block block = Plugin.getInstance().getServer().getWorld(syncCustomerSign.getRegion().getWorld()).getBlockAt(syncCustomerSign.getX(), syncCustomerSign.getY(), syncCustomerSign.getZ());
if (block.getType().equals(Material.SIGN_POST) || block.getType().equals(Material.WALL_SIGN)) {
Sign sign = (Sign) block.getState();
//Get the nice name
ItemStack itemStack = ItemRepository.fromDBItem(items);
String dataName = ItemName.getDataName(itemStack);
String niceItemName;
if (dataName.endsWith(" ")) {
niceItemName = dataName + ItemName.nicer(itemStack.getType().toString());
} else if (!dataName.equals("")) {
niceItemName = dataName;
} else {
niceItemName = ItemName.nicer(itemStack.getType().toString());
}
if (itemStack.getItemMeta().hasDisplayName()) {
niceItemName = "(" + itemStack.getItemMeta().getDisplayName() + ")";
}
for (Integer line = 0; line < 4; line++) {
sign.setLine(line, ConfigManager.language.Sign_Customer_SignText.get(line).
replace("%id", items.getId().toString()).
replace("%itemname", ItemName.nicer(niceItemName)).
replace("%amount", items.getUnitAmount().toString()).
replace("%sell", items.getSell().toString()).
replace("%buy", items.getBuy().toString()));
}
sign.update();
}
}
});
}
if (lastItemStorageId != itemInShop.getItemStorage().getId()) {
//Reset the ItemStorage to avoid "Shop is full you cant sell"
try {
itemInShop.getItemStorage().setItemAmount(0);
Database.getDAO(ItemStorage.class).update(itemInShop.getItemStorage());
} catch (SQLException e) {
Logger.error("Could not reset ItemStorage", e);
}
lastItemStorageId = itemInShop.getItemStorage().getId();
}
}
}
|
diff --git a/test/com/xtremelabs/robolectric/RobolectricTest.java b/test/com/xtremelabs/robolectric/RobolectricTest.java
index 216bf2bc..a1b284e1 100644
--- a/test/com/xtremelabs/robolectric/RobolectricTest.java
+++ b/test/com/xtremelabs/robolectric/RobolectricTest.java
@@ -1,93 +1,93 @@
package com.xtremelabs.robolectric;
import android.content.Context;
import android.view.View;
import com.xtremelabs.robolectric.util.Implementation;
import com.xtremelabs.robolectric.util.Implements;
import com.xtremelabs.robolectric.util.TestOnClickListener;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@RunWith(WithTestDefaultsRunner.class)
public class RobolectricTest {
private PrintStream originalSystemOut;
private ByteArrayOutputStream buff;
@Before
public void setUp() {
originalSystemOut = System.out;
buff = new ByteArrayOutputStream();
PrintStream testOut = new PrintStream(buff);
System.setOut(testOut);
}
@After
public void tearDown() {
System.setOut(originalSystemOut);
}
@Test
public void shouldLogMissingInvokedShadowMethodsWhenRequested() throws Exception {
Robolectric.bindShadowClass(View.class, TestShadowView.class);
Robolectric.logMissingInvokedShadowMethods();
View aView = new View(null);
// There's a shadow method for this
aView.getContext();
String output = buff.toString();
assertEquals("", output);
aView.findViewById(27);
// No shadow here... should be logged
output = buff.toString();
- assertEquals("No Shadow method found for View.findViewById(int)\n", output);
+ assertEquals("No Shadow method found for View.findViewById(int)" + System.getProperty("line.separator"), output);
}
@Test // This is nasty because it depends on the test above having run first in order to fail
public void shouldNotLogMissingInvokedShadowMethodsByDefault() throws Exception {
Robolectric.bindShadowClass(View.class, ShadowWranglerTest.TestShadowView.class);
View aView = new View(null);
aView.findViewById(27);
String output = buff.toString();
assertEquals("", output);
}
@Test(expected= RuntimeException.class)
public void clickOn_shouldThrowIfViewIsDisabled() throws Exception {
View view = new View(null);
view.setEnabled(false);
Robolectric.clickOn(view);
}
public void clickOn_shouldCallClickListener() throws Exception {
View view = new View(null);
TestOnClickListener testOnClickListener = new TestOnClickListener();
view.setOnClickListener(testOnClickListener);
Robolectric.clickOn(view);
assertTrue(testOnClickListener.clicked);
}
@Implements(View.class)
public static class TestShadowView extends ShadowWranglerTest.TestShadowViewParent {
@SuppressWarnings({"UnusedDeclaration"})
@Implementation
public Context getContext() {
return null;
}
}
}
| true | true | public void shouldLogMissingInvokedShadowMethodsWhenRequested() throws Exception {
Robolectric.bindShadowClass(View.class, TestShadowView.class);
Robolectric.logMissingInvokedShadowMethods();
View aView = new View(null);
// There's a shadow method for this
aView.getContext();
String output = buff.toString();
assertEquals("", output);
aView.findViewById(27);
// No shadow here... should be logged
output = buff.toString();
assertEquals("No Shadow method found for View.findViewById(int)\n", output);
}
| public void shouldLogMissingInvokedShadowMethodsWhenRequested() throws Exception {
Robolectric.bindShadowClass(View.class, TestShadowView.class);
Robolectric.logMissingInvokedShadowMethods();
View aView = new View(null);
// There's a shadow method for this
aView.getContext();
String output = buff.toString();
assertEquals("", output);
aView.findViewById(27);
// No shadow here... should be logged
output = buff.toString();
assertEquals("No Shadow method found for View.findViewById(int)" + System.getProperty("line.separator"), output);
}
|
diff --git a/core/java/com/android/internal/widget/RotarySelector.java b/core/java/com/android/internal/widget/RotarySelector.java
index 6fabba38..a080d1f7 100644
--- a/core/java/com/android/internal/widget/RotarySelector.java
+++ b/core/java/com/android/internal/widget/RotarySelector.java
@@ -1,968 +1,968 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.widget;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;
import android.view.animation.DecelerateInterpolator;
import static android.view.animation.AnimationUtils.currentAnimationTimeMillis;
import com.android.internal.R;
/**
* Custom view that presents up to two items that are selectable by rotating a semi-circle from
* left to right, or right to left. Used by incoming call screen, and the lock screen when no
* security pattern is set.
*/
public class RotarySelector extends View {
public static final int HORIZONTAL = 0;
public static final int VERTICAL = 1;
private static final String LOG_TAG = "RotarySelector";
private static final boolean DBG = false;
private static final boolean VISUAL_DEBUG = false;
// Listener for onDialTrigger() callbacks.
private OnDialTriggerListener mOnDialTriggerListener;
private float mDensity;
// UI elements
private Bitmap mBackground;
private Bitmap mDimple;
private Bitmap mDimpleDim;
private Bitmap mLeftHandleIcon;
private Bitmap mRightHandleIcon;
private Bitmap mMidHandleIcon;
private Bitmap mArrowShortLeftAndRight;
private Bitmap mArrowLongLeft; // Long arrow starting on the left, pointing clockwise
private Bitmap mArrowLongRight; // Long arrow starting on the right, pointing CCW
private Bitmap mArrowDown; //Short arrow pointing down middle
// positions of the left and right handle
private int mLeftHandleX;
private int mRightHandleX;
private int mMidHandleX;
// current offset of rotary widget along the x axis
private int mRotaryOffsetX = 0;
// current offset of rotary widget along the y axis - added to pull middle dimple down
private int mRotaryOffsetY = 0;
// saves the initial Y value on ACTION_DOWN
private int mEventStartY;
// controls display of custom app dimple
private boolean mCustomAppDimple=false;
// size of the status bar for resizing the background
private int mStatusBarSize=0;
// backgrond Scale for landscape mode with status bar in our way
private float mStatusBarScale=1;
// controls to hide the arrows
private boolean mHideArrows = false;
// are we in rotary revamped mode?
private boolean mRevampedMode=false;
// state of the animation used to bring the handle back to its start position when
// the user lets go before triggering an action
private boolean mAnimating = false;
private boolean mAnimatingUp = false;
private long mAnimationStartTime;
private long mAnimationDuration;
private int mAnimatingDeltaXStart; // the animation will interpolate from this delta to zero
private int mAnimatingDeltaXEnd;
private int mAnimatingDeltaYStart;
private int mAnimatingDeltaYEnd;
private DecelerateInterpolator mInterpolator;
private Paint mPaint = new Paint();
// used to rotate the background and arrow assets depending on orientation
final Matrix mBgMatrix = new Matrix();
final Matrix mArrowMatrix = new Matrix();
final Matrix drawMatrix = new Matrix();
/**
* If the user is currently dragging something.
*/
private int mGrabbedState = NOTHING_GRABBED;
public static final int NOTHING_GRABBED = 0;
public static final int LEFT_HANDLE_GRABBED = 1;
public static final int MID_HANDLE_GRABBED = 2;
public static final int RIGHT_HANDLE_GRABBED = 3;
/**
* Whether the user has triggered something (e.g dragging the left handle all the way over to
* the right).
*/
private boolean mTriggered = false;
// Vibration (haptic feedback)
private Vibrator mVibrator;
private static final long VIBRATE_SHORT = 20; // msec
private static final long VIBRATE_LONG = 20; // msec
/**
* The drawable for the arrows need to be scrunched this many dips towards the rotary bg below
* it.
*/
private static final int ARROW_SCRUNCH_DIP = 6;
/**
* How far inset the left and right circles should be
*/
private static final int EDGE_PADDING_DIP = 9;
/**
* How far from the edge of the screen the user must drag to trigger the event.
*/
private static final int EDGE_TRIGGER_DIP = 100;
/**
* Dimensions of arc in background drawable.
*/
static final int OUTER_ROTARY_RADIUS_DIP = 390;
static final int ROTARY_STROKE_WIDTH_DIP = 83;
static final int SNAP_BACK_ANIMATION_DURATION_MILLIS = 300;
static final int SPIN_ANIMATION_DURATION_MILLIS = 800;
private int mEdgeTriggerThresh;
private int mDimpleWidth;
private int mBackgroundWidth;
private int mBackgroundHeight;
private final int mOuterRadius;
private final int mInnerRadius;
private int mDimpleSpacing;
private VelocityTracker mVelocityTracker;
private int mMinimumVelocity;
private int mMaximumVelocity;
private long mMaxAnimationDuration;
/**
* The number of dimples we are flinging when we do the "spin" animation. Used to know when to
* wrap the icons back around so they "rotate back" onto the screen.
* @see #updateAnimation()
*/
private int mDimplesOfFling = 0;
/**
* Either {@link #HORIZONTAL} or {@link #VERTICAL}.
*/
private int mOrientation;
public RotarySelector(Context context) {
this(context, null);
}
/**
* Constructor used when this widget is created from a layout file.
*/
public RotarySelector(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a =
context.obtainStyledAttributes(attrs, R.styleable.RotarySelector);
mOrientation = a.getInt(R.styleable.RotarySelector_orientation, HORIZONTAL);
a.recycle();
Resources r = getResources();
mDensity = r.getDisplayMetrics().density;
if (DBG) log("- Density: " + mDensity);
// Assets (all are BitmapDrawables).
mBackground = getBitmapFor(R.drawable.jog_dial_bg);
mDimple = getBitmapFor(R.drawable.jog_dial_dimple);
mDimpleDim = getBitmapFor(R.drawable.jog_dial_dimple_dim);
mArrowLongLeft = getBitmapFor(R.drawable.jog_dial_arrow_long_left_green);
mArrowLongRight = getBitmapFor(R.drawable.jog_dial_arrow_long_right_red);
mArrowDown = getBitmapFor(R.drawable.jog_dial_arrow_short_down_green);
mArrowShortLeftAndRight = getBitmapFor(R.drawable.jog_dial_arrow_short_left_and_right);
mInterpolator = new DecelerateInterpolator(1f);
mEdgeTriggerThresh = (int) (mDensity * EDGE_TRIGGER_DIP);
mDimpleWidth = mDimple.getWidth();
mBackgroundWidth = mBackground.getWidth();
mBackgroundHeight = mBackground.getHeight();
mOuterRadius = (int) (mDensity * OUTER_ROTARY_RADIUS_DIP);
mInnerRadius = (int) ((OUTER_ROTARY_RADIUS_DIP - ROTARY_STROKE_WIDTH_DIP) * mDensity);
final ViewConfiguration configuration = ViewConfiguration.get(mContext);
mMinimumVelocity = configuration.getScaledMinimumFlingVelocity() * 2;
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
mMaxAnimationDuration = 1000;
}
private Bitmap getBitmapFor(int resId) {
return BitmapFactory.decodeResource(getContext().getResources(), resId);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
final int edgePadding = (int) (EDGE_PADDING_DIP * mDensity);
mLeftHandleX = edgePadding + mDimpleWidth / 2;
final int length = isHoriz() ? w : h;
mRightHandleX = length - edgePadding - mDimpleWidth / 2;
mMidHandleX = length / 2;
mDimpleSpacing = (length / 2) - mLeftHandleX;
// bg matrix only needs to be calculated once
mBgMatrix.setTranslate(0, 0);
if (!isHoriz()) {
// set up matrix for translating drawing of background and arrow assets
final int left = w - mBackgroundHeight;
mBgMatrix.preRotate(-90, 0, 0);
mBgMatrix.postTranslate(left, h);
} else {
mBgMatrix.postTranslate(0, h - mBackgroundHeight);
}
}
private boolean isHoriz() {
return mOrientation == HORIZONTAL;
}
/**
* Sets the left handle icon to a given resource.
*
* The resource should refer to a Drawable object, or use 0 to remove
* the icon.
*
* @param resId the resource ID.
*/
public void setLeftHandleResource(int resId) {
if (resId != 0) {
mLeftHandleIcon = getBitmapFor(resId);
}
invalidate();
}
/**
* Sets the left handle icon to a given drawable.
*
* The argument should refer to a Drawable object, or use 0 to remove
* the icon.
*
* @param icon Bitmap object.
*/
public void setLeftHandleResource(Bitmap icon) {
mLeftHandleIcon=icon;
invalidate();
}
/**
* Sets the right handle icon to a given resource.
*
* The resource should refer to a Drawable object, or use 0 to remove
* the icon.
*
* @param resId the resource ID.
*/
public void setRightHandleResource(int resId) {
if (resId != 0) {
mRightHandleIcon = getBitmapFor(resId);
}
invalidate();
}
/**
* Sets the middle handle icon to a given resource.
*
* The resource should refer to a Drawable object, or use 0 to remove
* the icon.
*
* @param resId the resource ID.
*/
public void setMidHandleResource(int resId) {
if (resId != 0) {
mMidHandleIcon = getBitmapFor(resId);
}
invalidate();
}
/**
* Sets the middle handle icon to a given drawable.
*
* The argument should refer to a Drawable object, or use 0 to remove
* the icon.
*
* @param icon Bitmap object.
*/
public void setMidHandleResource(Bitmap icon) {
mMidHandleIcon=icon;
invalidate();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int length = isHoriz() ?
MeasureSpec.getSize(widthMeasureSpec) :
MeasureSpec.getSize(heightMeasureSpec);
final int arrowScrunch = (int) (ARROW_SCRUNCH_DIP * mDensity);
final int arrowH = mArrowShortLeftAndRight.getHeight();
// by making the height less than arrow + bg, arrow and bg will be scrunched together,
// overlaying somewhat (though on transparent portions of the drawable).
// this works because the arrows are drawn from the top, and the rotary bg is drawn
// from the bottom.
final int height = mBackgroundHeight + arrowH - arrowScrunch;
if (isHoriz()) {
setMeasuredDimension(length, height);
} else {
setMeasuredDimension(height, length);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
final int width = getWidth();
final int height = getHeight();
final int bgHeight = mBackgroundHeight;
final int bgTop = isHoriz() ?
height - bgHeight:
width - bgHeight;
final int halfdimple = mDimpleWidth / 2;
if (VISUAL_DEBUG) {
// draw bounding box around widget
mPaint.setColor(0xffff0000);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawRect(0, 0, width, getHeight(), mPaint);
}
// update animating state before we draw anything
if (mAnimating || mAnimatingUp) {
updateAnimation();
}
// Background:
drawMatrix.set(mBgMatrix);
if (isHoriz())
drawMatrix.postTranslate(0, (float) mRotaryOffsetY);
else
drawMatrix.postTranslate((float) mRotaryOffsetY, 0);
canvas.drawBitmap(mBackground, drawMatrix, mPaint);
// Draw the correct arrow(s) depending on the current state:
if (!mHideArrows) {
mArrowMatrix.reset();
switch (mGrabbedState) {
case NOTHING_GRABBED:
//mArrowShortLeftAndRight;
break;
case LEFT_HANDLE_GRABBED:
mArrowMatrix.setTranslate(0, 0);
if (!isHoriz()) {
mArrowMatrix.preRotate(-90, 0, 0);
mArrowMatrix.postTranslate(0, height);
}
canvas.drawBitmap(mArrowLongLeft, mArrowMatrix, mPaint);
break;
case MID_HANDLE_GRABBED:
mArrowMatrix.setTranslate(0, 0);
if (!isHoriz()) {
mArrowMatrix.preRotate(-90, 0, 0);
}
// draw left down arrow
mArrowMatrix.postTranslate(halfdimple, 0);
canvas.drawBitmap(mArrowDown, mArrowMatrix, mPaint);
// draw right down arrow
mArrowMatrix.postTranslate(mRightHandleX-mLeftHandleX, 0);
canvas.drawBitmap(mArrowDown, mArrowMatrix, mPaint);
// draw mid down arrow
mArrowMatrix.postTranslate(mMidHandleX-mRightHandleX, -(mDimpleWidth/4));
canvas.drawBitmap(mArrowDown, mArrowMatrix, mPaint);
break;
case RIGHT_HANDLE_GRABBED:
- mArrowMatrix.setTranslate(0, 0);
+ mArrowMatrix.setTranslate(80, 0);
if (!isHoriz()) {
mArrowMatrix.preRotate(-90, 0, 0);
// since bg width is > height of screen in landscape mode...
mArrowMatrix.postTranslate(0, height + (mBackgroundWidth - height));
}
canvas.drawBitmap(mArrowLongRight, mArrowMatrix, mPaint);
break;
default:
throw new IllegalStateException("invalid mGrabbedState: " + mGrabbedState);
}
}
if (VISUAL_DEBUG) {
// draw circle bounding arc drawable: good sanity check we're doing the math correctly
float or = OUTER_ROTARY_RADIUS_DIP * mDensity;
final int vOffset = mBackgroundWidth - height;
final int midX = isHoriz() ? width / 2 : mBackgroundWidth / 2 - vOffset;
if (isHoriz()) {
canvas.drawCircle(midX, or + bgTop, or, mPaint);
} else {
canvas.drawCircle(or + bgTop, midX, or, mPaint);
}
}
// left dimple / icon
{
final int xOffset = mLeftHandleX + mRotaryOffsetX;
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
xOffset);
final int x = isHoriz() ? xOffset : drawableY + bgTop;
final int y = isHoriz() ? drawableY + bgTop : height - xOffset;
if (mRevampedMode || (mGrabbedState != RIGHT_HANDLE_GRABBED && mGrabbedState != MID_HANDLE_GRABBED)) {
drawCentered(mDimple, canvas, x, y);
drawCentered(mLeftHandleIcon, canvas, x, y);
} else {
drawCentered(mDimpleDim, canvas, x, y);
}
}
// center dimple / icon
{
final int xOffset = isHoriz() ?
width / 2 + mRotaryOffsetX:
height / 2 + mRotaryOffsetX;
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
xOffset);
final int x = isHoriz() ? xOffset : drawableY + bgTop;
final int y = isHoriz() ? drawableY + bgTop : height - xOffset;
if ((mRevampedMode || (mGrabbedState != LEFT_HANDLE_GRABBED
&& mGrabbedState != RIGHT_HANDLE_GRABBED)) && mCustomAppDimple) {
drawCentered(mDimple, canvas, x, y);
drawCentered(mMidHandleIcon, canvas, x, y);
} else {
drawCentered(mDimpleDim, canvas, x, y);
}
}
// right dimple / icon
{
final int xOffset = mRightHandleX + mRotaryOffsetX;
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
xOffset);
final int x = isHoriz() ? xOffset : drawableY + bgTop;
final int y = isHoriz() ? drawableY + bgTop : height - xOffset;
if (mRevampedMode || (mGrabbedState != LEFT_HANDLE_GRABBED
&& mGrabbedState != MID_HANDLE_GRABBED)) {
drawCentered(mDimple, canvas, x, y);
drawCentered(mRightHandleIcon, canvas, x, y);
} else {
drawCentered(mDimpleDim, canvas, x, y);
}
}
// draw extra left hand dimples
int dimpleLeft = mRotaryOffsetX + mLeftHandleX - mDimpleSpacing;
while (dimpleLeft > -halfdimple) {
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
dimpleLeft);
if (isHoriz()) {
drawCentered(mDimpleDim, canvas, dimpleLeft, drawableY + bgTop);
} else {
drawCentered(mDimpleDim, canvas, drawableY + bgTop, height - dimpleLeft);
}
dimpleLeft -= mDimpleSpacing;
}
// draw extra middle dimples
int dimpleMid = mRotaryOffsetX + mMidHandleX - mDimpleSpacing;
while (dimpleMid > -halfdimple) {
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
dimpleLeft);
if (isHoriz()) {
drawCentered(mDimpleDim, canvas, dimpleLeft, drawableY + bgTop);
} else {
drawCentered(mDimpleDim, canvas, drawableY + bgTop, height - dimpleLeft);
}
dimpleMid -= mDimpleSpacing;
}
// draw extra right hand dimples
int dimpleRight = mRotaryOffsetX + mRightHandleX + mDimpleSpacing;
final int rightThresh = mRight + halfdimple;
while (dimpleRight < rightThresh) {
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
dimpleRight);
if (isHoriz()) {
drawCentered(mDimpleDim, canvas, dimpleRight, drawableY + bgTop);
} else {
drawCentered(mDimpleDim, canvas, drawableY + bgTop, height - dimpleRight);
}
dimpleRight += mDimpleSpacing;
}
}
/**
* Assuming bitmap is a bounding box around a piece of an arc drawn by two concentric circles
* (as the background drawable for the rotary widget is), and given an x coordinate along the
* drawable, return the y coordinate of a point on the arc that is between the two concentric
* circles. The resulting y combined with the incoming x is a point along the circle in
* between the two concentric circles.
*
* @param backgroundWidth The width of the asset (the bottom of the box surrounding the arc).
* @param innerRadius The radius of the circle that intersects the drawable at the bottom two
* corders of the drawable (top two corners in terms of drawing coordinates).
* @param outerRadius The radius of the circle who's top most point is the top center of the
* drawable (bottom center in terms of drawing coordinates).
* @param x The distance along the x axis of the desired point. @return The y coordinate, in drawing coordinates, that will place (x, y) along the circle
* in between the two concentric circles.
*/
private int getYOnArc(int backgroundWidth, int innerRadius, int outerRadius, int x) {
// the hypotenuse
final int halfWidth = (outerRadius - innerRadius) / 2;
final int middleRadius = innerRadius + halfWidth;
// the bottom leg of the triangle
final int triangleBottom = (backgroundWidth / 2) - x;
// "Our offense is like the pythagorean theorem: There is no answer!" - Shaquille O'Neal
final int triangleY =
(int) Math.sqrt(middleRadius * middleRadius - triangleBottom * triangleBottom);
// convert to drawing coordinates:
// middleRadius - triangleY =
// the vertical distance from the outer edge of the circle to the desired point
// from there we add the distance from the top of the drawable to the middle circle
return middleRadius - triangleY + halfWidth + mRotaryOffsetY;
}
/**
* Handle touch screen events.
*
* @param event The motion event.
* @return True if the event was handled, false otherwise.
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mAnimating) {
return true;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
final int height = getHeight();
final int width = getWidth();
final int eventX = isHoriz() ?
(int) event.getX():
height - ((int) event.getY());
final int eventY = isHoriz() ?
(int) event.getY():
width - ((int) event.getX());
final int hitWindow = mDimpleWidth;
final int downThresh = mDimpleWidth * 2;
final int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
if (DBG) log("touch-down");
mTriggered = false;
mEventStartY = eventY;
if (mGrabbedState != NOTHING_GRABBED) {
reset();
invalidate();
}
if (eventX < mLeftHandleX + hitWindow) {
mRotaryOffsetX = eventX - mLeftHandleX;
setGrabbedState(LEFT_HANDLE_GRABBED);
invalidate();
vibrate(VIBRATE_SHORT);
} else if (eventX > mMidHandleX - hitWindow && eventX <= mRightHandleX - hitWindow && mCustomAppDimple) {
setGrabbedState(MID_HANDLE_GRABBED);
invalidate();
vibrate(VIBRATE_SHORT);
} else if (eventX > mRightHandleX - hitWindow) {
mRotaryOffsetX = eventX - mRightHandleX;
setGrabbedState(RIGHT_HANDLE_GRABBED);
invalidate();
vibrate(VIBRATE_SHORT);
}
break;
case MotionEvent.ACTION_MOVE:
if (DBG) log("touch-move");
if (mGrabbedState == LEFT_HANDLE_GRABBED) {
mRotaryOffsetX = eventX - mLeftHandleX;
invalidate();
final int rightThresh = isHoriz() ? getRight() : height;
if (eventX >= rightThresh - mEdgeTriggerThresh && !mTriggered) {
mTriggered = true;
dispatchTriggerEvent(OnDialTriggerListener.LEFT_HANDLE);
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
final int rawVelocity = isHoriz() ?
(int) velocityTracker.getXVelocity():
-(int) velocityTracker.getYVelocity();
final int velocity = Math.max(mMinimumVelocity, rawVelocity);
mDimplesOfFling = Math.max(
8,
Math.abs(velocity / mDimpleSpacing));
startAnimationWithVelocity(
eventX - mLeftHandleX,
mDimplesOfFling * mDimpleSpacing,
velocity);
}
} else if (mGrabbedState == MID_HANDLE_GRABBED && (mCustomAppDimple)) {
mRotaryOffsetY = eventY - mEventStartY;
if (!isHoriz())
mRotaryOffsetY = mEventStartY - eventY;
if (mRotaryOffsetY < 0) mRotaryOffsetY=0;
invalidate();
if (Math.abs(mRotaryOffsetY) >= downThresh && !mTriggered) {
mTriggered = true;
dispatchTriggerEvent(OnDialTriggerListener.MID_HANDLE);
// set up "flow up" animation
int delta = (isHoriz() ? eventY - mEventStartY : mEventStartY - eventY);
startAnimationUp(delta, 0, SNAP_BACK_ANIMATION_DURATION_MILLIS);
}
} else if (mGrabbedState == RIGHT_HANDLE_GRABBED) {
mRotaryOffsetX = eventX - mRightHandleX;
invalidate();
if (eventX <= mEdgeTriggerThresh && !mTriggered) {
mTriggered = true;
dispatchTriggerEvent(OnDialTriggerListener.RIGHT_HANDLE);
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
final int rawVelocity = isHoriz() ?
(int) velocityTracker.getXVelocity():
- (int) velocityTracker.getYVelocity();
final int velocity = Math.min(-mMinimumVelocity, rawVelocity);
mDimplesOfFling = Math.max(
8,
Math.abs(velocity / mDimpleSpacing));
startAnimationWithVelocity(
eventX - mRightHandleX,
-(mDimplesOfFling * mDimpleSpacing),
velocity);
}
}
break;
case MotionEvent.ACTION_UP:
if (DBG) log("touch-up");
// handle animating back to start if they didn't trigger
if (mGrabbedState == LEFT_HANDLE_GRABBED
&& Math.abs(eventX - mLeftHandleX) > 5) {
// set up "snap back" animation
startAnimation(eventX - mLeftHandleX, 0, SNAP_BACK_ANIMATION_DURATION_MILLIS);
} else if (mGrabbedState == MID_HANDLE_GRABBED) {
// set up "flow up" animation
int delta = (isHoriz() ? eventY - mEventStartY : mEventStartY - eventY);
if (delta > 5)
startAnimationUp(delta, 0, SNAP_BACK_ANIMATION_DURATION_MILLIS);
} else if (mGrabbedState == RIGHT_HANDLE_GRABBED
&& Math.abs(eventX - mRightHandleX) > 5) {
// set up "snap back" animation
startAnimation(eventX - mRightHandleX, 0, SNAP_BACK_ANIMATION_DURATION_MILLIS);
}
mRotaryOffsetX = 0;
mRotaryOffsetY = 0;
setGrabbedState(NOTHING_GRABBED);
invalidate();
if (mVelocityTracker != null) {
mVelocityTracker.recycle(); // wishin' we had generational GC
mVelocityTracker = null;
}
break;
case MotionEvent.ACTION_CANCEL:
if (DBG) log("touch-cancel");
reset();
invalidate();
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
break;
}
return true;
}
private void startAnimation(int startX, int endX, int duration) {
mAnimating = true;
mAnimationStartTime = currentAnimationTimeMillis();
mAnimationDuration = duration;
mAnimatingDeltaXStart = startX;
mAnimatingDeltaXEnd = endX;
setGrabbedState(NOTHING_GRABBED);
mDimplesOfFling = 0;
invalidate();
}
private void startAnimationWithVelocity(int startX, int endX, int pixelsPerSecond) {
mAnimating = true;
mAnimationStartTime = currentAnimationTimeMillis();
mAnimationDuration = 1000 * (endX - startX) / pixelsPerSecond;
mAnimatingDeltaXStart = startX;
mAnimatingDeltaXEnd = endX;
setGrabbedState(NOTHING_GRABBED);
invalidate();
}
private void startAnimationUp(int startY, int endY, int duration) {
mAnimatingUp = true;
mAnimationStartTime = currentAnimationTimeMillis();
mAnimationDuration = duration;
mAnimatingDeltaYStart = startY;
mAnimatingDeltaYEnd = endY;
setGrabbedState(NOTHING_GRABBED);
invalidate();
}
private void updateAnimation() {
final long millisSoFar = currentAnimationTimeMillis() - mAnimationStartTime;
final long millisLeft = mAnimationDuration - millisSoFar;
final int totalDeltaX = mAnimatingDeltaXStart - mAnimatingDeltaXEnd;
final int totalDeltaY = mAnimatingDeltaYStart - mAnimatingDeltaYEnd;
int dx;
final boolean goingRight = totalDeltaX < 0;
if (DBG) log("millisleft for animating: " + millisLeft);
if (millisLeft <= 0) {
mAnimating = false;
mAnimatingUp = false;
reset();
return;
}
// from 0 to 1 as animation progresses
float interpolation =
mInterpolator.getInterpolation((float) millisSoFar / mAnimationDuration);
if (mAnimating) {
dx = (int) (totalDeltaX * (1 - interpolation));
mRotaryOffsetX = mAnimatingDeltaXEnd + dx;
}
if (mAnimatingUp) {
dx = (int) (totalDeltaY * (1 - interpolation));
mRotaryOffsetY = mAnimatingDeltaYEnd + dx;
}
// once we have gone far enough to animate the current buttons off screen, we start
// wrapping the offset back to the other side so that when the animation is finished,
// the buttons will come back into their original places.
if (mDimplesOfFling > 0 && mAnimatingUp == false) {
if (!goingRight && mRotaryOffsetX < -3 * mDimpleSpacing) {
// wrap around on fling left
mRotaryOffsetX += mDimplesOfFling * mDimpleSpacing;
} else if (goingRight && mRotaryOffsetX > 3 * mDimpleSpacing) {
// wrap around on fling right
mRotaryOffsetX -= mDimplesOfFling * mDimpleSpacing;
}
}
invalidate();
}
public void reset() {
mAnimating = false;
mRotaryOffsetX = 0;
mDimplesOfFling = 0;
setGrabbedState(NOTHING_GRABBED);
mTriggered = false;
}
/**
* Triggers haptic feedback.
*/
private synchronized void vibrate(long duration) {
if (mVibrator == null) {
mVibrator = (android.os.Vibrator)
getContext().getSystemService(Context.VIBRATOR_SERVICE);
}
mVibrator.vibrate(duration);
}
/**
* Draw the bitmap so that it's centered
* on the point (x,y), then draws it using specified canvas.
* TODO: is there already a utility method somewhere for this?
*/
private void drawCentered(Bitmap d, Canvas c, int x, int y) {
int w = d.getWidth();
int h = d.getHeight();
c.drawBitmap(d, x - (w / 2), y - (h / 2), mPaint);
}
/**
* Registers a callback to be invoked when the dial
* is "triggered" by rotating it one way or the other.
*
* @param l the OnDialTriggerListener to attach to this view
*/
public void setOnDialTriggerListener(OnDialTriggerListener l) {
mOnDialTriggerListener = l;
}
/**
* Dispatches a trigger event to our listener.
*/
private void dispatchTriggerEvent(int whichHandle) {
vibrate(VIBRATE_LONG);
if (mOnDialTriggerListener != null) {
mOnDialTriggerListener.onDialTrigger(this, whichHandle);
}
}
/**
* Sets the current grabbed state, and dispatches a grabbed state change
* event to our listener.
*/
private void setGrabbedState(int newState) {
if (newState != mGrabbedState) {
mGrabbedState = newState;
if (mOnDialTriggerListener != null) {
mOnDialTriggerListener.onGrabbedStateChange(this, mGrabbedState);
}
}
}
/**
* Interface definition for a callback to be invoked when the dial
* is "triggered" by rotating it one way or the other.
*/
public interface OnDialTriggerListener {
/**
* The dial was triggered because the user grabbed the left handle,
* and rotated the dial clockwise.
*/
public static final int LEFT_HANDLE = 1;
/**
* The dial was triggered because the user grabbed the middle handle,
* and moved the dial down.
*/
public static final int MID_HANDLE = 2;
/**
* The dial was triggered because the user grabbed the right handle,
* and rotated the dial counterclockwise.
*/
public static final int RIGHT_HANDLE = 3;
/**
* Called when the dial is triggered.
*
* @param v The view that was triggered
* @param whichHandle Which "dial handle" the user grabbed,
* either {@link #LEFT_HANDLE}, {@link #RIGHT_HANDLE}.
*/
void onDialTrigger(View v, int whichHandle);
/**
* Called when the "grabbed state" changes (i.e. when
* the user either grabs or releases one of the handles.)
*
* @param v the view that was triggered
* @param grabbedState the new state: either {@link #NOTHING_GRABBED},
* {@link #LEFT_HANDLE_GRABBED}, or {@link #RIGHT_HANDLE_GRABBED}.
*/
void onGrabbedStateChange(View v, int grabbedState);
}
/**
* Sets weather or not to display the custom app dimple
*/
public void enableCustomAppDimple(boolean newState){
mCustomAppDimple=newState;
}
/**
* Sets weather or not to display the directional arrows
*/
public void hideArrows(boolean changeMe) {
mHideArrows = changeMe;
}
/**
* Sets up the original rotary style - called from InCallTouchUi.java only
*/
public void setRotary(boolean newState){
if(newState){
mBackground = getBitmapFor(R.drawable.jog_dial_bg);
mDimple = getBitmapFor(R.drawable.jog_dial_dimple);
mDimpleDim = getBitmapFor(R.drawable.jog_dial_dimple_dim);
}
}
/**
* Sets up the rotary revamped style - called from LockScreen.java and InCallTouchUi.java
*/
public void setRevamped(boolean newState){
if(newState){
if(mCustomAppDimple)
mBackground = getBitmapFor(R.drawable.jog_dial_bg);
else
mBackground = getBitmapFor(R.drawable.jog_dial_bg);
mDimple = getBitmapFor(R.drawable.jog_dial_dimple);
mDimpleDim = getBitmapFor(R.drawable.jog_dial_dimple_dim);
}
mRevampedMode=newState;
}
// Debugging / testing code
private void log(String msg) {
Log.d(LOG_TAG, msg);
}
}
| true | true | protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
final int width = getWidth();
final int height = getHeight();
final int bgHeight = mBackgroundHeight;
final int bgTop = isHoriz() ?
height - bgHeight:
width - bgHeight;
final int halfdimple = mDimpleWidth / 2;
if (VISUAL_DEBUG) {
// draw bounding box around widget
mPaint.setColor(0xffff0000);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawRect(0, 0, width, getHeight(), mPaint);
}
// update animating state before we draw anything
if (mAnimating || mAnimatingUp) {
updateAnimation();
}
// Background:
drawMatrix.set(mBgMatrix);
if (isHoriz())
drawMatrix.postTranslate(0, (float) mRotaryOffsetY);
else
drawMatrix.postTranslate((float) mRotaryOffsetY, 0);
canvas.drawBitmap(mBackground, drawMatrix, mPaint);
// Draw the correct arrow(s) depending on the current state:
if (!mHideArrows) {
mArrowMatrix.reset();
switch (mGrabbedState) {
case NOTHING_GRABBED:
//mArrowShortLeftAndRight;
break;
case LEFT_HANDLE_GRABBED:
mArrowMatrix.setTranslate(0, 0);
if (!isHoriz()) {
mArrowMatrix.preRotate(-90, 0, 0);
mArrowMatrix.postTranslate(0, height);
}
canvas.drawBitmap(mArrowLongLeft, mArrowMatrix, mPaint);
break;
case MID_HANDLE_GRABBED:
mArrowMatrix.setTranslate(0, 0);
if (!isHoriz()) {
mArrowMatrix.preRotate(-90, 0, 0);
}
// draw left down arrow
mArrowMatrix.postTranslate(halfdimple, 0);
canvas.drawBitmap(mArrowDown, mArrowMatrix, mPaint);
// draw right down arrow
mArrowMatrix.postTranslate(mRightHandleX-mLeftHandleX, 0);
canvas.drawBitmap(mArrowDown, mArrowMatrix, mPaint);
// draw mid down arrow
mArrowMatrix.postTranslate(mMidHandleX-mRightHandleX, -(mDimpleWidth/4));
canvas.drawBitmap(mArrowDown, mArrowMatrix, mPaint);
break;
case RIGHT_HANDLE_GRABBED:
mArrowMatrix.setTranslate(0, 0);
if (!isHoriz()) {
mArrowMatrix.preRotate(-90, 0, 0);
// since bg width is > height of screen in landscape mode...
mArrowMatrix.postTranslate(0, height + (mBackgroundWidth - height));
}
canvas.drawBitmap(mArrowLongRight, mArrowMatrix, mPaint);
break;
default:
throw new IllegalStateException("invalid mGrabbedState: " + mGrabbedState);
}
}
if (VISUAL_DEBUG) {
// draw circle bounding arc drawable: good sanity check we're doing the math correctly
float or = OUTER_ROTARY_RADIUS_DIP * mDensity;
final int vOffset = mBackgroundWidth - height;
final int midX = isHoriz() ? width / 2 : mBackgroundWidth / 2 - vOffset;
if (isHoriz()) {
canvas.drawCircle(midX, or + bgTop, or, mPaint);
} else {
canvas.drawCircle(or + bgTop, midX, or, mPaint);
}
}
// left dimple / icon
{
final int xOffset = mLeftHandleX + mRotaryOffsetX;
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
xOffset);
final int x = isHoriz() ? xOffset : drawableY + bgTop;
final int y = isHoriz() ? drawableY + bgTop : height - xOffset;
if (mRevampedMode || (mGrabbedState != RIGHT_HANDLE_GRABBED && mGrabbedState != MID_HANDLE_GRABBED)) {
drawCentered(mDimple, canvas, x, y);
drawCentered(mLeftHandleIcon, canvas, x, y);
} else {
drawCentered(mDimpleDim, canvas, x, y);
}
}
// center dimple / icon
{
final int xOffset = isHoriz() ?
width / 2 + mRotaryOffsetX:
height / 2 + mRotaryOffsetX;
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
xOffset);
final int x = isHoriz() ? xOffset : drawableY + bgTop;
final int y = isHoriz() ? drawableY + bgTop : height - xOffset;
if ((mRevampedMode || (mGrabbedState != LEFT_HANDLE_GRABBED
&& mGrabbedState != RIGHT_HANDLE_GRABBED)) && mCustomAppDimple) {
drawCentered(mDimple, canvas, x, y);
drawCentered(mMidHandleIcon, canvas, x, y);
} else {
drawCentered(mDimpleDim, canvas, x, y);
}
}
// right dimple / icon
{
final int xOffset = mRightHandleX + mRotaryOffsetX;
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
xOffset);
final int x = isHoriz() ? xOffset : drawableY + bgTop;
final int y = isHoriz() ? drawableY + bgTop : height - xOffset;
if (mRevampedMode || (mGrabbedState != LEFT_HANDLE_GRABBED
&& mGrabbedState != MID_HANDLE_GRABBED)) {
drawCentered(mDimple, canvas, x, y);
drawCentered(mRightHandleIcon, canvas, x, y);
} else {
drawCentered(mDimpleDim, canvas, x, y);
}
}
// draw extra left hand dimples
int dimpleLeft = mRotaryOffsetX + mLeftHandleX - mDimpleSpacing;
while (dimpleLeft > -halfdimple) {
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
dimpleLeft);
if (isHoriz()) {
drawCentered(mDimpleDim, canvas, dimpleLeft, drawableY + bgTop);
} else {
drawCentered(mDimpleDim, canvas, drawableY + bgTop, height - dimpleLeft);
}
dimpleLeft -= mDimpleSpacing;
}
// draw extra middle dimples
int dimpleMid = mRotaryOffsetX + mMidHandleX - mDimpleSpacing;
while (dimpleMid > -halfdimple) {
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
dimpleLeft);
if (isHoriz()) {
drawCentered(mDimpleDim, canvas, dimpleLeft, drawableY + bgTop);
} else {
drawCentered(mDimpleDim, canvas, drawableY + bgTop, height - dimpleLeft);
}
dimpleMid -= mDimpleSpacing;
}
// draw extra right hand dimples
int dimpleRight = mRotaryOffsetX + mRightHandleX + mDimpleSpacing;
final int rightThresh = mRight + halfdimple;
while (dimpleRight < rightThresh) {
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
dimpleRight);
if (isHoriz()) {
drawCentered(mDimpleDim, canvas, dimpleRight, drawableY + bgTop);
} else {
drawCentered(mDimpleDim, canvas, drawableY + bgTop, height - dimpleRight);
}
dimpleRight += mDimpleSpacing;
}
}
| protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
final int width = getWidth();
final int height = getHeight();
final int bgHeight = mBackgroundHeight;
final int bgTop = isHoriz() ?
height - bgHeight:
width - bgHeight;
final int halfdimple = mDimpleWidth / 2;
if (VISUAL_DEBUG) {
// draw bounding box around widget
mPaint.setColor(0xffff0000);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawRect(0, 0, width, getHeight(), mPaint);
}
// update animating state before we draw anything
if (mAnimating || mAnimatingUp) {
updateAnimation();
}
// Background:
drawMatrix.set(mBgMatrix);
if (isHoriz())
drawMatrix.postTranslate(0, (float) mRotaryOffsetY);
else
drawMatrix.postTranslate((float) mRotaryOffsetY, 0);
canvas.drawBitmap(mBackground, drawMatrix, mPaint);
// Draw the correct arrow(s) depending on the current state:
if (!mHideArrows) {
mArrowMatrix.reset();
switch (mGrabbedState) {
case NOTHING_GRABBED:
//mArrowShortLeftAndRight;
break;
case LEFT_HANDLE_GRABBED:
mArrowMatrix.setTranslate(0, 0);
if (!isHoriz()) {
mArrowMatrix.preRotate(-90, 0, 0);
mArrowMatrix.postTranslate(0, height);
}
canvas.drawBitmap(mArrowLongLeft, mArrowMatrix, mPaint);
break;
case MID_HANDLE_GRABBED:
mArrowMatrix.setTranslate(0, 0);
if (!isHoriz()) {
mArrowMatrix.preRotate(-90, 0, 0);
}
// draw left down arrow
mArrowMatrix.postTranslate(halfdimple, 0);
canvas.drawBitmap(mArrowDown, mArrowMatrix, mPaint);
// draw right down arrow
mArrowMatrix.postTranslate(mRightHandleX-mLeftHandleX, 0);
canvas.drawBitmap(mArrowDown, mArrowMatrix, mPaint);
// draw mid down arrow
mArrowMatrix.postTranslate(mMidHandleX-mRightHandleX, -(mDimpleWidth/4));
canvas.drawBitmap(mArrowDown, mArrowMatrix, mPaint);
break;
case RIGHT_HANDLE_GRABBED:
mArrowMatrix.setTranslate(80, 0);
if (!isHoriz()) {
mArrowMatrix.preRotate(-90, 0, 0);
// since bg width is > height of screen in landscape mode...
mArrowMatrix.postTranslate(0, height + (mBackgroundWidth - height));
}
canvas.drawBitmap(mArrowLongRight, mArrowMatrix, mPaint);
break;
default:
throw new IllegalStateException("invalid mGrabbedState: " + mGrabbedState);
}
}
if (VISUAL_DEBUG) {
// draw circle bounding arc drawable: good sanity check we're doing the math correctly
float or = OUTER_ROTARY_RADIUS_DIP * mDensity;
final int vOffset = mBackgroundWidth - height;
final int midX = isHoriz() ? width / 2 : mBackgroundWidth / 2 - vOffset;
if (isHoriz()) {
canvas.drawCircle(midX, or + bgTop, or, mPaint);
} else {
canvas.drawCircle(or + bgTop, midX, or, mPaint);
}
}
// left dimple / icon
{
final int xOffset = mLeftHandleX + mRotaryOffsetX;
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
xOffset);
final int x = isHoriz() ? xOffset : drawableY + bgTop;
final int y = isHoriz() ? drawableY + bgTop : height - xOffset;
if (mRevampedMode || (mGrabbedState != RIGHT_HANDLE_GRABBED && mGrabbedState != MID_HANDLE_GRABBED)) {
drawCentered(mDimple, canvas, x, y);
drawCentered(mLeftHandleIcon, canvas, x, y);
} else {
drawCentered(mDimpleDim, canvas, x, y);
}
}
// center dimple / icon
{
final int xOffset = isHoriz() ?
width / 2 + mRotaryOffsetX:
height / 2 + mRotaryOffsetX;
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
xOffset);
final int x = isHoriz() ? xOffset : drawableY + bgTop;
final int y = isHoriz() ? drawableY + bgTop : height - xOffset;
if ((mRevampedMode || (mGrabbedState != LEFT_HANDLE_GRABBED
&& mGrabbedState != RIGHT_HANDLE_GRABBED)) && mCustomAppDimple) {
drawCentered(mDimple, canvas, x, y);
drawCentered(mMidHandleIcon, canvas, x, y);
} else {
drawCentered(mDimpleDim, canvas, x, y);
}
}
// right dimple / icon
{
final int xOffset = mRightHandleX + mRotaryOffsetX;
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
xOffset);
final int x = isHoriz() ? xOffset : drawableY + bgTop;
final int y = isHoriz() ? drawableY + bgTop : height - xOffset;
if (mRevampedMode || (mGrabbedState != LEFT_HANDLE_GRABBED
&& mGrabbedState != MID_HANDLE_GRABBED)) {
drawCentered(mDimple, canvas, x, y);
drawCentered(mRightHandleIcon, canvas, x, y);
} else {
drawCentered(mDimpleDim, canvas, x, y);
}
}
// draw extra left hand dimples
int dimpleLeft = mRotaryOffsetX + mLeftHandleX - mDimpleSpacing;
while (dimpleLeft > -halfdimple) {
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
dimpleLeft);
if (isHoriz()) {
drawCentered(mDimpleDim, canvas, dimpleLeft, drawableY + bgTop);
} else {
drawCentered(mDimpleDim, canvas, drawableY + bgTop, height - dimpleLeft);
}
dimpleLeft -= mDimpleSpacing;
}
// draw extra middle dimples
int dimpleMid = mRotaryOffsetX + mMidHandleX - mDimpleSpacing;
while (dimpleMid > -halfdimple) {
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
dimpleLeft);
if (isHoriz()) {
drawCentered(mDimpleDim, canvas, dimpleLeft, drawableY + bgTop);
} else {
drawCentered(mDimpleDim, canvas, drawableY + bgTop, height - dimpleLeft);
}
dimpleMid -= mDimpleSpacing;
}
// draw extra right hand dimples
int dimpleRight = mRotaryOffsetX + mRightHandleX + mDimpleSpacing;
final int rightThresh = mRight + halfdimple;
while (dimpleRight < rightThresh) {
final int drawableY = getYOnArc(
mBackgroundWidth,
mInnerRadius,
mOuterRadius,
dimpleRight);
if (isHoriz()) {
drawCentered(mDimpleDim, canvas, dimpleRight, drawableY + bgTop);
} else {
drawCentered(mDimpleDim, canvas, drawableY + bgTop, height - dimpleRight);
}
dimpleRight += mDimpleSpacing;
}
}
|
diff --git a/src/main/java/org/glite/authz/pap/repository/dao/FileSystemDAOFactory.java b/src/main/java/org/glite/authz/pap/repository/dao/FileSystemDAOFactory.java
index 14d5eda..61ec9b4 100644
--- a/src/main/java/org/glite/authz/pap/repository/dao/FileSystemDAOFactory.java
+++ b/src/main/java/org/glite/authz/pap/repository/dao/FileSystemDAOFactory.java
@@ -1,46 +1,46 @@
package org.glite.authz.pap.repository.dao;
import java.io.File;
import org.glite.authz.pap.common.RepositoryConfiguration;
import org.glite.authz.pap.repository.RepositoryException;
public class FileSystemDAOFactory extends DAOFactory {
private static FileSystemDAOFactory instance = null;
public static FileSystemDAOFactory getInstance() {
if (instance == null) {
instance = new FileSystemDAOFactory();
}
return instance;
}
private FileSystemDAOFactory() {
initDB();
}
public PolicyDAO getPolicyDAO() {
return FileSystemPolicyDAO.getInstance();
}
public PolicySetDAO getPolicySetDAO() {
return FileSystemPolicySetDAO.getInstance();
}
public RootPolicySetDAO getRootPolicySetDAO() {
return FileSystemRootPolicySetDAO.getInstance();
}
// Maybe not the right place for initializing the DB
private void initDB() {
File rootDir = new File(RepositoryConfiguration.getFileSystemDatabaseDir());
if (!rootDir.exists()) {
if (!rootDir.mkdirs()) {
throw new RepositoryException("Cannot create DB dir");
}
}
- if (!(rootDir.canExecute() && rootDir.canRead() && rootDir.canWrite())) {
+ if (!(rootDir.canRead() && rootDir.canWrite())) {
throw new RepositoryException("Permission denied for DB dir");
}
}
}
| true | true | private void initDB() {
File rootDir = new File(RepositoryConfiguration.getFileSystemDatabaseDir());
if (!rootDir.exists()) {
if (!rootDir.mkdirs()) {
throw new RepositoryException("Cannot create DB dir");
}
}
if (!(rootDir.canExecute() && rootDir.canRead() && rootDir.canWrite())) {
throw new RepositoryException("Permission denied for DB dir");
}
}
| private void initDB() {
File rootDir = new File(RepositoryConfiguration.getFileSystemDatabaseDir());
if (!rootDir.exists()) {
if (!rootDir.mkdirs()) {
throw new RepositoryException("Cannot create DB dir");
}
}
if (!(rootDir.canRead() && rootDir.canWrite())) {
throw new RepositoryException("Permission denied for DB dir");
}
}
|
diff --git a/core/infinit.e.processing.custom.library/src/com/ikanow/infinit/e/processing/custom/launcher/CustomHadoopTaskLauncher.java b/core/infinit.e.processing.custom.library/src/com/ikanow/infinit/e/processing/custom/launcher/CustomHadoopTaskLauncher.java
index 6464d624..8b9e07dc 100644
--- a/core/infinit.e.processing.custom.library/src/com/ikanow/infinit/e/processing/custom/launcher/CustomHadoopTaskLauncher.java
+++ b/core/infinit.e.processing.custom.library/src/com/ikanow/infinit/e/processing/custom/launcher/CustomHadoopTaskLauncher.java
@@ -1,523 +1,523 @@
/*******************************************************************************
* Copyright 2012, The Infinit.e Open Source Project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package com.ikanow.infinit.e.processing.custom.launcher;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.OutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.bson.types.ObjectId;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.ikanow.infinit.e.data_model.store.DbManager;
import com.ikanow.infinit.e.data_model.store.MongoDbManager;
import com.ikanow.infinit.e.data_model.store.config.source.SourcePojo;
import com.ikanow.infinit.e.data_model.store.custom.mapreduce.CustomMapReduceJobPojo;
import com.ikanow.infinit.e.data_model.store.document.DocumentPojo;
import com.ikanow.infinit.e.processing.custom.output.CustomOutputManager;
import com.ikanow.infinit.e.processing.custom.utils.HadoopUtils;
import com.ikanow.infinit.e.processing.custom.utils.InfiniteHadoopUtils;
import com.ikanow.infinit.e.processing.custom.utils.PropertiesManager;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
public class CustomHadoopTaskLauncher extends AppenderSkeleton {
private static Logger _logger = Logger.getLogger(CustomHadoopTaskLauncher.class);
private com.ikanow.infinit.e.data_model.utils.PropertiesManager prop_general = new com.ikanow.infinit.e.data_model.utils.PropertiesManager();
private PropertiesManager props_custom = null;
private boolean bLocalMode;
private Integer nDebugLimit;
public CustomHadoopTaskLauncher(boolean bLocalMode_, Integer nDebugLimit_, PropertiesManager prop_custom_)
{
bLocalMode = bLocalMode_;
nDebugLimit = nDebugLimit_;
props_custom = prop_custom_;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public String runHadoopJob(CustomMapReduceJobPojo job, String tempJarLocation) throws IOException, SAXException, ParserConfigurationException
{
StringWriter xml = new StringWriter();
String outputCollection = job.outputCollectionTemp;// (non-append mode)
if ( ( null != job.appendResults ) && job.appendResults)
outputCollection = job.outputCollection; // (append mode, write directly in....)
else if ( null != job.incrementalMode )
job.incrementalMode = false; // (not allowed to be in incremental mode and not update mode)
createConfigXML(xml, job.jobtitle,job.inputCollection, InfiniteHadoopUtils.getQueryOrProcessing(job.query,InfiniteHadoopUtils.QuerySpec.INPUTFIELDS), job.isCustomTable, job.getOutputDatabase(), job._id.toString(), outputCollection, job.mapper, job.reducer, job.combiner, InfiniteHadoopUtils.getQueryOrProcessing(job.query,InfiniteHadoopUtils.QuerySpec.QUERY), job.communityIds, job.outputKey, job.outputValue,job.arguments, job.incrementalMode);
ClassLoader savedClassLoader = Thread.currentThread().getContextClassLoader();
//TODO (INF-1159): NOTE WE SHOULD REPLACE THIS WITH JarAsByteArrayClassLoader (data_model.utils) WHEN POSSIBLE
URLClassLoader child = new URLClassLoader (new URL[] { new File(tempJarLocation).toURI().toURL() }, savedClassLoader);
Thread.currentThread().setContextClassLoader(child);
// Now load the XML into a configuration object:
Configuration config = new Configuration();
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new ByteArrayInputStream(xml.toString().getBytes()));
NodeList nList = doc.getElementsByTagName("property");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String name = getTagValue("name", eElement);
String value = getTagValue("value", eElement);
if ((null != name) && (null != value)) {
config.set(name, value);
}
}
}
}
catch (Exception e) {
throw new IOException(e.getMessage());
}
// Now run the JAR file
try {
config.setBoolean("mapred.used.genericoptionsparser", true); // (just stops an annoying warning from appearing)
if (bLocalMode) {
config.set("mapred.job.tracker", "local");
config.set("fs.default.name", "local");
}
else {
String trackerUrl = HadoopUtils.getXMLProperty(props_custom.getHadoopConfigPath() + "/hadoop/mapred-site.xml", "mapred.job.tracker");
String fsUrl = HadoopUtils.getXMLProperty(props_custom.getHadoopConfigPath() + "/hadoop/core-site.xml", "fs.default.name");
config.set("mapred.job.tracker", trackerUrl);
config.set("fs.default.name", fsUrl);
}
Job hj = new Job( config );
Class<?> classToLoad = Class.forName (job.mapper, true, child);
hj.setJarByClass(classToLoad);
hj.setInputFormatClass((Class<? extends InputFormat>) Class.forName ("com.ikanow.infinit.e.data_model.custom.InfiniteMongoInputFormat", true, child));
if ((null != job.exportToHdfs) && job.exportToHdfs) {
hj.setOutputFormatClass((Class<? extends OutputFormat>) Class.forName ("org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat", true, child));
Path outPath = InfiniteHadoopUtils.ensureOutputDirectory(job, props_custom);
SequenceFileOutputFormat.setOutputPath(hj, outPath);
}
else { // normal case, stays in MongoDB
hj.setOutputFormatClass((Class<? extends OutputFormat>) Class.forName ("com.ikanow.infinit.e.data_model.custom.InfiniteMongoOutputFormat", true, child));
}
hj.setMapperClass((Class<? extends Mapper>) Class.forName (job.mapper, true, child));
if ((null != job.reducer) && !job.reducer.startsWith("#") && !job.reducer.equalsIgnoreCase("null") && !job.reducer.equalsIgnoreCase("none")) {
hj.setReducerClass((Class<? extends Reducer>) Class.forName (job.reducer, true, child));
}
else {
hj.setNumReduceTasks(0);
}
if ((null != job.combiner) && !job.combiner.startsWith("#") && !job.combiner.equalsIgnoreCase("null") && !job.combiner.equalsIgnoreCase("none")) {
hj.setCombinerClass((Class<? extends Reducer>) Class.forName (job.combiner, true, child));
}
hj.setOutputKeyClass(Class.forName (job.outputKey, true, child));
hj.setOutputValueClass(Class.forName (job.outputValue, true, child));
hj.setJobName(job.jobtitle);
if (bLocalMode) {
hj.submit();
currThreadId = null;
Logger.getRootLogger().addAppender(this);
currLocalJobId = hj.getJobID().toString();
currLocalJobErrs.setLength(0);
while (!hj.isComplete()) {
Thread.sleep(1000);
}
Logger.getRootLogger().removeAppender(this);
if (hj.isSuccessful()) {
if (this.currLocalJobErrs.length() > 0) {
return "local_done: " + this.currLocalJobErrs.toString();
}
else {
return "local_done";
}
}
else {
return "Error: " + this.currLocalJobErrs.toString();
}
}
else {
hj.submit();
String jobId = hj.getJobID().toString();
return jobId;
}
}
catch (Exception e) {
e.printStackTrace();
Thread.currentThread().setContextClassLoader(savedClassLoader);
return "Error: " + InfiniteHadoopUtils.createExceptionMessage(e);
}
finally {
Thread.currentThread().setContextClassLoader(savedClassLoader);
}
}
public String runHadoopJob_commandLine(CustomMapReduceJobPojo job, String jar)
{
String jobid = null;
try
{
job.tempConfigXMLLocation = createConfigXML_commandLine(job.jobtitle,job.inputCollection,job._id.toString(),job.tempConfigXMLLocation, job.mapper, job.reducer, job.combiner, InfiniteHadoopUtils.getQueryOrProcessing(job.query,InfiniteHadoopUtils.QuerySpec.QUERY), job.communityIds, job.isCustomTable, job.getOutputDatabase(), job.outputKey, job.outputValue,job.outputCollectionTemp,job.arguments, job.incrementalMode);
Runtime rt = Runtime.getRuntime();
String[] commands = new String[]{"hadoop","--config", props_custom.getHadoopConfigPath() + "/hadoop", "jar", jar, "-conf", job.tempConfigXMLLocation};
String command = "";
for (String s : commands )
command += s + " ";
Process pr = rt.exec(commands);
//Once we start running the command attach to stderr to
//receive the output to parse out the jobid
InputStream in = pr.getErrorStream();
InputStreamReader is = new InputStreamReader(in);
BufferedReader br = new BufferedReader(is);
StringBuilder output = new StringBuilder();
String line = null;
long startTime = new Date().getTime();
boolean bGotJobId = false;
//while we haven't found the id, there are still lines to read, and it hasn't been more than 60 seconds
while (!bGotJobId && (line = br.readLine()) != null && (new Date().getTime() - startTime) < InfiniteHadoopUtils.SECONDS_60 )
{
output.append(line);
int getJobIdIndex = -1;
String searchstring = "INFO mapred.JobClient: Running job: ";
if ((getJobIdIndex = line.indexOf(searchstring)) >= 0)
{
// Get JobId and trim() it (obviously trivial)
jobid = line.substring(getJobIdIndex + searchstring.length()).trim();
bGotJobId = true;
}
}
//60 seconds passed and we never found the id
if ( !bGotJobId )
{
_logger.info("job_start_timeout_error_title=" + job.jobtitle + " job_start_timeout_error_id=" + job._id.toString() + " job_start_timeout_error_message=" + output.toString());
//if we never found the id mark it as errored out
return "Error:\n" + output.toString();
}
}
catch (Exception ex)
{
//had an error running command
//probably log error to the job so we stop trying to run it
_logger.info("job_start_timeout_error_title=" + job.jobtitle + " job_start_timeout_error_id=" + job._id.toString() + " job_start_timeout_error_message=" + InfiniteHadoopUtils.createExceptionMessage(ex));
jobid = "Error:\n" + ex.getMessage(); // (means this gets displayed)
}
return jobid;
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// UTILS
/**
* Create the xml file that will configure the mongo commands and
* write that to the server
*
* @param input
* @param output
* @throws IOException
*/
private String createConfigXML_commandLine( String title, String input, String output, String configLocation, String mapper, String reducer, String combiner, String query, List<ObjectId> communityIds, boolean isCustomTable, String outputDatabase, String outputKey, String outputValue, String tempOutputCollection, String arguments, Boolean incrementalMode) throws IOException
{
if ( configLocation == null )
configLocation = InfiniteHadoopUtils.assignNewConfigLocation(props_custom);
File configFile = new File(configLocation);
FileWriter fstream = new FileWriter(configFile);
BufferedWriter out = new BufferedWriter(fstream);
createConfigXML(out, title, input, InfiniteHadoopUtils.getQueryOrProcessing(query,InfiniteHadoopUtils.QuerySpec.INPUTFIELDS), isCustomTable, outputDatabase, output, tempOutputCollection, mapper, reducer, combiner, query, communityIds, outputKey, outputValue, arguments, incrementalMode);
fstream.close();
return configLocation;
}
private void createConfigXML( Writer out, String title, String input, String fields, boolean isCustomTable, String outputDatabase, String output, String tempOutputCollection, String mapper, String reducer, String combiner, String query, List<ObjectId> communityIds, String outputKey, String outputValue, String arguments, Boolean incrementalMode) throws IOException
{
String dbserver = prop_general.getDatabaseServer();
output = outputDatabase + "." + tempOutputCollection;
int nSplits = 8;
int nDocsPerSplit = 12500;
//add communities to query if this is not a custom table
BasicDBObject oldQueryObj = null;
// Start with the old query:
if (query.startsWith("{")) {
oldQueryObj = (BasicDBObject) com.mongodb.util.JSON.parse(query);
}
else {
oldQueryObj = new BasicDBObject();
}
int nLimit = 0;
if (oldQueryObj.containsField("$limit")) {
nLimit = oldQueryObj.getInt("$limit");
oldQueryObj.remove("$limit");
}
if (oldQueryObj.containsField("$splits")) {
nSplits = oldQueryObj.getInt("$splits");
oldQueryObj.remove("$splits");
}
- if (bLocalMode) { // If in local mode, then set this to infinity so we always run inside our limit/split version
+ if (bLocalMode) { // If in local mode, then set this to a large number so we always run inside our limit/split version
// (since for some reason MongoInputFormat seems to fail on large collections)
- nSplits = Integer.MAX_VALUE;
+ nSplits = 10000000; // (10m)
}
if (oldQueryObj.containsField("$docsPerSplit")) {
nDocsPerSplit = oldQueryObj.getInt("$docsPerSplit");
oldQueryObj.remove("$docsPerSplit");
}
oldQueryObj.remove("$fields");
oldQueryObj.remove("$output");
if (null != nDebugLimit) { // (debug mode override)
nLimit = nDebugLimit;
this.bTestMode = true;
}
boolean tmpIncMode = ( null != incrementalMode) && incrementalMode;
if ( !isCustomTable )
{
// Community Ids aren't indexed in the metadata collection, but source keys are, so we need to transform to that
BasicDBObject keyQuery = new BasicDBObject(SourcePojo.communityIds_, new BasicDBObject(DbManager.in_, communityIds));
if (oldQueryObj.containsField(DocumentPojo.sourceKey_) || input.startsWith("feature.")) {
// Source Key specified by user, stick communityIds check in for security
oldQueryObj.put(DocumentPojo.communityId_, new BasicDBObject(DbManager.in_, communityIds));
}
else { // Source key not specified by user, transform communities->sourcekeys
BasicDBObject keyFields = new BasicDBObject(SourcePojo.key_, 1);
DBCursor dbc = MongoDbManager.getIngest().getSource().find(keyQuery, keyFields);
if (dbc.count() > 500) {
// (too many source keys let's keep the query size sensible...)
oldQueryObj.put(DocumentPojo.communityId_, new BasicDBObject(DbManager.in_, communityIds));
}
else {
HashSet<String> sourceKeys = new HashSet<String>();
while (dbc.hasNext()) {
DBObject dbo = dbc.next();
String sourceKey = (String) dbo.get(SourcePojo.key_);
if (null != sourceKey) {
sourceKeys.add(sourceKey);
}
}
if (sourceKeys.isEmpty()) { // query returns empty
throw new RuntimeException("Communities contain no sources");
}
BasicDBObject newQueryClauseObj = new BasicDBObject(DbManager.in_, sourceKeys);
// Now combine the queries...
oldQueryObj.put(DocumentPojo.sourceKey_, newQueryClauseObj);
} // (end if too many source keys across the communities)
}//(end if need to break source keys down into communities)
query = oldQueryObj.toString();
}
else
{
//get the custom table (and database)
input = CustomOutputManager.getCustomDbAndCollection(input);
}
if ( arguments == null )
arguments = "";
// For logging in local mode:
currQuery = query;
// Generic configuration
out.write("<?xml version=\"1.0\"?>\n<configuration>");
// Mongo specific configuration
out.write(
"\n\t<property><!-- name of job shown in jobtracker --><name>mongo.job.name</name><value>"+title+"</value></property>"+
"\n\t<property><!-- run the job verbosely ? --><name>mongo.job.verbose</name><value>true</value></property>"+
"\n\t<property><!-- Run the job in the foreground and wait for response, or background it? --><name>mongo.job.background</name><value>false</value></property>"+
"\n\t<property><!-- If you are reading from mongo, the URI --><name>mongo.input.uri</name><value>mongodb://"+dbserver+"/"+input+"</value></property>"+
"\n\t<property><!-- If you are writing to mongo, the URI --><name>mongo.output.uri</name><value>mongodb://"+dbserver+"/"+output+"</value> </property>"+
"\n\t<property><!-- The query, in JSON, to execute [OPTIONAL] --><name>mongo.input.query</name><value>" + query + "</value></property>"+
"\n\t<property><!-- The fields, in JSON, to read [OPTIONAL] --><name>mongo.input.fields</name><value>"+( (fields==null) ? ("") : fields )+"</value></property>"+
"\n\t<property><!-- A JSON sort specification for read [OPTIONAL] --><name>mongo.input.sort</name><value></value></property>"+
"\n\t<property><!-- The number of documents to limit to for read [OPTIONAL] --><name>mongo.input.limit</name><value>" + nLimit + "</value><!-- 0 == no limit --></property>"+
"\n\t<property><!-- The number of documents to skip in read [OPTIONAL] --><!-- TODO - Are we running limit() or skip() first? --><name>mongo.input.skip</name><value>0</value> <!-- 0 == no skip --></property>"+
"\n\t<property><!-- Class for the mapper --><name>mongo.job.mapper</name><value>"+ mapper+"</value></property>"+
"\n\t<property><!-- Reducer class --><name>mongo.job.reducer</name><value>"+reducer+"</value></property>"+
"\n\t<property><!-- InputFormat Class --><name>mongo.job.input.format</name><value>com.ikanow.infinit.e.data_model.custom.InfiniteMongoInputFormat</value></property>"+
"\n\t<property><!-- OutputFormat Class --><name>mongo.job.output.format</name><value>com.ikanow.infinit.e.data_model.custom.InfiniteMongoOutputFormat</value></property>"+
"\n\t<property><!-- Output key class for the output format --><name>mongo.job.output.key</name><value>"+outputKey+"</value></property>"+
"\n\t<property><!-- Output value class for the output format --><name>mongo.job.output.value</name><value>"+outputValue+"</value></property>"+
"\n\t<property><!-- Output key class for the mapper [optional] --><name>mongo.job.mapper.output.key</name><value></value></property>"+
"\n\t<property><!-- Output value class for the mapper [optional] --><name>mongo.job.mapper.output.value</name><value></value></property>"+
"\n\t<property><!-- Class for the combiner [optional] --><name>mongo.job.combiner</name><value>"+combiner+"</value></property>"+
"\n\t<property><!-- Partitioner class [optional] --><name>mongo.job.partitioner</name><value></value></property>"+
"\n\t<property><!-- Sort Comparator class [optional] --><name>mongo.job.sort_comparator</name><value></value></property>"+
"\n\t<property><!-- Split Size [optional] --><name>mongo.input.split_size</name><value>32</value></property>"
);
// Infinit.e specific configuration
out.write(
"\n\t<property><!-- User Arguments [optional] --><name>arguments</name><value>"+ StringEscapeUtils.escapeXml(arguments)+"</value></property>"+
"\n\t<property><!-- Maximum number of splits [optional] --><name>max.splits</name><value>"+nSplits+"</value></property>"+
"\n\t<property><!-- Maximum number of docs per split [optional] --><name>max.docs.per.split</name><value>"+nDocsPerSplit+"</value></property>"+
"\n\t<property><!-- Infinit.e incremental mode [optional] --><name>update.incremental</name><value>"+tmpIncMode+"</value></property>"
);
// Closing thoughts:
out.write("\n</configuration>");
out.flush();
out.close();
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// REALLY LOW LEVEL UTILS
private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
if (null != nValue) {
return nValue.getNodeValue();
}
else {
return null;
}
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// LOGGING INTERFACE
private String currLocalJobId = null;
private String currSanityCheck = null;
private String currThreadId = null;
private String currQuery = null;
private StringBuffer currLocalJobErrs = new StringBuffer();
private boolean bTestMode = false;
@Override
public void close() {
}
@Override
public boolean requiresLayout() {
return false;
}
@Override
protected void append(LoggingEvent arg0) {
if (null == currThreadId) { // this is one of the first message that is printed out so get the thread...
if (arg0.getLoggerName().equals("com.mongodb.hadoop.input.MongoInputSplit")) {
if ((null != currQuery) && arg0.getRenderedMessage().contains(currQuery)) {
currThreadId = arg0.getThreadName();
currSanityCheck = "Task:attempt_" + currLocalJobId.substring(4) + "_";
}
}
}//TESTED
else if ((null != currThreadId) && arg0.getLoggerName().equals("org.apache.hadoop.mapred.Task")) {
if (arg0.getRenderedMessage().startsWith(currSanityCheck)) {
// This is to check we didn't accidentally get someone else's messages
if (!currThreadId.equals(arg0.getThreadName())) {
_logger.error("Drop all logging: thread mismatch for " + currLocalJobId);
currLocalJobErrs.setLength(0);
currThreadId = "ZXCVB";
}
}
}//TESTED
else if (arg0.getLoggerName().equals("org.apache.hadoop.mapred.LocalJobRunner")) {
if (arg0.getMessage().toString().equals(currLocalJobId)) {
String[] exceptionInfo = arg0.getThrowableStrRep();
if (null != exceptionInfo) {
currLocalJobErrs.append("Uncaught Exception in local job.\n");
for (String errLine: exceptionInfo) {
if (errLine.startsWith(" at org.apache.hadoop")) {
break;
}
currLocalJobErrs.append(errLine).append("\n");
}
}
}
}//TESTED (uncaught exception)
else if (!arg0.getLoggerName().startsWith("org.apache.hadoop")) {
if (arg0.getThreadName().equals(currThreadId)) {
if ((arg0.getLevel() == Level.ERROR)|| bTestMode) {
currLocalJobErrs.append('[').append(arg0.getLevel()).append("] ").
append(arg0.getLoggerName()).append(":").append(arg0.getLocationInformation().getLineNumber()).append(" ").
append(arg0.getMessage()).append("\n");
String[] exceptionInfo = arg0.getThrowableStrRep();
if (null != exceptionInfo) {
for (String errLine: exceptionInfo) {
if (errLine.startsWith(" at org.apache.hadoop")) {
break;
}
currLocalJobErrs.append(errLine).append("\n");
}
}//(end if exception information present)
}//(end if error or in test mode)
}//(end if this is my thread)
}//TESTED
}
}
| false | true | private void createConfigXML( Writer out, String title, String input, String fields, boolean isCustomTable, String outputDatabase, String output, String tempOutputCollection, String mapper, String reducer, String combiner, String query, List<ObjectId> communityIds, String outputKey, String outputValue, String arguments, Boolean incrementalMode) throws IOException
{
String dbserver = prop_general.getDatabaseServer();
output = outputDatabase + "." + tempOutputCollection;
int nSplits = 8;
int nDocsPerSplit = 12500;
//add communities to query if this is not a custom table
BasicDBObject oldQueryObj = null;
// Start with the old query:
if (query.startsWith("{")) {
oldQueryObj = (BasicDBObject) com.mongodb.util.JSON.parse(query);
}
else {
oldQueryObj = new BasicDBObject();
}
int nLimit = 0;
if (oldQueryObj.containsField("$limit")) {
nLimit = oldQueryObj.getInt("$limit");
oldQueryObj.remove("$limit");
}
if (oldQueryObj.containsField("$splits")) {
nSplits = oldQueryObj.getInt("$splits");
oldQueryObj.remove("$splits");
}
if (bLocalMode) { // If in local mode, then set this to infinity so we always run inside our limit/split version
// (since for some reason MongoInputFormat seems to fail on large collections)
nSplits = Integer.MAX_VALUE;
}
if (oldQueryObj.containsField("$docsPerSplit")) {
nDocsPerSplit = oldQueryObj.getInt("$docsPerSplit");
oldQueryObj.remove("$docsPerSplit");
}
oldQueryObj.remove("$fields");
oldQueryObj.remove("$output");
if (null != nDebugLimit) { // (debug mode override)
nLimit = nDebugLimit;
this.bTestMode = true;
}
boolean tmpIncMode = ( null != incrementalMode) && incrementalMode;
if ( !isCustomTable )
{
// Community Ids aren't indexed in the metadata collection, but source keys are, so we need to transform to that
BasicDBObject keyQuery = new BasicDBObject(SourcePojo.communityIds_, new BasicDBObject(DbManager.in_, communityIds));
if (oldQueryObj.containsField(DocumentPojo.sourceKey_) || input.startsWith("feature.")) {
// Source Key specified by user, stick communityIds check in for security
oldQueryObj.put(DocumentPojo.communityId_, new BasicDBObject(DbManager.in_, communityIds));
}
else { // Source key not specified by user, transform communities->sourcekeys
BasicDBObject keyFields = new BasicDBObject(SourcePojo.key_, 1);
DBCursor dbc = MongoDbManager.getIngest().getSource().find(keyQuery, keyFields);
if (dbc.count() > 500) {
// (too many source keys let's keep the query size sensible...)
oldQueryObj.put(DocumentPojo.communityId_, new BasicDBObject(DbManager.in_, communityIds));
}
else {
HashSet<String> sourceKeys = new HashSet<String>();
while (dbc.hasNext()) {
DBObject dbo = dbc.next();
String sourceKey = (String) dbo.get(SourcePojo.key_);
if (null != sourceKey) {
sourceKeys.add(sourceKey);
}
}
if (sourceKeys.isEmpty()) { // query returns empty
throw new RuntimeException("Communities contain no sources");
}
BasicDBObject newQueryClauseObj = new BasicDBObject(DbManager.in_, sourceKeys);
// Now combine the queries...
oldQueryObj.put(DocumentPojo.sourceKey_, newQueryClauseObj);
} // (end if too many source keys across the communities)
}//(end if need to break source keys down into communities)
query = oldQueryObj.toString();
}
else
{
//get the custom table (and database)
input = CustomOutputManager.getCustomDbAndCollection(input);
}
if ( arguments == null )
arguments = "";
// For logging in local mode:
currQuery = query;
// Generic configuration
out.write("<?xml version=\"1.0\"?>\n<configuration>");
// Mongo specific configuration
out.write(
"\n\t<property><!-- name of job shown in jobtracker --><name>mongo.job.name</name><value>"+title+"</value></property>"+
"\n\t<property><!-- run the job verbosely ? --><name>mongo.job.verbose</name><value>true</value></property>"+
"\n\t<property><!-- Run the job in the foreground and wait for response, or background it? --><name>mongo.job.background</name><value>false</value></property>"+
"\n\t<property><!-- If you are reading from mongo, the URI --><name>mongo.input.uri</name><value>mongodb://"+dbserver+"/"+input+"</value></property>"+
"\n\t<property><!-- If you are writing to mongo, the URI --><name>mongo.output.uri</name><value>mongodb://"+dbserver+"/"+output+"</value> </property>"+
"\n\t<property><!-- The query, in JSON, to execute [OPTIONAL] --><name>mongo.input.query</name><value>" + query + "</value></property>"+
"\n\t<property><!-- The fields, in JSON, to read [OPTIONAL] --><name>mongo.input.fields</name><value>"+( (fields==null) ? ("") : fields )+"</value></property>"+
"\n\t<property><!-- A JSON sort specification for read [OPTIONAL] --><name>mongo.input.sort</name><value></value></property>"+
"\n\t<property><!-- The number of documents to limit to for read [OPTIONAL] --><name>mongo.input.limit</name><value>" + nLimit + "</value><!-- 0 == no limit --></property>"+
"\n\t<property><!-- The number of documents to skip in read [OPTIONAL] --><!-- TODO - Are we running limit() or skip() first? --><name>mongo.input.skip</name><value>0</value> <!-- 0 == no skip --></property>"+
"\n\t<property><!-- Class for the mapper --><name>mongo.job.mapper</name><value>"+ mapper+"</value></property>"+
"\n\t<property><!-- Reducer class --><name>mongo.job.reducer</name><value>"+reducer+"</value></property>"+
"\n\t<property><!-- InputFormat Class --><name>mongo.job.input.format</name><value>com.ikanow.infinit.e.data_model.custom.InfiniteMongoInputFormat</value></property>"+
"\n\t<property><!-- OutputFormat Class --><name>mongo.job.output.format</name><value>com.ikanow.infinit.e.data_model.custom.InfiniteMongoOutputFormat</value></property>"+
"\n\t<property><!-- Output key class for the output format --><name>mongo.job.output.key</name><value>"+outputKey+"</value></property>"+
"\n\t<property><!-- Output value class for the output format --><name>mongo.job.output.value</name><value>"+outputValue+"</value></property>"+
"\n\t<property><!-- Output key class for the mapper [optional] --><name>mongo.job.mapper.output.key</name><value></value></property>"+
"\n\t<property><!-- Output value class for the mapper [optional] --><name>mongo.job.mapper.output.value</name><value></value></property>"+
"\n\t<property><!-- Class for the combiner [optional] --><name>mongo.job.combiner</name><value>"+combiner+"</value></property>"+
"\n\t<property><!-- Partitioner class [optional] --><name>mongo.job.partitioner</name><value></value></property>"+
"\n\t<property><!-- Sort Comparator class [optional] --><name>mongo.job.sort_comparator</name><value></value></property>"+
"\n\t<property><!-- Split Size [optional] --><name>mongo.input.split_size</name><value>32</value></property>"
);
// Infinit.e specific configuration
out.write(
"\n\t<property><!-- User Arguments [optional] --><name>arguments</name><value>"+ StringEscapeUtils.escapeXml(arguments)+"</value></property>"+
"\n\t<property><!-- Maximum number of splits [optional] --><name>max.splits</name><value>"+nSplits+"</value></property>"+
"\n\t<property><!-- Maximum number of docs per split [optional] --><name>max.docs.per.split</name><value>"+nDocsPerSplit+"</value></property>"+
"\n\t<property><!-- Infinit.e incremental mode [optional] --><name>update.incremental</name><value>"+tmpIncMode+"</value></property>"
);
// Closing thoughts:
out.write("\n</configuration>");
out.flush();
out.close();
}
| private void createConfigXML( Writer out, String title, String input, String fields, boolean isCustomTable, String outputDatabase, String output, String tempOutputCollection, String mapper, String reducer, String combiner, String query, List<ObjectId> communityIds, String outputKey, String outputValue, String arguments, Boolean incrementalMode) throws IOException
{
String dbserver = prop_general.getDatabaseServer();
output = outputDatabase + "." + tempOutputCollection;
int nSplits = 8;
int nDocsPerSplit = 12500;
//add communities to query if this is not a custom table
BasicDBObject oldQueryObj = null;
// Start with the old query:
if (query.startsWith("{")) {
oldQueryObj = (BasicDBObject) com.mongodb.util.JSON.parse(query);
}
else {
oldQueryObj = new BasicDBObject();
}
int nLimit = 0;
if (oldQueryObj.containsField("$limit")) {
nLimit = oldQueryObj.getInt("$limit");
oldQueryObj.remove("$limit");
}
if (oldQueryObj.containsField("$splits")) {
nSplits = oldQueryObj.getInt("$splits");
oldQueryObj.remove("$splits");
}
if (bLocalMode) { // If in local mode, then set this to a large number so we always run inside our limit/split version
// (since for some reason MongoInputFormat seems to fail on large collections)
nSplits = 10000000; // (10m)
}
if (oldQueryObj.containsField("$docsPerSplit")) {
nDocsPerSplit = oldQueryObj.getInt("$docsPerSplit");
oldQueryObj.remove("$docsPerSplit");
}
oldQueryObj.remove("$fields");
oldQueryObj.remove("$output");
if (null != nDebugLimit) { // (debug mode override)
nLimit = nDebugLimit;
this.bTestMode = true;
}
boolean tmpIncMode = ( null != incrementalMode) && incrementalMode;
if ( !isCustomTable )
{
// Community Ids aren't indexed in the metadata collection, but source keys are, so we need to transform to that
BasicDBObject keyQuery = new BasicDBObject(SourcePojo.communityIds_, new BasicDBObject(DbManager.in_, communityIds));
if (oldQueryObj.containsField(DocumentPojo.sourceKey_) || input.startsWith("feature.")) {
// Source Key specified by user, stick communityIds check in for security
oldQueryObj.put(DocumentPojo.communityId_, new BasicDBObject(DbManager.in_, communityIds));
}
else { // Source key not specified by user, transform communities->sourcekeys
BasicDBObject keyFields = new BasicDBObject(SourcePojo.key_, 1);
DBCursor dbc = MongoDbManager.getIngest().getSource().find(keyQuery, keyFields);
if (dbc.count() > 500) {
// (too many source keys let's keep the query size sensible...)
oldQueryObj.put(DocumentPojo.communityId_, new BasicDBObject(DbManager.in_, communityIds));
}
else {
HashSet<String> sourceKeys = new HashSet<String>();
while (dbc.hasNext()) {
DBObject dbo = dbc.next();
String sourceKey = (String) dbo.get(SourcePojo.key_);
if (null != sourceKey) {
sourceKeys.add(sourceKey);
}
}
if (sourceKeys.isEmpty()) { // query returns empty
throw new RuntimeException("Communities contain no sources");
}
BasicDBObject newQueryClauseObj = new BasicDBObject(DbManager.in_, sourceKeys);
// Now combine the queries...
oldQueryObj.put(DocumentPojo.sourceKey_, newQueryClauseObj);
} // (end if too many source keys across the communities)
}//(end if need to break source keys down into communities)
query = oldQueryObj.toString();
}
else
{
//get the custom table (and database)
input = CustomOutputManager.getCustomDbAndCollection(input);
}
if ( arguments == null )
arguments = "";
// For logging in local mode:
currQuery = query;
// Generic configuration
out.write("<?xml version=\"1.0\"?>\n<configuration>");
// Mongo specific configuration
out.write(
"\n\t<property><!-- name of job shown in jobtracker --><name>mongo.job.name</name><value>"+title+"</value></property>"+
"\n\t<property><!-- run the job verbosely ? --><name>mongo.job.verbose</name><value>true</value></property>"+
"\n\t<property><!-- Run the job in the foreground and wait for response, or background it? --><name>mongo.job.background</name><value>false</value></property>"+
"\n\t<property><!-- If you are reading from mongo, the URI --><name>mongo.input.uri</name><value>mongodb://"+dbserver+"/"+input+"</value></property>"+
"\n\t<property><!-- If you are writing to mongo, the URI --><name>mongo.output.uri</name><value>mongodb://"+dbserver+"/"+output+"</value> </property>"+
"\n\t<property><!-- The query, in JSON, to execute [OPTIONAL] --><name>mongo.input.query</name><value>" + query + "</value></property>"+
"\n\t<property><!-- The fields, in JSON, to read [OPTIONAL] --><name>mongo.input.fields</name><value>"+( (fields==null) ? ("") : fields )+"</value></property>"+
"\n\t<property><!-- A JSON sort specification for read [OPTIONAL] --><name>mongo.input.sort</name><value></value></property>"+
"\n\t<property><!-- The number of documents to limit to for read [OPTIONAL] --><name>mongo.input.limit</name><value>" + nLimit + "</value><!-- 0 == no limit --></property>"+
"\n\t<property><!-- The number of documents to skip in read [OPTIONAL] --><!-- TODO - Are we running limit() or skip() first? --><name>mongo.input.skip</name><value>0</value> <!-- 0 == no skip --></property>"+
"\n\t<property><!-- Class for the mapper --><name>mongo.job.mapper</name><value>"+ mapper+"</value></property>"+
"\n\t<property><!-- Reducer class --><name>mongo.job.reducer</name><value>"+reducer+"</value></property>"+
"\n\t<property><!-- InputFormat Class --><name>mongo.job.input.format</name><value>com.ikanow.infinit.e.data_model.custom.InfiniteMongoInputFormat</value></property>"+
"\n\t<property><!-- OutputFormat Class --><name>mongo.job.output.format</name><value>com.ikanow.infinit.e.data_model.custom.InfiniteMongoOutputFormat</value></property>"+
"\n\t<property><!-- Output key class for the output format --><name>mongo.job.output.key</name><value>"+outputKey+"</value></property>"+
"\n\t<property><!-- Output value class for the output format --><name>mongo.job.output.value</name><value>"+outputValue+"</value></property>"+
"\n\t<property><!-- Output key class for the mapper [optional] --><name>mongo.job.mapper.output.key</name><value></value></property>"+
"\n\t<property><!-- Output value class for the mapper [optional] --><name>mongo.job.mapper.output.value</name><value></value></property>"+
"\n\t<property><!-- Class for the combiner [optional] --><name>mongo.job.combiner</name><value>"+combiner+"</value></property>"+
"\n\t<property><!-- Partitioner class [optional] --><name>mongo.job.partitioner</name><value></value></property>"+
"\n\t<property><!-- Sort Comparator class [optional] --><name>mongo.job.sort_comparator</name><value></value></property>"+
"\n\t<property><!-- Split Size [optional] --><name>mongo.input.split_size</name><value>32</value></property>"
);
// Infinit.e specific configuration
out.write(
"\n\t<property><!-- User Arguments [optional] --><name>arguments</name><value>"+ StringEscapeUtils.escapeXml(arguments)+"</value></property>"+
"\n\t<property><!-- Maximum number of splits [optional] --><name>max.splits</name><value>"+nSplits+"</value></property>"+
"\n\t<property><!-- Maximum number of docs per split [optional] --><name>max.docs.per.split</name><value>"+nDocsPerSplit+"</value></property>"+
"\n\t<property><!-- Infinit.e incremental mode [optional] --><name>update.incremental</name><value>"+tmpIncMode+"</value></property>"
);
// Closing thoughts:
out.write("\n</configuration>");
out.flush();
out.close();
}
|
diff --git a/orion_viewer/src/universe/constellation/orion/viewer/Action.java b/orion_viewer/src/universe/constellation/orion/viewer/Action.java
index 051dae4..727ad7b 100644
--- a/orion_viewer/src/universe/constellation/orion/viewer/Action.java
+++ b/orion_viewer/src/universe/constellation/orion/viewer/Action.java
@@ -1,414 +1,415 @@
/*
* Orion Viewer - pdf, djvu, xps and cbz file viewer for android devices
*
* Copyright (C) 2011-2012 Michael Bogdanov
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package universe.constellation.orion.viewer;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.widget.Toast;
import universe.constellation.orion.viewer.outline.OutlineActivity;
import universe.constellation.orion.viewer.outline.OutlineItem;
import universe.constellation.orion.viewer.prefs.OrionApplication;
import universe.constellation.orion.viewer.prefs.OrionBookPreferences;
import universe.constellation.orion.viewer.prefs.OrionPreferenceActivity;
import universe.constellation.orion.viewer.prefs.TemporaryOptions;
import java.util.HashMap;
/**
* User: mike
* Date: 06.01.12
* Time: 18:28
*/
public enum Action {
NONE (R.string.action_none, R.integer.action_none) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
//none action
}
} ,
MENU (R.string.action_menu, R.integer.action_menu) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
activity.openOptionsMenu();
}
} ,
NEXT (R.string.action_next_page, R.integer.action_next_page) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
if (controller != null) {
controller.drawNext();
}
}
} ,
PREV (R.string.action_prev_page, R.integer.action_prev_page) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
if (controller != null) {
controller.drawPrev();
}
}
} ,
NEXT10 (R.string.action_next_10, R.integer.action_next_10) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
int page = controller.getCurrentPage() + 10;
if (page > controller.getPageCount() - 1) {
page = controller.getPageCount() - 1;
}
controller.drawPage(page);
}
},
PREV10 (R.string.action_prev_10, R.integer.action_prev_10) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
int page = controller.getCurrentPage() - 10;
if (page < 0) {
page = 0;
}
controller.drawPage(page);
}
},
FIRST_PAGE (R.string.action_first_page, R.integer.action_first_page) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
if (controller != null) {
controller.drawPage(0);
}
}
} ,
LAST_PAGE (R.string.action_last_page, R.integer.action_last_page) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
if (controller != null) {
controller.drawPage(controller.getPageCount() - 1);
}
}
} ,
SHOW_OUTLINE (R.string.action_outline, R.integer.action_open_outline) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
Common.d("In Show Outline!");
OutlineItem[] outline = controller.getOutline();
if (outline != null && outline.length != 0) {
// final Dialog dialog = new Dialog(activity);
// dialog.setTitle(R.string.table_of_contents);
// LinearLayout contents = new LinearLayout(activity);
// contents.setOrientation(LinearLayout.VERTICAL);
// LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
// params.leftMargin = 5;
// params.rightMargin = 5;
// params.bottomMargin = 2;
// params.topMargin = 2;
//
// InMemoryTreeStateManager<Integer> manager = new InMemoryTreeStateManager<Integer>();
// manager.setVisibleByDefault(false);
// OutlineAdapter.SetManagerFromOutlineItems(manager, outline);
// TreeViewList tocTree = new TreeViewList(activity);
// tocTree.setAdapter(new OutlineAdapter(controller, activity, dialog, manager, outline));
//
// contents.addView(tocTree, params);
// dialog.setContentView(contents);
// dialog.show();
activity.getOrionContext().getTempOptions().outline = outline;
Intent intent = new Intent(activity, OutlineActivity.class);
activity.startActivityForResult(intent, OrionViewerActivity.OPEN_BOOKMARK_ACTIVITY_RESULT);
} else {
activity.showWarning(R.string.warn_no_outline);
}
}
},
SELECT_TEXT (R.string.action_select_text, R.integer.action_select_text) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
activity.textSelectionMode();
}
},
ADD_BOOKMARK (R.string.action_add_bookmark, R.integer.action_add_bookmark) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
activity.showOrionDialog(OrionViewerActivity.ADD_BOOKMARK_SCREEN, this, parameter);
}
},
OPEN_BOOKMARKS (R.string.action_open_bookmarks, R.integer.action_open_bookmarks) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
Intent bookmark = new Intent(activity.getApplicationContext(), OrionBookmarkActivity.class);
bookmark.putExtra(OrionBookmarkActivity.BOOK_ID, activity.getBookId());
activity.startActivityForResult(bookmark, OrionViewerActivity.OPEN_BOOKMARK_ACTIVITY_RESULT);
}
},
DAY_NIGHT (R.string.action_day_night_mode, R.integer.action_day_night_mode) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
activity.changeDayNightMode();
}
},
BOOK_OPTIONS (R.string.action_book_options, R.integer.action_book_options) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
Intent intent = new Intent(activity, OrionBookPreferences.class);
activity.startActivity(intent);
}
},
ZOOM (R.string.action_zoom_page, R.integer.action_zoom_page) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
activity.showOrionDialog(OrionViewerActivity.ZOOM_SCREEN, null, null);
}
},
PAGE_LAYOUT (R.string.action_layout_page, R.integer.action_page_layout) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
activity.showOrionDialog(OrionViewerActivity.PAGE_LAYOUT_SCREEN, null, null);
}
},
CROP (R.string.action_crop_page, R.integer.action_crop_page) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
activity.showOrionDialog(OrionViewerActivity.CROP_SCREEN, null, null);
}
},
GOTO (R.string.action_goto_page, R.integer.action_goto_page) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
activity.showOrionDialog(OrionViewerActivity.PAGE_SCREEN, this, null);
}
},
ROTATION (R.string.action_rotation_page, R.integer.action_rotation_page) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
activity.showOrionDialog(OrionViewerActivity.ROTATION_SCREEN, null, null);
}
},
ROTATE_90 (R.string.action_rotate_90, R.integer.action_rotate_90) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
//controller.setRotation((controller.getRotation() - 1) % 2);
}
},
ROTATE_270 (R.string.action_rotate_270, R.integer.action_rotate_270) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
//controller.setRotation((controller.getRotation() + 1) % 2);
}
},
DICTIONARY (R.string.action_dictionary, R.integer.action_dictionary) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
String dict = activity.getGlobalOptions().getDictionary();
String action = null;
Intent intent = new Intent();
String queryText = null;
if ("FORA".equals(dict)) {
action = "com.ngc.fora.action.LOOKUP";
queryText = "HEADWORD";
} else if ("COLORDICT".equals(dict)) {
action = "colordict.intent.action.SEARCH";
queryText = "EXTRA_QUERY";
} else if ("AARD".equals(dict)) {
- action = Intent.ACTION_MAIN;
+ action = Intent.ACTION_SEARCH;
intent.setClassName("aarddict.android", "aarddict.android.LookupActivity");
queryText = "query";
+ parameter = parameter == null ? "" : parameter;
}
if (action != null) {
intent.setAction(action);
if (parameter != null) {
intent.putExtra(queryText, (String) parameter);
}
try {
activity.startActivity(intent);
} catch (ActivityNotFoundException ex) {
Common.d(ex);
activity.showWarning("Couldn't find dictionary: " + action);
}
}
}
},
OPEN_BOOK (R.string.action_open, R.integer.action_open_book) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
Intent intent = new Intent(activity, OrionFileManagerActivity.class);
intent.putExtra(OrionBaseActivity.DONT_OPEN_RECENT, true);
activity.startActivity(intent);
}
},
OPTIONS (R.string.action_options_page, R.integer.action_options_page) {
@Override
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
Intent intent = new Intent(activity, OrionPreferenceActivity.class);
activity.startActivity(intent);
}
},
INVERSE_CROP (R.string.action_inverse_crops, R.integer.action_inverse_crop) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
TemporaryOptions opts = activity.getOrionContext().getTempOptions();
opts.inverseCropping = !opts.inverseCropping;
String title = activity.getResources().getString(R.string.action_inverse_crops) + ":" +(opts.inverseCropping ? "inverted" : "normal");
Toast.makeText(activity.getApplicationContext(), title, Toast.LENGTH_SHORT).show();
}
},
SWITCH_CROP (R.string.action_switch_long_crop, R.integer.action_switch_long_crop) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
TemporaryOptions opts = activity.getOrionContext().getTempOptions();
opts.switchCropping = !opts.switchCropping;
String title = activity.getResources().getString(R.string.action_switch_long_crop) + ":" + (opts.switchCropping ? "big" : "small");
Toast.makeText(activity.getApplicationContext(), title, Toast.LENGTH_SHORT).show();
}
},
CROP_LEFT (R.string.action_crop_left, R.integer.action_crop_left) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
updateMargin(controller, true, 0);
}
},
UNCROP_LEFT (R.string.action_uncrop_left, R.integer.action_uncrop_left) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
updateMargin(controller, false, 0);
}
},
CROP_RIGHT (R.string.action_crop_right, R.integer.action_crop_right) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
updateMargin(controller, true, 1);
}
},
UNCROP_RIGHT (R.string.action_uncrop_right, R.integer.action_uncrop_right) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
updateMargin(controller, false, 1);
}
},
CROP_TOP (R.string.action_crop_top, R.integer.action_crop_top) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
updateMargin(controller, true, 2);
}
},
UNCROP_TOP (R.string.action_uncrop_top, R.integer.action_uncrop_top) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
updateMargin(controller, false, 2);
}
},
CROP_BOTTOM (R.string.action_crop_bottom, R.integer.action_crop_bottom) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
updateMargin(controller, true, 3);
}
},
UNCROP_BOTTOM (R.string.action_uncrop_bottom, R.integer.action_uncrop_bottom) {
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
updateMargin(controller, false, 3);
}
};
private static final HashMap<Integer, Action> actions = new HashMap<Integer, Action>();
static {
Action [] values = values();
for (int i = 0; i < values.length; i++) {
Action value = values[i];
actions.put(value.code, value);
}
}
private final int name;
private final int code;
Action(int nameId, int resId) {
this.name = nameId;
this.code = OrionApplication.instance.getResources().getInteger(resId);
}
public int getName() {
return name;
}
public int getCode() {
return code;
}
public static Action getAction(int code) {
Action result = actions.get(code);
return result != null ? result : NONE;
}
public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
}
protected void updateMargin(Controller controller, boolean isCrop, int index) {
if (controller.isEvenCropEnabled() && controller.isEvenPage()) {
if (index == 0 || index == 1) {
index += 4;
}
}
int [] margins = new int[6];
controller.getMargins(margins);
OrionApplication context = controller.getActivity().getOrionContext();
TemporaryOptions tempOpts = context.getTempOptions();
if (tempOpts.inverseCropping) {
isCrop = !isCrop;
}
int delta = tempOpts.switchCropping ? context.getOptions().getLongCrop() : 1;
margins[index] += isCrop ? delta : -delta;
if (margins[index] > OrionViewerActivity.CROP_RESTRICTION_MAX) {
margins[index] = OrionViewerActivity.CROP_RESTRICTION_MAX;
}
if (margins[index] < OrionViewerActivity.CROP_RESTRICTION_MIN) {
margins[index] = OrionViewerActivity.CROP_RESTRICTION_MIN;
}
controller.changeMargins(margins);
}
}
| false | true | public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
String dict = activity.getGlobalOptions().getDictionary();
String action = null;
Intent intent = new Intent();
String queryText = null;
if ("FORA".equals(dict)) {
action = "com.ngc.fora.action.LOOKUP";
queryText = "HEADWORD";
} else if ("COLORDICT".equals(dict)) {
action = "colordict.intent.action.SEARCH";
queryText = "EXTRA_QUERY";
} else if ("AARD".equals(dict)) {
action = Intent.ACTION_MAIN;
intent.setClassName("aarddict.android", "aarddict.android.LookupActivity");
queryText = "query";
}
if (action != null) {
intent.setAction(action);
if (parameter != null) {
intent.putExtra(queryText, (String) parameter);
}
try {
activity.startActivity(intent);
} catch (ActivityNotFoundException ex) {
Common.d(ex);
activity.showWarning("Couldn't find dictionary: " + action);
}
}
}
| public void doAction(Controller controller, OrionViewerActivity activity, Object parameter) {
String dict = activity.getGlobalOptions().getDictionary();
String action = null;
Intent intent = new Intent();
String queryText = null;
if ("FORA".equals(dict)) {
action = "com.ngc.fora.action.LOOKUP";
queryText = "HEADWORD";
} else if ("COLORDICT".equals(dict)) {
action = "colordict.intent.action.SEARCH";
queryText = "EXTRA_QUERY";
} else if ("AARD".equals(dict)) {
action = Intent.ACTION_SEARCH;
intent.setClassName("aarddict.android", "aarddict.android.LookupActivity");
queryText = "query";
parameter = parameter == null ? "" : parameter;
}
if (action != null) {
intent.setAction(action);
if (parameter != null) {
intent.putExtra(queryText, (String) parameter);
}
try {
activity.startActivity(intent);
} catch (ActivityNotFoundException ex) {
Common.d(ex);
activity.showWarning("Couldn't find dictionary: " + action);
}
}
}
|
diff --git a/src/java/com/eviware/x/impl/swing/SwingFileDialogs.java b/src/java/com/eviware/x/impl/swing/SwingFileDialogs.java
index e95d20f69..8a8248849 100644
--- a/src/java/com/eviware/x/impl/swing/SwingFileDialogs.java
+++ b/src/java/com/eviware/x/impl/swing/SwingFileDialogs.java
@@ -1,131 +1,131 @@
/*
* soapUI, copyright (C) 2004-2008 eviware.com
*
* soapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details at gnu.org.
*/
package com.eviware.x.impl.swing;
import java.awt.Component;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JFileChooser;
import com.eviware.soapui.support.ExtensionFileFilter;
import com.eviware.x.dialogs.XFileDialogs;
/**
*
* @author Lars
*/
public class SwingFileDialogs implements XFileDialogs
{
private static Component parent;
private static Map<Object, JFileChooser> choosers = new HashMap<Object, JFileChooser>();
public SwingFileDialogs(Component parent)
{
SwingFileDialogs.parent = parent;
}
public static synchronized JFileChooser getChooser(Object action)
{
action = null;
JFileChooser chooser = choosers.get(action);
if( chooser == null )
{
chooser = new JFileChooser();
choosers.put(action, chooser);
}
chooser.resetChoosableFileFilters();
return chooser;
}
public static Component getParent()
{
return parent;
}
public File saveAs(Object action, String title)
{
return saveAs(action, title, null, null, null);
}
public File saveAs(Object action, String title, String extension, String fileType, File defaultFile)
{
JFileChooser chooser = getChooser(action);
chooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
chooser.setDialogTitle(title);
chooser.setAcceptAllFileFilterUsed( true );
if(extension != null && fileType != null)
chooser.setFileFilter( new ExtensionFileFilter( extension, fileType ));
if(defaultFile != null)
chooser.setSelectedFile(defaultFile);
if (chooser.showSaveDialog(getParent()) != JFileChooser.APPROVE_OPTION)
return null;
return chooser.getSelectedFile();
}
public File open(Object action, String title, String extension, String fileType, String current)
{
return openFile( action, title, extension, fileType, current );
}
public static File openFile(Object action, String title, String extension, String fileType, String current)
{
JFileChooser chooser = getChooser(action);
- chooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES);
+ chooser.setFileSelectionMode( JFileChooser.FILES_ONLY);
chooser.setDialogTitle(title);
chooser.setAcceptAllFileFilterUsed( true );
if( current != null )
{
File file = new File( current);
if( file.isDirectory())
chooser.setCurrentDirectory(file);
else
chooser.setSelectedFile( file );
}
if(extension != null && fileType != null)
chooser.setFileFilter( new ExtensionFileFilter( extension, fileType ));
if (chooser.showOpenDialog(getParent()) != JFileChooser.APPROVE_OPTION)
return null;
return chooser.getSelectedFile();
}
public File openXML(Object action, String title)
{
return open(action, title, ".xml", "XML Files (*.xml)", null);
}
public File openDirectory(Object action, String title, File defaultDirectory)
{
JFileChooser chooser = getChooser(action);
chooser.setDialogTitle(title);
chooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
if(defaultDirectory != null)
chooser.setCurrentDirectory( defaultDirectory );
if (chooser.showOpenDialog(getParent()) != JFileChooser.APPROVE_OPTION)
return null;
return chooser.getSelectedFile();
}
}
| true | true | public static File openFile(Object action, String title, String extension, String fileType, String current)
{
JFileChooser chooser = getChooser(action);
chooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES);
chooser.setDialogTitle(title);
chooser.setAcceptAllFileFilterUsed( true );
if( current != null )
{
File file = new File( current);
if( file.isDirectory())
chooser.setCurrentDirectory(file);
else
chooser.setSelectedFile( file );
}
if(extension != null && fileType != null)
chooser.setFileFilter( new ExtensionFileFilter( extension, fileType ));
if (chooser.showOpenDialog(getParent()) != JFileChooser.APPROVE_OPTION)
return null;
return chooser.getSelectedFile();
}
| public static File openFile(Object action, String title, String extension, String fileType, String current)
{
JFileChooser chooser = getChooser(action);
chooser.setFileSelectionMode( JFileChooser.FILES_ONLY);
chooser.setDialogTitle(title);
chooser.setAcceptAllFileFilterUsed( true );
if( current != null )
{
File file = new File( current);
if( file.isDirectory())
chooser.setCurrentDirectory(file);
else
chooser.setSelectedFile( file );
}
if(extension != null && fileType != null)
chooser.setFileFilter( new ExtensionFileFilter( extension, fileType ));
if (chooser.showOpenDialog(getParent()) != JFileChooser.APPROVE_OPTION)
return null;
return chooser.getSelectedFile();
}
|
diff --git a/api/src/test/java/org/openmrs/module/tracnetreportingsdmx/TracnetReportTest.java b/api/src/test/java/org/openmrs/module/tracnetreportingsdmx/TracnetReportTest.java
index c6cfae0..09c37d0 100644
--- a/api/src/test/java/org/openmrs/module/tracnetreportingsdmx/TracnetReportTest.java
+++ b/api/src/test/java/org/openmrs/module/tracnetreportingsdmx/TracnetReportTest.java
@@ -1,96 +1,97 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.tracnetreportingsdmx;
import java.io.ByteArrayOutputStream;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Test;
import org.openmrs.GlobalProperty;
import org.openmrs.api.context.Context;
import org.openmrs.module.reporting.common.DateUtil;
import org.openmrs.module.reporting.evaluation.EvaluationContext;
import org.openmrs.module.reporting.report.ReportData;
import org.openmrs.module.reporting.report.ReportDesign;
import org.openmrs.module.reporting.report.definition.ReportDefinition;
import org.openmrs.module.reporting.report.definition.service.ReportDefinitionService;
import org.openmrs.module.reporting.report.renderer.ReportRenderer;
import org.openmrs.module.reporting.report.service.ReportService;
import org.openmrs.module.reporting.report.util.ReportUtil;
import org.openmrs.test.BaseContextSensitiveTest;
import org.openmrs.test.BaseModuleContextSensitiveTest;
import org.openmrs.test.SkipBaseSetup;
/**
* Tests the production of the TracNet Report Definition to SDMX
*/
@SkipBaseSetup
public class TracnetReportTest extends BaseModuleContextSensitiveTest {
Log log = LogFactory.getLog(getClass());
/**
* @see BaseContextSensitiveTest#useInMemoryDatabase()
*/
@Override
public Boolean useInMemoryDatabase() {
return false;
}
@Before
public void setup() throws Exception {
authenticate();
setGlobalProperty("tracnetreportingsdmx.locationDataProviderId", "1234");
setGlobalProperty("tracnetreportingsdmx.confirmation_email_address", "[email protected]");
setGlobalProperty("tracnetreportingsdmx.email_from", "[email protected]");
setGlobalProperty("tracnetreportingsdmx.email_to", "[email protected]");
}
/**
* Tests the TracnetReport
*/
@Test
public void shouldGenerateTracnetReport() throws Exception {
ReportDefinition reportDefinition = TracnetReport.getTracnetReportDefinition(true);
EvaluationContext context = new EvaluationContext();
context.addParameterValue("startDate", DateUtil.getDateTime(2011, 1, 1));
context.addParameterValue("endDate", DateUtil.getDateTime(2011, 1, 31));
ReportDefinitionService rs = Context.getService(ReportDefinitionService.class);
ReportData data = rs.evaluate(reportDefinition, context);
ReportDesign design = Context.getService(ReportService.class).getReportDesignByUuid(TracnetReport.REPORT_DESIGN_UUID);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ReportRenderer renderer = design.getRendererType().newInstance();
renderer.render(data, design.getUuid(), baos);
baos.close();
String fileName = renderer.getFilename(reportDefinition, design.getUuid());
- ReportUtil.writeByteArrayToFile(new File("/home/mseaton/Desktop", fileName), baos.toByteArray());
+ File outFile = File.createTempFile(fileName, null);
+ ReportUtil.writeByteArrayToFile(outFile, baos.toByteArray());
}
private void setGlobalProperty(String name, String value) {
GlobalProperty gp = Context.getAdministrationService().getGlobalPropertyObject(name);
if (gp == null) {
gp = new GlobalProperty(name);
}
gp.setPropertyValue(value);
Context.getAdministrationService().saveGlobalProperty(gp);
}
}
| true | true | public void shouldGenerateTracnetReport() throws Exception {
ReportDefinition reportDefinition = TracnetReport.getTracnetReportDefinition(true);
EvaluationContext context = new EvaluationContext();
context.addParameterValue("startDate", DateUtil.getDateTime(2011, 1, 1));
context.addParameterValue("endDate", DateUtil.getDateTime(2011, 1, 31));
ReportDefinitionService rs = Context.getService(ReportDefinitionService.class);
ReportData data = rs.evaluate(reportDefinition, context);
ReportDesign design = Context.getService(ReportService.class).getReportDesignByUuid(TracnetReport.REPORT_DESIGN_UUID);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ReportRenderer renderer = design.getRendererType().newInstance();
renderer.render(data, design.getUuid(), baos);
baos.close();
String fileName = renderer.getFilename(reportDefinition, design.getUuid());
ReportUtil.writeByteArrayToFile(new File("/home/mseaton/Desktop", fileName), baos.toByteArray());
}
| public void shouldGenerateTracnetReport() throws Exception {
ReportDefinition reportDefinition = TracnetReport.getTracnetReportDefinition(true);
EvaluationContext context = new EvaluationContext();
context.addParameterValue("startDate", DateUtil.getDateTime(2011, 1, 1));
context.addParameterValue("endDate", DateUtil.getDateTime(2011, 1, 31));
ReportDefinitionService rs = Context.getService(ReportDefinitionService.class);
ReportData data = rs.evaluate(reportDefinition, context);
ReportDesign design = Context.getService(ReportService.class).getReportDesignByUuid(TracnetReport.REPORT_DESIGN_UUID);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ReportRenderer renderer = design.getRendererType().newInstance();
renderer.render(data, design.getUuid(), baos);
baos.close();
String fileName = renderer.getFilename(reportDefinition, design.getUuid());
File outFile = File.createTempFile(fileName, null);
ReportUtil.writeByteArrayToFile(outFile, baos.toByteArray());
}
|
diff --git a/Experimental/src/sectionOne/BalloonApplet.java b/Experimental/src/sectionOne/BalloonApplet.java
index 7ce89bf..d9e4dc1 100644
--- a/Experimental/src/sectionOne/BalloonApplet.java
+++ b/Experimental/src/sectionOne/BalloonApplet.java
@@ -1,206 +1,206 @@
package sectionOne;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;//import java.awt.event.*; goes with ActionListener and actionPerformed
public class BalloonApplet extends Applet
implements ActionListener//import java.awt.event.*; goes with ActionListener and actionPerformed
{//variable & object declarations and initializations
private static final long serialVersionUID = 1L; //serialID, don't touch
Button east, west, north, south, northWest, northEast, southWest, southEast, farUL, farUR, farLL, farLR, midpoint;
public static final int DISPLAY_WIDTH = 600;
public static final int DISPLAY_HEIGHT = 600;
// Set to true to print coordinates of balloon to console /////
public static final boolean CONSOLE_LOGGING_ENABLED = false; //
///////////////////////////////////////////////////////////////
private int startX = 275;
private int startY = 212;
public void init()
{
west = new Button ("West");
add (west);
west.addActionListener (this);
north = new Button ("North");
add (north);
north.addActionListener (this);
south = new Button ("South");
add (south);
south.addActionListener (this);
east = new Button ("East");
add (east);
east.addActionListener (this);
northWest = new Button ("Northwest");
add (northWest);
northWest.addActionListener (this);
northEast = new Button ("Northeast");
add (northEast);
northEast.addActionListener (this);
southWest = new Button ("Southwest");
add (southWest);
southWest.addActionListener (this);
- southEast = new Button ("SouthEast");
+ southEast = new Button ("Southeast");
add (southEast);
southEast.addActionListener (this);
farUL = new Button ("Go to upper-left corner");
add (farUL);
farUL.addActionListener (this);
farUR = new Button ("Go to upper-right corner");
add (farUR);
farUR.addActionListener (this);
farLL = new Button ("Go to lower-left corner");
add (farLL);
farLL.addActionListener (this);
farLR = new Button ("Go to lower-right corner");
add (farLR);
farLR.addActionListener (this);
midpoint = new Button ("Go to the exact center");
add (midpoint);
midpoint.addActionListener (this);
if (CONSOLE_LOGGING_ENABLED)
{
System.out.println("Console tracking enabled.");
System.out.println("");
System.out.println(" x | y ");
System.out.println("--------+--------");
}
}// endInit
public void paint(Graphics g)
{
resize(DISPLAY_WIDTH,500);
resize(DISPLAY_HEIGHT,500);
setBackground(Color.CYAN);
g.setColor(Color.BLACK);
g.fillOval(startX,startY,50,75);//no longer a weird balloon
}//endPaint
public void actionPerformed(ActionEvent clic)//import java.awt.event.*; goes with ActionListener and actionPerformed
{
if (clic.getSource()== east)
goEast();
else if (clic.getSource()== west)
goWest();
else if (clic.getSource()== north)
goNorth();
else if (clic.getSource()== south)
goSouth();
else if (clic.getSource()== northWest)
goNorthWest();
else if (clic.getSource()== northEast)
goNorthEast();
else if (clic.getSource()== southWest)
goSouthWest();
else if (clic.getSource()== southEast)
goSouthEast();
else if (clic.getSource()== farUL)
goToULCorner();
else if (clic.getSource()== farUR)
goToURCorner();
else if (clic.getSource()== farLL)
goToLLCorner();
else if (clic.getSource()== farLR)
goToLRCorner();
else if (clic.getSource()== midpoint)
goToCenter();
if (CONSOLE_LOGGING_ENABLED)
System.out.println(" " + startX + "\t| " + startY);
repaint();
}//endActionPerformed
public void goEast()
{
startX+=5;
}
public void goWest()
{
startX-=5;
}
public void goNorth()
{
startY-=2;
}
public void goSouth()
{
startY+=2;
}
public void goNorthEast()
{
startX+=10;
startY-=10;
}
public void goNorthWest()
{
startX-=10;
startY-=10;
}
public void goSouthEast()
{
startX-=10;
startY+=10;
}
public void goSouthWest()
{
startX+=10;
startY+=10;
}
public void goToCenter()
{
startX=275;
startY=212;
}
public void goToULCorner()
{
startX=0;
startY=0;
}
public void goToURCorner()
{
startX=550;
startY=0;
}
public void goToLLCorner()
{
startX=0;
startY=424;
}
public void goToLRCorner()
{
startX=550;
startY=424;
}
} //endProgram
| true | true | public void init()
{
west = new Button ("West");
add (west);
west.addActionListener (this);
north = new Button ("North");
add (north);
north.addActionListener (this);
south = new Button ("South");
add (south);
south.addActionListener (this);
east = new Button ("East");
add (east);
east.addActionListener (this);
northWest = new Button ("Northwest");
add (northWest);
northWest.addActionListener (this);
northEast = new Button ("Northeast");
add (northEast);
northEast.addActionListener (this);
southWest = new Button ("Southwest");
add (southWest);
southWest.addActionListener (this);
southEast = new Button ("SouthEast");
add (southEast);
southEast.addActionListener (this);
farUL = new Button ("Go to upper-left corner");
add (farUL);
farUL.addActionListener (this);
farUR = new Button ("Go to upper-right corner");
add (farUR);
farUR.addActionListener (this);
farLL = new Button ("Go to lower-left corner");
add (farLL);
farLL.addActionListener (this);
farLR = new Button ("Go to lower-right corner");
add (farLR);
farLR.addActionListener (this);
midpoint = new Button ("Go to the exact center");
add (midpoint);
midpoint.addActionListener (this);
if (CONSOLE_LOGGING_ENABLED)
{
System.out.println("Console tracking enabled.");
System.out.println("");
System.out.println(" x | y ");
System.out.println("--------+--------");
}
}// endInit
| public void init()
{
west = new Button ("West");
add (west);
west.addActionListener (this);
north = new Button ("North");
add (north);
north.addActionListener (this);
south = new Button ("South");
add (south);
south.addActionListener (this);
east = new Button ("East");
add (east);
east.addActionListener (this);
northWest = new Button ("Northwest");
add (northWest);
northWest.addActionListener (this);
northEast = new Button ("Northeast");
add (northEast);
northEast.addActionListener (this);
southWest = new Button ("Southwest");
add (southWest);
southWest.addActionListener (this);
southEast = new Button ("Southeast");
add (southEast);
southEast.addActionListener (this);
farUL = new Button ("Go to upper-left corner");
add (farUL);
farUL.addActionListener (this);
farUR = new Button ("Go to upper-right corner");
add (farUR);
farUR.addActionListener (this);
farLL = new Button ("Go to lower-left corner");
add (farLL);
farLL.addActionListener (this);
farLR = new Button ("Go to lower-right corner");
add (farLR);
farLR.addActionListener (this);
midpoint = new Button ("Go to the exact center");
add (midpoint);
midpoint.addActionListener (this);
if (CONSOLE_LOGGING_ENABLED)
{
System.out.println("Console tracking enabled.");
System.out.println("");
System.out.println(" x | y ");
System.out.println("--------+--------");
}
}// endInit
|
diff --git a/common/logisticspipes/config/Configs.java b/common/logisticspipes/config/Configs.java
index f350dc53..042188fd 100644
--- a/common/logisticspipes/config/Configs.java
+++ b/common/logisticspipes/config/Configs.java
@@ -1,275 +1,276 @@
package logisticspipes.config;
import java.io.File;
import logisticspipes.LogisticsPipes;
import logisticspipes.proxy.MainProxy;
import net.minecraft.src.ModLoader;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.Property;
public class Configs {
// Ids
public static int ItemPartsId = 6867;
public static int ItemHUDId = 6868;
public static int ItemCardId = 6869;
public static int ItemDiskId = 6870;
public static int ItemModuleId = 6871;
public static int LOGISTICSREMOTEORDERER_ID = 6872;
public static int LOGISTICSNETWORKMONITOR_ID = 6873;
public static int LOGISTICSPIPE_BASIC_ID = 6874;
public static int LOGISTICSPIPE_REQUEST_ID = 6875;
public static int LOGISTICSPIPE_PROVIDER_ID = 6876;
public static int LOGISTICSPIPE_CRAFTING_ID = 6877;
public static int LOGISTICSPIPE_SATELLITE_ID = 6878;
public static int LOGISTICSPIPE_SUPPLIER_ID = 6879;
public static int LOGISTICSPIPE_BUILDERSUPPLIER_ID = 6880;
public static int LOGISTICSPIPE_CHASSI1_ID = 6881;
public static int LOGISTICSPIPE_CHASSI2_ID = 6882;
public static int LOGISTICSPIPE_CHASSI3_ID = 6883;
public static int LOGISTICSPIPE_CHASSI4_ID = 6884;
public static int LOGISTICSPIPE_CHASSI5_ID = 6885;
public static int LOGISTICSPIPE_LIQUIDSUPPLIER_ID = 6886;
public static int LOGISTICSPIPE_CRAFTING_MK2_ID = 6887;
public static int LOGISTICSPIPE_REQUEST_MK2_ID = 6888;
public static int LOGISTICSPIPE_REMOTE_ORDERER_ID = 6889;
public static int LOGISTICSPIPE_PROVIDER_MK2_ID = 6890;
public static int LOGISTICSPIPE_APIARIST_ANALYSER_ID = 6891;
public static int LOGISTICSPIPE_APIARIST_SINK_ID = 6892;
public static int LOGISTICSPIPE_INVSYSCON_ID = 6893;
public static int LOGISTICSPIPE_ENTRANCE_ID = 6894;
public static int LOGISTICSPIPE_DESTINATION_ID = 6895;
public static int LOGISTICSPIPE_CRAFTING_MK3_ID = 6896;
public static int LOGISTICSCRAFTINGSIGNCREATOR_ID = 6900;
private static Configuration configuration;
// Configrables
public static int LOGISTICS_DETECTION_LENGTH = 50;
public static int LOGISTICS_DETECTION_COUNT = 100;
public static int LOGISTICS_DETECTION_FREQUENCY = 20;
public static boolean LOGISTICS_ORDERER_COUNT_INVERTWHEEL = false;
public static boolean LOGISTICS_ORDERER_PAGE_INVERTWHEEL = false;
public static final float LOGISTICS_ROUTED_SPEED_MULTIPLIER = 20F;
public static final float LOGISTICS_DEFAULTROUTED_SPEED_MULTIPLIER = 10F;
public static int LOGISTICS_HUD_RENDER_DISTANCE = 15;
public static boolean LOGISTICS_POWER_USAGE_DISABLED = false;
public static boolean LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED = false;
public static boolean ToolTipInfo = LogisticsPipes.DEBUG;
//GuiOrderer Popup setting
public static boolean displayPopup = true;
//BlockID
public static int LOGISTICS_SIGN_ID = 1100;
public static int LOGISTICS_SOLID_BLOCK_ID = 1101;
public static void load() {
File configFile = null;
if(MainProxy.isClient()) {
configFile = new File(net.minecraft.client.Minecraft.getMinecraftDir(), "config/LogisticsPipes.cfg");
} else if(MainProxy.isServer()) {
configFile = net.minecraft.server.MinecraftServer.getServer().getFile("config/LogisticsPipes.cfg");
} else {
ModLoader.getLogger().severe("No server, no client? Where am I running?");
return;
}
configuration = new Configuration(configFile);
configuration.load();
Property logisticRemoteOrdererIdProperty = configuration.get("logisticsRemoteOrderer.id", Configuration.CATEGORY_ITEM, LOGISTICSREMOTEORDERER_ID);
logisticRemoteOrdererIdProperty.comment = "The item id for the remote orderer";
Property logisticNetworkMonitorIdProperty = configuration.get("logisticsNetworkMonitor.id", Configuration.CATEGORY_ITEM, LOGISTICSNETWORKMONITOR_ID);
logisticNetworkMonitorIdProperty.comment = "The item id for the network monitor";
Property logisticPipeIdProperty = configuration.get("logisticsPipe.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_BASIC_ID);
logisticPipeIdProperty.comment = "The item id for the basic logistics pipe";
Property logisticPipeRequesterIdProperty = configuration.get("logisticsPipeRequester.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_REQUEST_ID);
logisticPipeRequesterIdProperty.comment = "The item id for the requesting logistics pipe";
Property logisticPipeProviderIdProperty = configuration.get("logisticsPipeProvider.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_PROVIDER_ID);
logisticPipeProviderIdProperty.comment = "The item id for the providing logistics pipe";
Property logisticPipeCraftingIdProperty = configuration.get("logisticsPipeCrafting.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CRAFTING_ID);
logisticPipeCraftingIdProperty.comment = "The item id for the crafting logistics pipe";
Property logisticPipeSatelliteIdProperty = configuration.get("logisticsPipeSatellite.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_SATELLITE_ID);
logisticPipeSatelliteIdProperty.comment = "The item id for the crafting satellite pipe";
Property logisticPipeSupplierIdProperty = configuration.get("logisticsPipeSupplier.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_SUPPLIER_ID);
logisticPipeSupplierIdProperty.comment = "The item id for the supplier pipe";
Property logisticPipeChassi1IdProperty = configuration.get("logisticsPipeChassi1.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI1_ID);
logisticPipeChassi1IdProperty.comment = "The item id for the chassi1";
Property logisticPipeChassi2IdProperty = configuration.get("logisticsPipeChassi2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI2_ID);
logisticPipeChassi2IdProperty.comment = "The item id for the chassi2";
Property logisticPipeChassi3IdProperty = configuration.get("logisticsPipeChassi3.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI3_ID);
logisticPipeChassi3IdProperty.comment = "The item id for the chassi3";
Property logisticPipeChassi4IdProperty = configuration.get("logisticsPipeChassi4.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI4_ID);
logisticPipeChassi4IdProperty.comment = "The item id for the chassi4";
Property logisticPipeChassi5IdProperty = configuration.get("logisticsPipeChassi5.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI5_ID);
logisticPipeChassi5IdProperty.comment = "The item id for the chassi5";
Property logisticPipeCraftingMK2IdProperty = configuration.get("logisticsPipeCraftingMK2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CRAFTING_MK2_ID);
logisticPipeCraftingMK2IdProperty.comment = "The item id for the crafting logistics pipe MK2";
Property logisticPipeCraftingMK3IdProperty = configuration.get("logisticsPipeCraftingMK3.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CRAFTING_MK3_ID);
logisticPipeCraftingMK3IdProperty.comment = "The item id for the crafting logistics pipe MK3";
Property logisticPipeRequesterMK2IdProperty = configuration.get("logisticsPipeRequesterMK2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_REQUEST_MK2_ID);
logisticPipeRequesterMK2IdProperty.comment = "The item id for the requesting logistics pipe MK2";
Property logisticPipeProviderMK2IdProperty = configuration.get("logisticsPipeProviderMK2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_PROVIDER_MK2_ID);
logisticPipeProviderMK2IdProperty.comment = "The item id for the provider logistics pipe MK2";
Property logisticPipeApiaristAnalyserIdProperty = configuration.get("logisticsPipeApiaristAnalyser.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_APIARIST_ANALYSER_ID);
logisticPipeApiaristAnalyserIdProperty.comment = "The item id for the apiarist logistics analyser pipe";
Property logisticPipeRemoteOrdererIdProperty = configuration.get("logisticsPipeRemoteOrderer.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_REMOTE_ORDERER_ID);
logisticPipeRemoteOrdererIdProperty.comment = "The item id for the remote orderer logistics pipe";
Property logisticPipeApiaristSinkIdProperty = configuration.get("logisticsPipeApiaristSink.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_APIARIST_SINK_ID);
logisticPipeApiaristSinkIdProperty.comment = "The item id for the apiarist logistics sink pipe";
Property logisticModuleIdProperty = configuration.get("logisticsModules.id", Configuration.CATEGORY_ITEM, ItemModuleId);
logisticModuleIdProperty.comment = "The item id for the modules";
Property logisticItemDiskIdProperty = configuration.get("logisticsDisk.id", Configuration.CATEGORY_ITEM, ItemDiskId);
logisticItemDiskIdProperty.comment = "The item id for the disk";
Property logisticItemHUDIdProperty = configuration.get("logisticsHUD.id", Configuration.CATEGORY_ITEM, ItemHUDId);
logisticItemHUDIdProperty.comment = "The item id for the Logistics HUD glasses";
Property logisticItemPartsIdProperty = configuration.get("logisticsHUDParts.id", Configuration.CATEGORY_ITEM, ItemPartsId);
logisticItemPartsIdProperty.comment = "The item id for the Logistics item parts";
Property logisticCraftingSignCreatorIdProperty = configuration.get("logisticsCraftingSignCreator.id", Configuration.CATEGORY_ITEM, LOGISTICSCRAFTINGSIGNCREATOR_ID);
logisticCraftingSignCreatorIdProperty.comment = "The item id for the crafting sign creator";
Property logisticPipeBuilderSupplierIdProperty = configuration.get("logisticsPipeBuilderSupplier.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_BUILDERSUPPLIER_ID);
logisticPipeBuilderSupplierIdProperty.comment = "The item id for the builder supplier pipe";
Property logisticPipeLiquidSupplierIdProperty = configuration.get("logisticsPipeLiquidSupplier.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_LIQUIDSUPPLIER_ID);
logisticPipeLiquidSupplierIdProperty.comment = "The item id for the liquid supplier pipe";
Property logisticInvSysConIdProperty = configuration.get("logisticInvSysCon.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_INVSYSCON_ID);
logisticInvSysConIdProperty.comment = "The item id for the inventory system connector pipe";
Property logisticEntranceIdProperty = configuration.get("logisticEntrance.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_ENTRANCE_ID);
logisticEntranceIdProperty.comment = "The item id for the logistics system entrance pipe";
Property logisticDestinationIdProperty = configuration.get("logisticDestination.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_DESTINATION_ID);
logisticDestinationIdProperty.comment = "The item id for the logistics system destination pipe";
Property logisticItemCardIdProperty = configuration.get("logisticItemCard.id", Configuration.CATEGORY_ITEM, ItemCardId);
logisticItemCardIdProperty.comment = "The item id for the logistics item card";
Property detectionLength = configuration.get("detectionLength", Configuration.CATEGORY_GENERAL, LOGISTICS_DETECTION_LENGTH);
detectionLength.comment = "The maximum shortest length between logistics pipes. This is an indicator on the maxim depth of the recursion algorithm to discover logistics neighbours. A low value might use less CPU, a high value will allow longer pipe sections";
Property detectionCount = configuration.get("detectionCount", Configuration.CATEGORY_GENERAL, LOGISTICS_DETECTION_COUNT);
detectionCount.comment = "The maximum number of buildcraft pipees (including forks) between logistics pipes. This is an indicator of the maximum ammount of nodes the recursion algorithm will visit before giving up. As it is possible to fork a pipe connection using standard BC pipes the algorithm will attempt to discover all available destinations through that pipe. Do note that the logistics system will not interfere with the operation of non-logistics pipes. So a forked pipe will usually be sup-optimal, but it is possible. A low value might reduce CPU usage, a high value will be able to handle more complex pipe setups. If you never fork your connection between the logistics pipes this has the same meaning as detectionLength and the lower of the two will be used";
Property detectionFrequency = configuration.get("detectionFrequency", Configuration.CATEGORY_GENERAL, LOGISTICS_DETECTION_FREQUENCY);
detectionFrequency.comment = "The amount of time that passes between checks to see if it is still connected to its neighbours. A low value will mean that it will detect changes faster but use more CPU. A high value means detection takes longer, but CPU consumption is reduced. A value of 20 will check about every second";
Property countInvertWheelProperty = configuration.get("ordererCountInvertWheel", Configuration.CATEGORY_GENERAL, LOGISTICS_ORDERER_COUNT_INVERTWHEEL);
countInvertWheelProperty.comment = "Inverts the the mouse wheel scrolling for remote order number of items";
Property pageInvertWheelProperty = configuration.get("ordererPageInvertWheel", Configuration.CATEGORY_GENERAL, LOGISTICS_ORDERER_PAGE_INVERTWHEEL);
pageInvertWheelProperty.comment = "Inverts the the mouse wheel scrolling for remote order pages";
Property pageDisplayPopupProperty = configuration.get("displayPopup", Configuration.CATEGORY_GENERAL, displayPopup);
pageDisplayPopupProperty.comment = "Set the default configuration for the popup of the Orderer Gui. Should it be used?";
if(configuration.categories.get(Configuration.CATEGORY_BLOCK).containsKey("logisticsBlockId")) {
Property logisticsBlockId = configuration.get("logisticsBlockId", Configuration.CATEGORY_BLOCK, LOGISTICS_SIGN_ID);
LOGISTICS_SIGN_ID = Integer.parseInt(logisticsBlockId.value);
configuration.categories.get(Configuration.CATEGORY_BLOCK).remove("logisticsBlockId");
}
Property logisticsSignId = configuration.get("logisticsSignId", Configuration.CATEGORY_BLOCK, LOGISTICS_SIGN_ID);
logisticsSignId.comment = "The ID of the LogisticsPipes Sign";
Property logisticsSolidBlockId = configuration.get("logisticsSolidBlockId", Configuration.CATEGORY_BLOCK, LOGISTICS_SOLID_BLOCK_ID);
logisticsSolidBlockId.comment = "The ID of the LogisticsPipes Solid Block";
Property logsiticsPowerUsageDisable = configuration.get("powerUsageDisabled", Configuration.CATEGORY_GENERAL, LOGISTICS_POWER_USAGE_DISABLED);
logsiticsPowerUsageDisable.comment = "Diable the power usage trough LogisticsPipes";
Property logsiticsTileGenericReplacementDisable = configuration.get("TileReplaceDisabled", Configuration.CATEGORY_GENERAL, LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED);
logsiticsTileGenericReplacementDisable.comment = "Diable the Replacement of the TileGenericPipe trough the LogisticsTileGenericPipe";
Property logsiticsHUDRenderDistance = configuration.get("HUDRenderDistance", Configuration.CATEGORY_GENERAL, LOGISTICS_HUD_RENDER_DISTANCE);
logsiticsHUDRenderDistance.comment = "The max. distance between a player and the HUD that get's shown in blocks.";
configuration.save();
LOGISTICSNETWORKMONITOR_ID = Integer.parseInt(logisticNetworkMonitorIdProperty.value);
LOGISTICSREMOTEORDERER_ID = Integer.parseInt(logisticRemoteOrdererIdProperty.value);
ItemModuleId = Integer.parseInt(logisticModuleIdProperty.value);
ItemDiskId = Integer.parseInt(logisticItemDiskIdProperty.value);
ItemCardId = Integer.parseInt(logisticItemCardIdProperty.value);
ItemHUDId = Integer.parseInt(logisticItemHUDIdProperty.value);
ItemPartsId = Integer.parseInt(logisticItemPartsIdProperty.value);
LOGISTICSPIPE_BASIC_ID = Integer.parseInt(logisticPipeIdProperty.value);
LOGISTICSPIPE_REQUEST_ID = Integer.parseInt(logisticPipeRequesterIdProperty.value);
LOGISTICSPIPE_PROVIDER_ID = Integer.parseInt(logisticPipeProviderIdProperty.value);
LOGISTICSPIPE_CRAFTING_ID = Integer.parseInt(logisticPipeCraftingIdProperty.value);
LOGISTICSPIPE_SATELLITE_ID = Integer.parseInt(logisticPipeSatelliteIdProperty.value);
LOGISTICSPIPE_SUPPLIER_ID = Integer.parseInt(logisticPipeSupplierIdProperty.value);
LOGISTICSPIPE_CHASSI1_ID = Integer.parseInt(logisticPipeChassi1IdProperty.value);
LOGISTICSPIPE_CHASSI2_ID = Integer.parseInt(logisticPipeChassi2IdProperty.value);
LOGISTICSPIPE_CHASSI3_ID = Integer.parseInt(logisticPipeChassi3IdProperty.value);
LOGISTICSPIPE_CHASSI4_ID = Integer.parseInt(logisticPipeChassi4IdProperty.value);
LOGISTICSPIPE_CHASSI5_ID = Integer.parseInt(logisticPipeChassi5IdProperty.value);
LOGISTICSPIPE_CRAFTING_MK2_ID = Integer.parseInt(logisticPipeCraftingMK2IdProperty.value);
+ LOGISTICSPIPE_CRAFTING_MK3_ID = Integer.parseInt(logisticPipeCraftingMK3IdProperty.value);
LOGISTICSPIPE_REQUEST_MK2_ID = Integer.parseInt(logisticPipeRequesterMK2IdProperty.value);
LOGISTICSPIPE_PROVIDER_MK2_ID = Integer.parseInt(logisticPipeProviderMK2IdProperty.value);
LOGISTICSPIPE_REMOTE_ORDERER_ID = Integer.parseInt(logisticPipeRemoteOrdererIdProperty.value);
LOGISTICSPIPE_APIARIST_ANALYSER_ID = Integer.parseInt(logisticPipeApiaristAnalyserIdProperty.value);
LOGISTICSPIPE_APIARIST_SINK_ID = Integer.parseInt(logisticPipeApiaristSinkIdProperty.value);
LOGISTICSPIPE_ENTRANCE_ID = Integer.parseInt(logisticEntranceIdProperty.value);
LOGISTICSPIPE_DESTINATION_ID = Integer.parseInt(logisticDestinationIdProperty.value);
LOGISTICSPIPE_INVSYSCON_ID = Integer.parseInt(logisticInvSysConIdProperty.value);
LOGISTICS_SIGN_ID = Integer.parseInt(logisticsSignId.value);
LOGISTICS_SOLID_BLOCK_ID = Integer.parseInt(logisticsSolidBlockId.value);
LOGISTICS_DETECTION_LENGTH = Integer.parseInt(detectionLength.value);
LOGISTICS_DETECTION_COUNT = Integer.parseInt(detectionCount.value);
LOGISTICS_DETECTION_FREQUENCY = Math.max(Integer.parseInt(detectionFrequency.value), 1);
LOGISTICS_ORDERER_COUNT_INVERTWHEEL = Boolean.parseBoolean(countInvertWheelProperty.value);
LOGISTICS_ORDERER_PAGE_INVERTWHEEL = Boolean.parseBoolean(pageInvertWheelProperty.value);
LOGISTICS_POWER_USAGE_DISABLED = Boolean.parseBoolean(logsiticsPowerUsageDisable.value);
LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED = Boolean.parseBoolean(logsiticsTileGenericReplacementDisable.value);
LOGISTICSCRAFTINGSIGNCREATOR_ID = Integer.parseInt(logisticCraftingSignCreatorIdProperty.value);
LOGISTICS_HUD_RENDER_DISTANCE = Integer.parseInt(logsiticsHUDRenderDistance.value);
displayPopup = Boolean.parseBoolean(pageDisplayPopupProperty.value);
LOGISTICSPIPE_BUILDERSUPPLIER_ID = Integer.parseInt(logisticPipeBuilderSupplierIdProperty.value);
LOGISTICSPIPE_LIQUIDSUPPLIER_ID = Integer.parseInt(logisticPipeLiquidSupplierIdProperty.value);
}
public static void savePopupState() {
Property pageDisplayPopupProperty = configuration.get("displayPopup", Configuration.CATEGORY_GENERAL, displayPopup);
pageDisplayPopupProperty.comment = "Set the default configuration for the popup of the Orderer Gui. Should it be used?";
pageDisplayPopupProperty.value = Boolean.toString(displayPopup);
configuration.save();
}
}
| true | true | public static void load() {
File configFile = null;
if(MainProxy.isClient()) {
configFile = new File(net.minecraft.client.Minecraft.getMinecraftDir(), "config/LogisticsPipes.cfg");
} else if(MainProxy.isServer()) {
configFile = net.minecraft.server.MinecraftServer.getServer().getFile("config/LogisticsPipes.cfg");
} else {
ModLoader.getLogger().severe("No server, no client? Where am I running?");
return;
}
configuration = new Configuration(configFile);
configuration.load();
Property logisticRemoteOrdererIdProperty = configuration.get("logisticsRemoteOrderer.id", Configuration.CATEGORY_ITEM, LOGISTICSREMOTEORDERER_ID);
logisticRemoteOrdererIdProperty.comment = "The item id for the remote orderer";
Property logisticNetworkMonitorIdProperty = configuration.get("logisticsNetworkMonitor.id", Configuration.CATEGORY_ITEM, LOGISTICSNETWORKMONITOR_ID);
logisticNetworkMonitorIdProperty.comment = "The item id for the network monitor";
Property logisticPipeIdProperty = configuration.get("logisticsPipe.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_BASIC_ID);
logisticPipeIdProperty.comment = "The item id for the basic logistics pipe";
Property logisticPipeRequesterIdProperty = configuration.get("logisticsPipeRequester.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_REQUEST_ID);
logisticPipeRequesterIdProperty.comment = "The item id for the requesting logistics pipe";
Property logisticPipeProviderIdProperty = configuration.get("logisticsPipeProvider.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_PROVIDER_ID);
logisticPipeProviderIdProperty.comment = "The item id for the providing logistics pipe";
Property logisticPipeCraftingIdProperty = configuration.get("logisticsPipeCrafting.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CRAFTING_ID);
logisticPipeCraftingIdProperty.comment = "The item id for the crafting logistics pipe";
Property logisticPipeSatelliteIdProperty = configuration.get("logisticsPipeSatellite.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_SATELLITE_ID);
logisticPipeSatelliteIdProperty.comment = "The item id for the crafting satellite pipe";
Property logisticPipeSupplierIdProperty = configuration.get("logisticsPipeSupplier.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_SUPPLIER_ID);
logisticPipeSupplierIdProperty.comment = "The item id for the supplier pipe";
Property logisticPipeChassi1IdProperty = configuration.get("logisticsPipeChassi1.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI1_ID);
logisticPipeChassi1IdProperty.comment = "The item id for the chassi1";
Property logisticPipeChassi2IdProperty = configuration.get("logisticsPipeChassi2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI2_ID);
logisticPipeChassi2IdProperty.comment = "The item id for the chassi2";
Property logisticPipeChassi3IdProperty = configuration.get("logisticsPipeChassi3.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI3_ID);
logisticPipeChassi3IdProperty.comment = "The item id for the chassi3";
Property logisticPipeChassi4IdProperty = configuration.get("logisticsPipeChassi4.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI4_ID);
logisticPipeChassi4IdProperty.comment = "The item id for the chassi4";
Property logisticPipeChassi5IdProperty = configuration.get("logisticsPipeChassi5.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI5_ID);
logisticPipeChassi5IdProperty.comment = "The item id for the chassi5";
Property logisticPipeCraftingMK2IdProperty = configuration.get("logisticsPipeCraftingMK2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CRAFTING_MK2_ID);
logisticPipeCraftingMK2IdProperty.comment = "The item id for the crafting logistics pipe MK2";
Property logisticPipeCraftingMK3IdProperty = configuration.get("logisticsPipeCraftingMK3.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CRAFTING_MK3_ID);
logisticPipeCraftingMK3IdProperty.comment = "The item id for the crafting logistics pipe MK3";
Property logisticPipeRequesterMK2IdProperty = configuration.get("logisticsPipeRequesterMK2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_REQUEST_MK2_ID);
logisticPipeRequesterMK2IdProperty.comment = "The item id for the requesting logistics pipe MK2";
Property logisticPipeProviderMK2IdProperty = configuration.get("logisticsPipeProviderMK2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_PROVIDER_MK2_ID);
logisticPipeProviderMK2IdProperty.comment = "The item id for the provider logistics pipe MK2";
Property logisticPipeApiaristAnalyserIdProperty = configuration.get("logisticsPipeApiaristAnalyser.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_APIARIST_ANALYSER_ID);
logisticPipeApiaristAnalyserIdProperty.comment = "The item id for the apiarist logistics analyser pipe";
Property logisticPipeRemoteOrdererIdProperty = configuration.get("logisticsPipeRemoteOrderer.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_REMOTE_ORDERER_ID);
logisticPipeRemoteOrdererIdProperty.comment = "The item id for the remote orderer logistics pipe";
Property logisticPipeApiaristSinkIdProperty = configuration.get("logisticsPipeApiaristSink.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_APIARIST_SINK_ID);
logisticPipeApiaristSinkIdProperty.comment = "The item id for the apiarist logistics sink pipe";
Property logisticModuleIdProperty = configuration.get("logisticsModules.id", Configuration.CATEGORY_ITEM, ItemModuleId);
logisticModuleIdProperty.comment = "The item id for the modules";
Property logisticItemDiskIdProperty = configuration.get("logisticsDisk.id", Configuration.CATEGORY_ITEM, ItemDiskId);
logisticItemDiskIdProperty.comment = "The item id for the disk";
Property logisticItemHUDIdProperty = configuration.get("logisticsHUD.id", Configuration.CATEGORY_ITEM, ItemHUDId);
logisticItemHUDIdProperty.comment = "The item id for the Logistics HUD glasses";
Property logisticItemPartsIdProperty = configuration.get("logisticsHUDParts.id", Configuration.CATEGORY_ITEM, ItemPartsId);
logisticItemPartsIdProperty.comment = "The item id for the Logistics item parts";
Property logisticCraftingSignCreatorIdProperty = configuration.get("logisticsCraftingSignCreator.id", Configuration.CATEGORY_ITEM, LOGISTICSCRAFTINGSIGNCREATOR_ID);
logisticCraftingSignCreatorIdProperty.comment = "The item id for the crafting sign creator";
Property logisticPipeBuilderSupplierIdProperty = configuration.get("logisticsPipeBuilderSupplier.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_BUILDERSUPPLIER_ID);
logisticPipeBuilderSupplierIdProperty.comment = "The item id for the builder supplier pipe";
Property logisticPipeLiquidSupplierIdProperty = configuration.get("logisticsPipeLiquidSupplier.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_LIQUIDSUPPLIER_ID);
logisticPipeLiquidSupplierIdProperty.comment = "The item id for the liquid supplier pipe";
Property logisticInvSysConIdProperty = configuration.get("logisticInvSysCon.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_INVSYSCON_ID);
logisticInvSysConIdProperty.comment = "The item id for the inventory system connector pipe";
Property logisticEntranceIdProperty = configuration.get("logisticEntrance.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_ENTRANCE_ID);
logisticEntranceIdProperty.comment = "The item id for the logistics system entrance pipe";
Property logisticDestinationIdProperty = configuration.get("logisticDestination.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_DESTINATION_ID);
logisticDestinationIdProperty.comment = "The item id for the logistics system destination pipe";
Property logisticItemCardIdProperty = configuration.get("logisticItemCard.id", Configuration.CATEGORY_ITEM, ItemCardId);
logisticItemCardIdProperty.comment = "The item id for the logistics item card";
Property detectionLength = configuration.get("detectionLength", Configuration.CATEGORY_GENERAL, LOGISTICS_DETECTION_LENGTH);
detectionLength.comment = "The maximum shortest length between logistics pipes. This is an indicator on the maxim depth of the recursion algorithm to discover logistics neighbours. A low value might use less CPU, a high value will allow longer pipe sections";
Property detectionCount = configuration.get("detectionCount", Configuration.CATEGORY_GENERAL, LOGISTICS_DETECTION_COUNT);
detectionCount.comment = "The maximum number of buildcraft pipees (including forks) between logistics pipes. This is an indicator of the maximum ammount of nodes the recursion algorithm will visit before giving up. As it is possible to fork a pipe connection using standard BC pipes the algorithm will attempt to discover all available destinations through that pipe. Do note that the logistics system will not interfere with the operation of non-logistics pipes. So a forked pipe will usually be sup-optimal, but it is possible. A low value might reduce CPU usage, a high value will be able to handle more complex pipe setups. If you never fork your connection between the logistics pipes this has the same meaning as detectionLength and the lower of the two will be used";
Property detectionFrequency = configuration.get("detectionFrequency", Configuration.CATEGORY_GENERAL, LOGISTICS_DETECTION_FREQUENCY);
detectionFrequency.comment = "The amount of time that passes between checks to see if it is still connected to its neighbours. A low value will mean that it will detect changes faster but use more CPU. A high value means detection takes longer, but CPU consumption is reduced. A value of 20 will check about every second";
Property countInvertWheelProperty = configuration.get("ordererCountInvertWheel", Configuration.CATEGORY_GENERAL, LOGISTICS_ORDERER_COUNT_INVERTWHEEL);
countInvertWheelProperty.comment = "Inverts the the mouse wheel scrolling for remote order number of items";
Property pageInvertWheelProperty = configuration.get("ordererPageInvertWheel", Configuration.CATEGORY_GENERAL, LOGISTICS_ORDERER_PAGE_INVERTWHEEL);
pageInvertWheelProperty.comment = "Inverts the the mouse wheel scrolling for remote order pages";
Property pageDisplayPopupProperty = configuration.get("displayPopup", Configuration.CATEGORY_GENERAL, displayPopup);
pageDisplayPopupProperty.comment = "Set the default configuration for the popup of the Orderer Gui. Should it be used?";
if(configuration.categories.get(Configuration.CATEGORY_BLOCK).containsKey("logisticsBlockId")) {
Property logisticsBlockId = configuration.get("logisticsBlockId", Configuration.CATEGORY_BLOCK, LOGISTICS_SIGN_ID);
LOGISTICS_SIGN_ID = Integer.parseInt(logisticsBlockId.value);
configuration.categories.get(Configuration.CATEGORY_BLOCK).remove("logisticsBlockId");
}
Property logisticsSignId = configuration.get("logisticsSignId", Configuration.CATEGORY_BLOCK, LOGISTICS_SIGN_ID);
logisticsSignId.comment = "The ID of the LogisticsPipes Sign";
Property logisticsSolidBlockId = configuration.get("logisticsSolidBlockId", Configuration.CATEGORY_BLOCK, LOGISTICS_SOLID_BLOCK_ID);
logisticsSolidBlockId.comment = "The ID of the LogisticsPipes Solid Block";
Property logsiticsPowerUsageDisable = configuration.get("powerUsageDisabled", Configuration.CATEGORY_GENERAL, LOGISTICS_POWER_USAGE_DISABLED);
logsiticsPowerUsageDisable.comment = "Diable the power usage trough LogisticsPipes";
Property logsiticsTileGenericReplacementDisable = configuration.get("TileReplaceDisabled", Configuration.CATEGORY_GENERAL, LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED);
logsiticsTileGenericReplacementDisable.comment = "Diable the Replacement of the TileGenericPipe trough the LogisticsTileGenericPipe";
Property logsiticsHUDRenderDistance = configuration.get("HUDRenderDistance", Configuration.CATEGORY_GENERAL, LOGISTICS_HUD_RENDER_DISTANCE);
logsiticsHUDRenderDistance.comment = "The max. distance between a player and the HUD that get's shown in blocks.";
configuration.save();
LOGISTICSNETWORKMONITOR_ID = Integer.parseInt(logisticNetworkMonitorIdProperty.value);
LOGISTICSREMOTEORDERER_ID = Integer.parseInt(logisticRemoteOrdererIdProperty.value);
ItemModuleId = Integer.parseInt(logisticModuleIdProperty.value);
ItemDiskId = Integer.parseInt(logisticItemDiskIdProperty.value);
ItemCardId = Integer.parseInt(logisticItemCardIdProperty.value);
ItemHUDId = Integer.parseInt(logisticItemHUDIdProperty.value);
ItemPartsId = Integer.parseInt(logisticItemPartsIdProperty.value);
LOGISTICSPIPE_BASIC_ID = Integer.parseInt(logisticPipeIdProperty.value);
LOGISTICSPIPE_REQUEST_ID = Integer.parseInt(logisticPipeRequesterIdProperty.value);
LOGISTICSPIPE_PROVIDER_ID = Integer.parseInt(logisticPipeProviderIdProperty.value);
LOGISTICSPIPE_CRAFTING_ID = Integer.parseInt(logisticPipeCraftingIdProperty.value);
LOGISTICSPIPE_SATELLITE_ID = Integer.parseInt(logisticPipeSatelliteIdProperty.value);
LOGISTICSPIPE_SUPPLIER_ID = Integer.parseInt(logisticPipeSupplierIdProperty.value);
LOGISTICSPIPE_CHASSI1_ID = Integer.parseInt(logisticPipeChassi1IdProperty.value);
LOGISTICSPIPE_CHASSI2_ID = Integer.parseInt(logisticPipeChassi2IdProperty.value);
LOGISTICSPIPE_CHASSI3_ID = Integer.parseInt(logisticPipeChassi3IdProperty.value);
LOGISTICSPIPE_CHASSI4_ID = Integer.parseInt(logisticPipeChassi4IdProperty.value);
LOGISTICSPIPE_CHASSI5_ID = Integer.parseInt(logisticPipeChassi5IdProperty.value);
LOGISTICSPIPE_CRAFTING_MK2_ID = Integer.parseInt(logisticPipeCraftingMK2IdProperty.value);
LOGISTICSPIPE_REQUEST_MK2_ID = Integer.parseInt(logisticPipeRequesterMK2IdProperty.value);
LOGISTICSPIPE_PROVIDER_MK2_ID = Integer.parseInt(logisticPipeProviderMK2IdProperty.value);
LOGISTICSPIPE_REMOTE_ORDERER_ID = Integer.parseInt(logisticPipeRemoteOrdererIdProperty.value);
LOGISTICSPIPE_APIARIST_ANALYSER_ID = Integer.parseInt(logisticPipeApiaristAnalyserIdProperty.value);
LOGISTICSPIPE_APIARIST_SINK_ID = Integer.parseInt(logisticPipeApiaristSinkIdProperty.value);
LOGISTICSPIPE_ENTRANCE_ID = Integer.parseInt(logisticEntranceIdProperty.value);
LOGISTICSPIPE_DESTINATION_ID = Integer.parseInt(logisticDestinationIdProperty.value);
LOGISTICSPIPE_INVSYSCON_ID = Integer.parseInt(logisticInvSysConIdProperty.value);
LOGISTICS_SIGN_ID = Integer.parseInt(logisticsSignId.value);
LOGISTICS_SOLID_BLOCK_ID = Integer.parseInt(logisticsSolidBlockId.value);
LOGISTICS_DETECTION_LENGTH = Integer.parseInt(detectionLength.value);
LOGISTICS_DETECTION_COUNT = Integer.parseInt(detectionCount.value);
LOGISTICS_DETECTION_FREQUENCY = Math.max(Integer.parseInt(detectionFrequency.value), 1);
LOGISTICS_ORDERER_COUNT_INVERTWHEEL = Boolean.parseBoolean(countInvertWheelProperty.value);
LOGISTICS_ORDERER_PAGE_INVERTWHEEL = Boolean.parseBoolean(pageInvertWheelProperty.value);
LOGISTICS_POWER_USAGE_DISABLED = Boolean.parseBoolean(logsiticsPowerUsageDisable.value);
LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED = Boolean.parseBoolean(logsiticsTileGenericReplacementDisable.value);
LOGISTICSCRAFTINGSIGNCREATOR_ID = Integer.parseInt(logisticCraftingSignCreatorIdProperty.value);
LOGISTICS_HUD_RENDER_DISTANCE = Integer.parseInt(logsiticsHUDRenderDistance.value);
displayPopup = Boolean.parseBoolean(pageDisplayPopupProperty.value);
LOGISTICSPIPE_BUILDERSUPPLIER_ID = Integer.parseInt(logisticPipeBuilderSupplierIdProperty.value);
LOGISTICSPIPE_LIQUIDSUPPLIER_ID = Integer.parseInt(logisticPipeLiquidSupplierIdProperty.value);
}
| public static void load() {
File configFile = null;
if(MainProxy.isClient()) {
configFile = new File(net.minecraft.client.Minecraft.getMinecraftDir(), "config/LogisticsPipes.cfg");
} else if(MainProxy.isServer()) {
configFile = net.minecraft.server.MinecraftServer.getServer().getFile("config/LogisticsPipes.cfg");
} else {
ModLoader.getLogger().severe("No server, no client? Where am I running?");
return;
}
configuration = new Configuration(configFile);
configuration.load();
Property logisticRemoteOrdererIdProperty = configuration.get("logisticsRemoteOrderer.id", Configuration.CATEGORY_ITEM, LOGISTICSREMOTEORDERER_ID);
logisticRemoteOrdererIdProperty.comment = "The item id for the remote orderer";
Property logisticNetworkMonitorIdProperty = configuration.get("logisticsNetworkMonitor.id", Configuration.CATEGORY_ITEM, LOGISTICSNETWORKMONITOR_ID);
logisticNetworkMonitorIdProperty.comment = "The item id for the network monitor";
Property logisticPipeIdProperty = configuration.get("logisticsPipe.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_BASIC_ID);
logisticPipeIdProperty.comment = "The item id for the basic logistics pipe";
Property logisticPipeRequesterIdProperty = configuration.get("logisticsPipeRequester.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_REQUEST_ID);
logisticPipeRequesterIdProperty.comment = "The item id for the requesting logistics pipe";
Property logisticPipeProviderIdProperty = configuration.get("logisticsPipeProvider.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_PROVIDER_ID);
logisticPipeProviderIdProperty.comment = "The item id for the providing logistics pipe";
Property logisticPipeCraftingIdProperty = configuration.get("logisticsPipeCrafting.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CRAFTING_ID);
logisticPipeCraftingIdProperty.comment = "The item id for the crafting logistics pipe";
Property logisticPipeSatelliteIdProperty = configuration.get("logisticsPipeSatellite.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_SATELLITE_ID);
logisticPipeSatelliteIdProperty.comment = "The item id for the crafting satellite pipe";
Property logisticPipeSupplierIdProperty = configuration.get("logisticsPipeSupplier.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_SUPPLIER_ID);
logisticPipeSupplierIdProperty.comment = "The item id for the supplier pipe";
Property logisticPipeChassi1IdProperty = configuration.get("logisticsPipeChassi1.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI1_ID);
logisticPipeChassi1IdProperty.comment = "The item id for the chassi1";
Property logisticPipeChassi2IdProperty = configuration.get("logisticsPipeChassi2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI2_ID);
logisticPipeChassi2IdProperty.comment = "The item id for the chassi2";
Property logisticPipeChassi3IdProperty = configuration.get("logisticsPipeChassi3.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI3_ID);
logisticPipeChassi3IdProperty.comment = "The item id for the chassi3";
Property logisticPipeChassi4IdProperty = configuration.get("logisticsPipeChassi4.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI4_ID);
logisticPipeChassi4IdProperty.comment = "The item id for the chassi4";
Property logisticPipeChassi5IdProperty = configuration.get("logisticsPipeChassi5.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI5_ID);
logisticPipeChassi5IdProperty.comment = "The item id for the chassi5";
Property logisticPipeCraftingMK2IdProperty = configuration.get("logisticsPipeCraftingMK2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CRAFTING_MK2_ID);
logisticPipeCraftingMK2IdProperty.comment = "The item id for the crafting logistics pipe MK2";
Property logisticPipeCraftingMK3IdProperty = configuration.get("logisticsPipeCraftingMK3.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CRAFTING_MK3_ID);
logisticPipeCraftingMK3IdProperty.comment = "The item id for the crafting logistics pipe MK3";
Property logisticPipeRequesterMK2IdProperty = configuration.get("logisticsPipeRequesterMK2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_REQUEST_MK2_ID);
logisticPipeRequesterMK2IdProperty.comment = "The item id for the requesting logistics pipe MK2";
Property logisticPipeProviderMK2IdProperty = configuration.get("logisticsPipeProviderMK2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_PROVIDER_MK2_ID);
logisticPipeProviderMK2IdProperty.comment = "The item id for the provider logistics pipe MK2";
Property logisticPipeApiaristAnalyserIdProperty = configuration.get("logisticsPipeApiaristAnalyser.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_APIARIST_ANALYSER_ID);
logisticPipeApiaristAnalyserIdProperty.comment = "The item id for the apiarist logistics analyser pipe";
Property logisticPipeRemoteOrdererIdProperty = configuration.get("logisticsPipeRemoteOrderer.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_REMOTE_ORDERER_ID);
logisticPipeRemoteOrdererIdProperty.comment = "The item id for the remote orderer logistics pipe";
Property logisticPipeApiaristSinkIdProperty = configuration.get("logisticsPipeApiaristSink.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_APIARIST_SINK_ID);
logisticPipeApiaristSinkIdProperty.comment = "The item id for the apiarist logistics sink pipe";
Property logisticModuleIdProperty = configuration.get("logisticsModules.id", Configuration.CATEGORY_ITEM, ItemModuleId);
logisticModuleIdProperty.comment = "The item id for the modules";
Property logisticItemDiskIdProperty = configuration.get("logisticsDisk.id", Configuration.CATEGORY_ITEM, ItemDiskId);
logisticItemDiskIdProperty.comment = "The item id for the disk";
Property logisticItemHUDIdProperty = configuration.get("logisticsHUD.id", Configuration.CATEGORY_ITEM, ItemHUDId);
logisticItemHUDIdProperty.comment = "The item id for the Logistics HUD glasses";
Property logisticItemPartsIdProperty = configuration.get("logisticsHUDParts.id", Configuration.CATEGORY_ITEM, ItemPartsId);
logisticItemPartsIdProperty.comment = "The item id for the Logistics item parts";
Property logisticCraftingSignCreatorIdProperty = configuration.get("logisticsCraftingSignCreator.id", Configuration.CATEGORY_ITEM, LOGISTICSCRAFTINGSIGNCREATOR_ID);
logisticCraftingSignCreatorIdProperty.comment = "The item id for the crafting sign creator";
Property logisticPipeBuilderSupplierIdProperty = configuration.get("logisticsPipeBuilderSupplier.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_BUILDERSUPPLIER_ID);
logisticPipeBuilderSupplierIdProperty.comment = "The item id for the builder supplier pipe";
Property logisticPipeLiquidSupplierIdProperty = configuration.get("logisticsPipeLiquidSupplier.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_LIQUIDSUPPLIER_ID);
logisticPipeLiquidSupplierIdProperty.comment = "The item id for the liquid supplier pipe";
Property logisticInvSysConIdProperty = configuration.get("logisticInvSysCon.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_INVSYSCON_ID);
logisticInvSysConIdProperty.comment = "The item id for the inventory system connector pipe";
Property logisticEntranceIdProperty = configuration.get("logisticEntrance.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_ENTRANCE_ID);
logisticEntranceIdProperty.comment = "The item id for the logistics system entrance pipe";
Property logisticDestinationIdProperty = configuration.get("logisticDestination.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_DESTINATION_ID);
logisticDestinationIdProperty.comment = "The item id for the logistics system destination pipe";
Property logisticItemCardIdProperty = configuration.get("logisticItemCard.id", Configuration.CATEGORY_ITEM, ItemCardId);
logisticItemCardIdProperty.comment = "The item id for the logistics item card";
Property detectionLength = configuration.get("detectionLength", Configuration.CATEGORY_GENERAL, LOGISTICS_DETECTION_LENGTH);
detectionLength.comment = "The maximum shortest length between logistics pipes. This is an indicator on the maxim depth of the recursion algorithm to discover logistics neighbours. A low value might use less CPU, a high value will allow longer pipe sections";
Property detectionCount = configuration.get("detectionCount", Configuration.CATEGORY_GENERAL, LOGISTICS_DETECTION_COUNT);
detectionCount.comment = "The maximum number of buildcraft pipees (including forks) between logistics pipes. This is an indicator of the maximum ammount of nodes the recursion algorithm will visit before giving up. As it is possible to fork a pipe connection using standard BC pipes the algorithm will attempt to discover all available destinations through that pipe. Do note that the logistics system will not interfere with the operation of non-logistics pipes. So a forked pipe will usually be sup-optimal, but it is possible. A low value might reduce CPU usage, a high value will be able to handle more complex pipe setups. If you never fork your connection between the logistics pipes this has the same meaning as detectionLength and the lower of the two will be used";
Property detectionFrequency = configuration.get("detectionFrequency", Configuration.CATEGORY_GENERAL, LOGISTICS_DETECTION_FREQUENCY);
detectionFrequency.comment = "The amount of time that passes between checks to see if it is still connected to its neighbours. A low value will mean that it will detect changes faster but use more CPU. A high value means detection takes longer, but CPU consumption is reduced. A value of 20 will check about every second";
Property countInvertWheelProperty = configuration.get("ordererCountInvertWheel", Configuration.CATEGORY_GENERAL, LOGISTICS_ORDERER_COUNT_INVERTWHEEL);
countInvertWheelProperty.comment = "Inverts the the mouse wheel scrolling for remote order number of items";
Property pageInvertWheelProperty = configuration.get("ordererPageInvertWheel", Configuration.CATEGORY_GENERAL, LOGISTICS_ORDERER_PAGE_INVERTWHEEL);
pageInvertWheelProperty.comment = "Inverts the the mouse wheel scrolling for remote order pages";
Property pageDisplayPopupProperty = configuration.get("displayPopup", Configuration.CATEGORY_GENERAL, displayPopup);
pageDisplayPopupProperty.comment = "Set the default configuration for the popup of the Orderer Gui. Should it be used?";
if(configuration.categories.get(Configuration.CATEGORY_BLOCK).containsKey("logisticsBlockId")) {
Property logisticsBlockId = configuration.get("logisticsBlockId", Configuration.CATEGORY_BLOCK, LOGISTICS_SIGN_ID);
LOGISTICS_SIGN_ID = Integer.parseInt(logisticsBlockId.value);
configuration.categories.get(Configuration.CATEGORY_BLOCK).remove("logisticsBlockId");
}
Property logisticsSignId = configuration.get("logisticsSignId", Configuration.CATEGORY_BLOCK, LOGISTICS_SIGN_ID);
logisticsSignId.comment = "The ID of the LogisticsPipes Sign";
Property logisticsSolidBlockId = configuration.get("logisticsSolidBlockId", Configuration.CATEGORY_BLOCK, LOGISTICS_SOLID_BLOCK_ID);
logisticsSolidBlockId.comment = "The ID of the LogisticsPipes Solid Block";
Property logsiticsPowerUsageDisable = configuration.get("powerUsageDisabled", Configuration.CATEGORY_GENERAL, LOGISTICS_POWER_USAGE_DISABLED);
logsiticsPowerUsageDisable.comment = "Diable the power usage trough LogisticsPipes";
Property logsiticsTileGenericReplacementDisable = configuration.get("TileReplaceDisabled", Configuration.CATEGORY_GENERAL, LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED);
logsiticsTileGenericReplacementDisable.comment = "Diable the Replacement of the TileGenericPipe trough the LogisticsTileGenericPipe";
Property logsiticsHUDRenderDistance = configuration.get("HUDRenderDistance", Configuration.CATEGORY_GENERAL, LOGISTICS_HUD_RENDER_DISTANCE);
logsiticsHUDRenderDistance.comment = "The max. distance between a player and the HUD that get's shown in blocks.";
configuration.save();
LOGISTICSNETWORKMONITOR_ID = Integer.parseInt(logisticNetworkMonitorIdProperty.value);
LOGISTICSREMOTEORDERER_ID = Integer.parseInt(logisticRemoteOrdererIdProperty.value);
ItemModuleId = Integer.parseInt(logisticModuleIdProperty.value);
ItemDiskId = Integer.parseInt(logisticItemDiskIdProperty.value);
ItemCardId = Integer.parseInt(logisticItemCardIdProperty.value);
ItemHUDId = Integer.parseInt(logisticItemHUDIdProperty.value);
ItemPartsId = Integer.parseInt(logisticItemPartsIdProperty.value);
LOGISTICSPIPE_BASIC_ID = Integer.parseInt(logisticPipeIdProperty.value);
LOGISTICSPIPE_REQUEST_ID = Integer.parseInt(logisticPipeRequesterIdProperty.value);
LOGISTICSPIPE_PROVIDER_ID = Integer.parseInt(logisticPipeProviderIdProperty.value);
LOGISTICSPIPE_CRAFTING_ID = Integer.parseInt(logisticPipeCraftingIdProperty.value);
LOGISTICSPIPE_SATELLITE_ID = Integer.parseInt(logisticPipeSatelliteIdProperty.value);
LOGISTICSPIPE_SUPPLIER_ID = Integer.parseInt(logisticPipeSupplierIdProperty.value);
LOGISTICSPIPE_CHASSI1_ID = Integer.parseInt(logisticPipeChassi1IdProperty.value);
LOGISTICSPIPE_CHASSI2_ID = Integer.parseInt(logisticPipeChassi2IdProperty.value);
LOGISTICSPIPE_CHASSI3_ID = Integer.parseInt(logisticPipeChassi3IdProperty.value);
LOGISTICSPIPE_CHASSI4_ID = Integer.parseInt(logisticPipeChassi4IdProperty.value);
LOGISTICSPIPE_CHASSI5_ID = Integer.parseInt(logisticPipeChassi5IdProperty.value);
LOGISTICSPIPE_CRAFTING_MK2_ID = Integer.parseInt(logisticPipeCraftingMK2IdProperty.value);
LOGISTICSPIPE_CRAFTING_MK3_ID = Integer.parseInt(logisticPipeCraftingMK3IdProperty.value);
LOGISTICSPIPE_REQUEST_MK2_ID = Integer.parseInt(logisticPipeRequesterMK2IdProperty.value);
LOGISTICSPIPE_PROVIDER_MK2_ID = Integer.parseInt(logisticPipeProviderMK2IdProperty.value);
LOGISTICSPIPE_REMOTE_ORDERER_ID = Integer.parseInt(logisticPipeRemoteOrdererIdProperty.value);
LOGISTICSPIPE_APIARIST_ANALYSER_ID = Integer.parseInt(logisticPipeApiaristAnalyserIdProperty.value);
LOGISTICSPIPE_APIARIST_SINK_ID = Integer.parseInt(logisticPipeApiaristSinkIdProperty.value);
LOGISTICSPIPE_ENTRANCE_ID = Integer.parseInt(logisticEntranceIdProperty.value);
LOGISTICSPIPE_DESTINATION_ID = Integer.parseInt(logisticDestinationIdProperty.value);
LOGISTICSPIPE_INVSYSCON_ID = Integer.parseInt(logisticInvSysConIdProperty.value);
LOGISTICS_SIGN_ID = Integer.parseInt(logisticsSignId.value);
LOGISTICS_SOLID_BLOCK_ID = Integer.parseInt(logisticsSolidBlockId.value);
LOGISTICS_DETECTION_LENGTH = Integer.parseInt(detectionLength.value);
LOGISTICS_DETECTION_COUNT = Integer.parseInt(detectionCount.value);
LOGISTICS_DETECTION_FREQUENCY = Math.max(Integer.parseInt(detectionFrequency.value), 1);
LOGISTICS_ORDERER_COUNT_INVERTWHEEL = Boolean.parseBoolean(countInvertWheelProperty.value);
LOGISTICS_ORDERER_PAGE_INVERTWHEEL = Boolean.parseBoolean(pageInvertWheelProperty.value);
LOGISTICS_POWER_USAGE_DISABLED = Boolean.parseBoolean(logsiticsPowerUsageDisable.value);
LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED = Boolean.parseBoolean(logsiticsTileGenericReplacementDisable.value);
LOGISTICSCRAFTINGSIGNCREATOR_ID = Integer.parseInt(logisticCraftingSignCreatorIdProperty.value);
LOGISTICS_HUD_RENDER_DISTANCE = Integer.parseInt(logsiticsHUDRenderDistance.value);
displayPopup = Boolean.parseBoolean(pageDisplayPopupProperty.value);
LOGISTICSPIPE_BUILDERSUPPLIER_ID = Integer.parseInt(logisticPipeBuilderSupplierIdProperty.value);
LOGISTICSPIPE_LIQUIDSUPPLIER_ID = Integer.parseInt(logisticPipeLiquidSupplierIdProperty.value);
}
|
diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseClassLoader.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseClassLoader.java
index 0b068109..43a2039b 100644
--- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseClassLoader.java
+++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseClassLoader.java
@@ -1,383 +1,381 @@
/*******************************************************************************
* Copyright (c) 2003, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.runtime.adaptor;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import org.eclipse.osgi.framework.adaptor.*;
import org.eclipse.osgi.framework.adaptor.core.*;
import org.eclipse.osgi.framework.internal.core.AbstractBundle;
import org.eclipse.osgi.framework.internal.core.Msg;
import org.eclipse.osgi.framework.internal.defaultadaptor.DefaultClassLoader;
import org.eclipse.osgi.framework.internal.defaultadaptor.DevClassPathHelper;
import org.eclipse.osgi.framework.log.FrameworkLogEntry;
import org.eclipse.osgi.framework.stats.*;
import org.eclipse.osgi.util.NLS;
import org.osgi.framework.*;
/**
* Internal class.
*/
public class EclipseClassLoader extends DefaultClassLoader {
private static String[] NL_JAR_VARIANTS = buildNLJarVariants(EnvironmentInfo.getDefault().getNL());
private static boolean DEFINE_PACKAGES;
private static final String VARIABLE_DELIM_STRING = "$"; //$NON-NLS-1$
private static final char VARIABLE_DELIM_CHAR = '$';
static {
try {
Class.forName("java.lang.Package"); //$NON-NLS-1$
DEFINE_PACKAGES = true;
} catch (ClassNotFoundException e) {
DEFINE_PACKAGES = false;
}
}
public EclipseClassLoader(ClassLoaderDelegate delegate, ProtectionDomain domain, String[] classpath, ClassLoader parent, BundleData bundleData) {
super(delegate, domain, classpath, parent, (EclipseBundleData) bundleData);
}
public Class findLocalClass(String className) throws ClassNotFoundException {
if (StatsManager.MONITOR_CLASSES) //Suport for performance analysis
ClassloaderStats.startLoadingClass(getClassloaderId(), className);
boolean found = true;
try {
AbstractBundle bundle = (AbstractBundle) hostdata.getBundle();
// If the bundle is active, uninstalled or stopping then the bundle has already
// been initialized (though it may have been destroyed) so just return the class.
if ((bundle.getState() & (Bundle.ACTIVE | Bundle.UNINSTALLED | Bundle.STOPPING)) != 0)
return basicFindLocalClass(className);
// The bundle is not active and does not require activation, just return the class
if (!shouldActivateFor(className))
return basicFindLocalClass(className);
// The bundle is starting. Note that if the state changed between the tests
// above and this test (e.g., it was not ACTIVE but now is), that's ok, we will
// just try to start it again (else case).
// TODO need an explanation here of why we duplicated the mechanism
// from the framework rather than just calling start() and letting it sort it out.
if (bundle.getState() == Bundle.STARTING) {
// If the thread trying to load the class is the one trying to activate the bundle, then return the class
if (bundle.testStateChanging(Thread.currentThread()) || bundle.testStateChanging(null))
return basicFindLocalClass(className);
// If it's another thread, we wait and try again. In any case the class is returned.
// The difference is that an exception can be logged.
// TODO do we really need this test? We just did it on the previous line?
if (!bundle.testStateChanging(Thread.currentThread())) {
Thread threadChangingState = bundle.getStateChanging();
if (StatsManager.TRACE_BUNDLES && threadChangingState != null) {
System.out.println("Concurrent startup of bundle " + bundle.getSymbolicName() + " by " + Thread.currentThread() + " and " + threadChangingState.getName() + ". Waiting up to 5000ms for " + threadChangingState + " to finish the initialization."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
}
long start = System.currentTimeMillis();
long delay = 5000;
long timeLeft = delay;
while (true) {
try {
- synchronized (this) {
- this.wait(100); // temporarily giveup the classloader lock
- }
+ Thread.sleep(100); // do not release the classloader lock (bug 86713)
if (bundle.testStateChanging(null) || timeLeft <= 0)
break;
} catch (InterruptedException e) {
//Ignore and keep waiting
}
timeLeft = start + delay - System.currentTimeMillis();
}
if (timeLeft <= 0 || bundle.getState() != Bundle.ACTIVE) {
String bundleName = bundle.getSymbolicName() == null ? Long.toString(bundle.getBundleId()) : bundle.getSymbolicName();
String message = NLS.bind(EclipseAdaptorMsg.ECLIPSE_CLASSLOADER_CONCURRENT_STARTUP, new Object[] {Thread.currentThread().getName(), className, threadChangingState.getName(), bundleName, Long.toString(delay)});
EclipseAdaptor.getDefault().getFrameworkLog().log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, message, 0, new Exception(EclipseAdaptorMsg.ECLIPSE_CLASSLOADER_GENERATED_EXCEPTION), null));
}
return basicFindLocalClass(className);
}
}
//The bundle must be started.
try {
hostdata.getBundle().start();
} catch (BundleException e) {
String message = NLS.bind(EclipseAdaptorMsg.ECLIPSE_CLASSLOADER_ACTIVATION, bundle.getSymbolicName(), Long.toString(bundle.getBundleId())); //$NON-NLS-1$
EclipseAdaptor.getDefault().getFrameworkLog().log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, message, 0, e, null));
throw new ClassNotFoundException(className, e);
}
return basicFindLocalClass(className);
} catch (ClassNotFoundException e) {
found = false;
throw e;
} finally {
if (StatsManager.MONITOR_CLASSES)
ClassloaderStats.endLoadingClass(getClassloaderId(), className, found);
}
}
/**
* Do the basic work for finding a class. This avoids the activation detection etc
* and can be used by subclasses to override the default (from the superclass)
* way of finding classes.
* @param name the class to look for
* @return the found class
* @throws ClassNotFoundException if the requested class cannot be found
*/
protected Class basicFindLocalClass(String name) throws ClassNotFoundException {
return super.findLocalClass(name);
}
/**
* Determines if for loading the given class we should activate the bundle.
*/
private boolean shouldActivateFor(String className) throws ClassNotFoundException {
//Don't reactivate on shut down
if (hostdata.getAdaptor().isStopping()) {
BundleStopper stopper = EclipseAdaptor.getDefault().getBundleStopper();
if (stopper != null && stopper.isStopped(hostdata.getBundle())) {
String message = NLS.bind(EclipseAdaptorMsg.ECLIPSE_CLASSLOADER_ALREADY_STOPPED, className, hostdata.getSymbolicName());
ClassNotFoundException exception = new ClassNotFoundException(message);
EclipseAdaptor.getDefault().getFrameworkLog().log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, message, 0, exception, null)); //$NON-NLS-1$
throw exception;
}
}
boolean autoStart = ((EclipseBundleData) hostdata).isAutoStart();
String[] autoStartExceptions = ((EclipseBundleData) hostdata).getAutoStartExceptions();
// no exceptions, it is easy to figure it out
if (autoStartExceptions == null)
return autoStart;
// otherwise, we need to check if the package is in the exceptions list
int dotPosition = className.lastIndexOf('.');
// the class has no package name... no exceptions apply
if (dotPosition == -1)
return autoStart;
String packageName = className.substring(0, dotPosition);
// should activate if autoStart and package is not an exception, or if !autoStart and package is exception
return autoStart ^ contains(autoStartExceptions, packageName);
}
private boolean contains(String[] array, String element) {
for (int i = 0; i < array.length; i++)
if (array[i].equals(element))
return true;
return false;
}
/**
* Override defineClass to allow for package defining.
*/
protected Class defineClass(String name, byte[] classbytes, int off, int len, ClasspathEntry classpathEntry) throws ClassFormatError {
if (!DEFINE_PACKAGES)
return super.defineClass(name, classbytes, off, len, classpathEntry);
// Define the package if it is not the default package.
int lastIndex = name.lastIndexOf('.');
if (lastIndex != -1) {
String packageName = name.substring(0, lastIndex);
Package pkg = getPackage(packageName);
if (pkg == null) {
// get info about the package from the classpath entry's manifest.
String specTitle = null, specVersion = null, specVendor = null, implTitle = null, implVersion = null, implVendor = null;
Manifest mf = ((EclipseClasspathEntry) classpathEntry).getManifest();
if (mf != null) {
Attributes mainAttributes = mf.getMainAttributes();
String dirName = packageName.replace('.', '/') + '/';
Attributes packageAttributes = mf.getAttributes(dirName);
boolean noEntry = false;
if (packageAttributes == null) {
noEntry = true;
packageAttributes = mainAttributes;
}
specTitle = packageAttributes.getValue(Attributes.Name.SPECIFICATION_TITLE);
if (specTitle == null && !noEntry)
specTitle = mainAttributes.getValue(Attributes.Name.SPECIFICATION_TITLE);
specVersion = packageAttributes.getValue(Attributes.Name.SPECIFICATION_VERSION);
if (specVersion == null && !noEntry)
specVersion = mainAttributes.getValue(Attributes.Name.SPECIFICATION_VERSION);
specVendor = packageAttributes.getValue(Attributes.Name.SPECIFICATION_VENDOR);
if (specVendor == null && !noEntry)
specVendor = mainAttributes.getValue(Attributes.Name.SPECIFICATION_VENDOR);
implTitle = packageAttributes.getValue(Attributes.Name.IMPLEMENTATION_TITLE);
if (implTitle == null && !noEntry)
implTitle = mainAttributes.getValue(Attributes.Name.IMPLEMENTATION_TITLE);
implVersion = packageAttributes.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
if (implVersion == null && !noEntry)
implVersion = mainAttributes.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
implVendor = packageAttributes.getValue(Attributes.Name.IMPLEMENTATION_VENDOR);
if (implVendor == null && !noEntry)
implVendor = mainAttributes.getValue(Attributes.Name.IMPLEMENTATION_VENDOR);
}
// The package is not defined yet define it before we define the class.
// TODO still need to seal packages.
definePackage(packageName, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, null);
}
}
return super.defineClass(name, classbytes, off, len, classpathEntry);
}
private String getClassloaderId() {
return hostdata.getBundle().getSymbolicName();
}
public URL getResource(String name) {
URL result = super.getResource(name);
if (StatsManager.MONITOR_RESOURCES) {
if (result != null && name.endsWith(".properties")) { //$NON-NLS-1$
ClassloaderStats.loadedBundle(getClassloaderId(), new ResourceBundleStats(getClassloaderId(), name, result));
}
}
return result;
}
protected void findClassPathEntry(ArrayList result, String entry, AbstractBundleData bundledata, ProtectionDomain domain) {
String var = hasPrefix(entry);
if (var != null) {
// find internal library using eclipse predefined vars
findInternalClassPath(var, result, entry, bundledata, domain);
return;
}
if (entry.length() > 0 && entry.charAt(0) == VARIABLE_DELIM_CHAR) {
// find external library using system property substitution
ClasspathEntry cpEntry = getExternalClassPath(substituteVars(entry), bundledata, domain);
if (cpEntry != null)
result.add(cpEntry);
return;
}
// if we get here just do the default searching
super.findClassPathEntry(result, entry, bundledata, domain);
}
private void findInternalClassPath(String var, ArrayList result, String entry, AbstractBundleData bundledata, ProtectionDomain domain) {
if (var.equals("ws")) { //$NON-NLS-1$
super.findClassPathEntry(result, "ws/" + EnvironmentInfo.getDefault().getWS() + entry.substring(4), bundledata, domain); //$NON-NLS-1$
return;
}
if (var.equals("os")) { //$NON-NLS-1$
super.findClassPathEntry(result, "os/" + EnvironmentInfo.getDefault().getOS() + entry.substring(4), bundledata, domain); //$NON-NLS-1$
return;
}
if (var.equals("nl")) { //$NON-NLS-1$
entry = entry.substring(4);
for (int i = 0; i < NL_JAR_VARIANTS.length; i++) {
if (addClassPathEntry(result, "nl/" + NL_JAR_VARIANTS[i] + entry, bundledata, domain)) //$NON-NLS-1$ //$NON-NLS-2$
return;
}
// is we are not in development mode, post some framework errors.
if (!DevClassPathHelper.inDevelopmentMode()) {
//BundleException be = new BundleException(Msg.formatter.getString("BUNDLE_CLASSPATH_ENTRY_NOT_FOUND_EXCEPTION", entry, hostdata.getLocation())); //$NON-NLS-1$
BundleException be = new BundleException(NLS.bind(Msg.BUNDLE_CLASSPATH_ENTRY_NOT_FOUND_EXCEPTION, entry)); //$NON-NLS-1$
bundledata.getAdaptor().getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, bundledata.getBundle(), be);
}
}
}
private static String[] buildNLJarVariants(String nl) {
ArrayList result = new ArrayList();
nl = nl.replace('_', '/');
while (nl.length() > 0) {
result.add("nl/" + nl + "/"); //$NON-NLS-1$ //$NON-NLS-2$
int i = nl.lastIndexOf('/'); //$NON-NLS-1$
nl = (i < 0) ? "" : nl.substring(0, i); //$NON-NLS-1$
}
result.add(""); //$NON-NLS-1$
return (String[]) result.toArray(new String[result.size()]);
}
//return a String representing the string found between the $s
private String hasPrefix(String libPath) {
if (libPath.startsWith("$ws$")) //$NON-NLS-1$
return "ws"; //$NON-NLS-1$
if (libPath.startsWith("$os$")) //$NON-NLS-1$
return "os"; //$NON-NLS-1$
if (libPath.startsWith("$nl$")) //$NON-NLS-1$
return "nl"; //$NON-NLS-1$
return null;
}
private String substituteVars(String cp) {
StringBuffer buf = new StringBuffer(cp.length());
StringTokenizer st = new StringTokenizer(cp, VARIABLE_DELIM_STRING, true);
boolean varStarted = false; // indicates we are processing a var subtitute
String var = null; // the current var key
while (st.hasMoreElements()) {
String tok = st.nextToken();
if (VARIABLE_DELIM_STRING.equals(tok)) {
if (!varStarted) {
varStarted = true; // we found the start of a var
var = ""; //$NON-NLS-1$
} else {
// we have found the end of a var
String prop = null;
// get the value of the var from system properties
if (var != null && var.length() > 0)
prop = System.getProperty(var);
if (prop != null)
// found a value; use it
buf.append(prop);
else
// could not find a value append the var name w/o delims
buf.append(var == null ? "" : var); //$NON-NLS-1$
varStarted = false;
var = null;
}
} else {
if (!varStarted)
buf.append(tok); // the token is not part of a var
else
var = tok; // the token is the var key; save the key to process when we find the end token
}
}
if (var != null)
// found a case of $var at the end of the cp with no trailing $; just append it as is.
buf.append(VARIABLE_DELIM_CHAR).append(var);
return buf.toString();
}
/**
* Override to create EclipseClasspathEntry objects. EclipseClasspathEntry
* allows access to the manifest file for the classpath entry.
*/
protected ClasspathEntry createClassPathEntry(BundleFile bundlefile, ProtectionDomain domain) {
return new EclipseClasspathEntry(bundlefile, domain);
}
/**
* A ClasspathEntry that has a manifest associated with it.
*/
protected class EclipseClasspathEntry extends ClasspathEntry {
Manifest mf;
boolean initMF = false;
protected EclipseClasspathEntry(BundleFile bundlefile, ProtectionDomain domain) {
super(bundlefile, domain);
}
public Manifest getManifest() {
if (initMF)
return mf;
BundleEntry mfEntry = getBundleFile().getEntry(org.eclipse.osgi.framework.internal.core.Constants.OSGI_BUNDLE_MANIFEST);
if (mfEntry != null)
try {
InputStream manIn = mfEntry.getInputStream();
mf = new Manifest(manIn);
manIn.close();
} catch (IOException e) {
// do nothing
}
initMF = true;
return mf;
}
}
}
| true | true | public Class findLocalClass(String className) throws ClassNotFoundException {
if (StatsManager.MONITOR_CLASSES) //Suport for performance analysis
ClassloaderStats.startLoadingClass(getClassloaderId(), className);
boolean found = true;
try {
AbstractBundle bundle = (AbstractBundle) hostdata.getBundle();
// If the bundle is active, uninstalled or stopping then the bundle has already
// been initialized (though it may have been destroyed) so just return the class.
if ((bundle.getState() & (Bundle.ACTIVE | Bundle.UNINSTALLED | Bundle.STOPPING)) != 0)
return basicFindLocalClass(className);
// The bundle is not active and does not require activation, just return the class
if (!shouldActivateFor(className))
return basicFindLocalClass(className);
// The bundle is starting. Note that if the state changed between the tests
// above and this test (e.g., it was not ACTIVE but now is), that's ok, we will
// just try to start it again (else case).
// TODO need an explanation here of why we duplicated the mechanism
// from the framework rather than just calling start() and letting it sort it out.
if (bundle.getState() == Bundle.STARTING) {
// If the thread trying to load the class is the one trying to activate the bundle, then return the class
if (bundle.testStateChanging(Thread.currentThread()) || bundle.testStateChanging(null))
return basicFindLocalClass(className);
// If it's another thread, we wait and try again. In any case the class is returned.
// The difference is that an exception can be logged.
// TODO do we really need this test? We just did it on the previous line?
if (!bundle.testStateChanging(Thread.currentThread())) {
Thread threadChangingState = bundle.getStateChanging();
if (StatsManager.TRACE_BUNDLES && threadChangingState != null) {
System.out.println("Concurrent startup of bundle " + bundle.getSymbolicName() + " by " + Thread.currentThread() + " and " + threadChangingState.getName() + ". Waiting up to 5000ms for " + threadChangingState + " to finish the initialization."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
}
long start = System.currentTimeMillis();
long delay = 5000;
long timeLeft = delay;
while (true) {
try {
synchronized (this) {
this.wait(100); // temporarily giveup the classloader lock
}
if (bundle.testStateChanging(null) || timeLeft <= 0)
break;
} catch (InterruptedException e) {
//Ignore and keep waiting
}
timeLeft = start + delay - System.currentTimeMillis();
}
if (timeLeft <= 0 || bundle.getState() != Bundle.ACTIVE) {
String bundleName = bundle.getSymbolicName() == null ? Long.toString(bundle.getBundleId()) : bundle.getSymbolicName();
String message = NLS.bind(EclipseAdaptorMsg.ECLIPSE_CLASSLOADER_CONCURRENT_STARTUP, new Object[] {Thread.currentThread().getName(), className, threadChangingState.getName(), bundleName, Long.toString(delay)});
EclipseAdaptor.getDefault().getFrameworkLog().log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, message, 0, new Exception(EclipseAdaptorMsg.ECLIPSE_CLASSLOADER_GENERATED_EXCEPTION), null));
}
return basicFindLocalClass(className);
}
}
//The bundle must be started.
try {
hostdata.getBundle().start();
} catch (BundleException e) {
String message = NLS.bind(EclipseAdaptorMsg.ECLIPSE_CLASSLOADER_ACTIVATION, bundle.getSymbolicName(), Long.toString(bundle.getBundleId())); //$NON-NLS-1$
EclipseAdaptor.getDefault().getFrameworkLog().log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, message, 0, e, null));
throw new ClassNotFoundException(className, e);
}
return basicFindLocalClass(className);
} catch (ClassNotFoundException e) {
found = false;
throw e;
} finally {
if (StatsManager.MONITOR_CLASSES)
ClassloaderStats.endLoadingClass(getClassloaderId(), className, found);
}
}
| public Class findLocalClass(String className) throws ClassNotFoundException {
if (StatsManager.MONITOR_CLASSES) //Suport for performance analysis
ClassloaderStats.startLoadingClass(getClassloaderId(), className);
boolean found = true;
try {
AbstractBundle bundle = (AbstractBundle) hostdata.getBundle();
// If the bundle is active, uninstalled or stopping then the bundle has already
// been initialized (though it may have been destroyed) so just return the class.
if ((bundle.getState() & (Bundle.ACTIVE | Bundle.UNINSTALLED | Bundle.STOPPING)) != 0)
return basicFindLocalClass(className);
// The bundle is not active and does not require activation, just return the class
if (!shouldActivateFor(className))
return basicFindLocalClass(className);
// The bundle is starting. Note that if the state changed between the tests
// above and this test (e.g., it was not ACTIVE but now is), that's ok, we will
// just try to start it again (else case).
// TODO need an explanation here of why we duplicated the mechanism
// from the framework rather than just calling start() and letting it sort it out.
if (bundle.getState() == Bundle.STARTING) {
// If the thread trying to load the class is the one trying to activate the bundle, then return the class
if (bundle.testStateChanging(Thread.currentThread()) || bundle.testStateChanging(null))
return basicFindLocalClass(className);
// If it's another thread, we wait and try again. In any case the class is returned.
// The difference is that an exception can be logged.
// TODO do we really need this test? We just did it on the previous line?
if (!bundle.testStateChanging(Thread.currentThread())) {
Thread threadChangingState = bundle.getStateChanging();
if (StatsManager.TRACE_BUNDLES && threadChangingState != null) {
System.out.println("Concurrent startup of bundle " + bundle.getSymbolicName() + " by " + Thread.currentThread() + " and " + threadChangingState.getName() + ". Waiting up to 5000ms for " + threadChangingState + " to finish the initialization."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
}
long start = System.currentTimeMillis();
long delay = 5000;
long timeLeft = delay;
while (true) {
try {
Thread.sleep(100); // do not release the classloader lock (bug 86713)
if (bundle.testStateChanging(null) || timeLeft <= 0)
break;
} catch (InterruptedException e) {
//Ignore and keep waiting
}
timeLeft = start + delay - System.currentTimeMillis();
}
if (timeLeft <= 0 || bundle.getState() != Bundle.ACTIVE) {
String bundleName = bundle.getSymbolicName() == null ? Long.toString(bundle.getBundleId()) : bundle.getSymbolicName();
String message = NLS.bind(EclipseAdaptorMsg.ECLIPSE_CLASSLOADER_CONCURRENT_STARTUP, new Object[] {Thread.currentThread().getName(), className, threadChangingState.getName(), bundleName, Long.toString(delay)});
EclipseAdaptor.getDefault().getFrameworkLog().log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, message, 0, new Exception(EclipseAdaptorMsg.ECLIPSE_CLASSLOADER_GENERATED_EXCEPTION), null));
}
return basicFindLocalClass(className);
}
}
//The bundle must be started.
try {
hostdata.getBundle().start();
} catch (BundleException e) {
String message = NLS.bind(EclipseAdaptorMsg.ECLIPSE_CLASSLOADER_ACTIVATION, bundle.getSymbolicName(), Long.toString(bundle.getBundleId())); //$NON-NLS-1$
EclipseAdaptor.getDefault().getFrameworkLog().log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, message, 0, e, null));
throw new ClassNotFoundException(className, e);
}
return basicFindLocalClass(className);
} catch (ClassNotFoundException e) {
found = false;
throw e;
} finally {
if (StatsManager.MONITOR_CLASSES)
ClassloaderStats.endLoadingClass(getClassloaderId(), className, found);
}
}
|
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/LocalDiskRepositoryManager.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/LocalDiskRepositoryManager.java
index 44cb9a71e..e23e84974 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/LocalDiskRepositoryManager.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/LocalDiskRepositoryManager.java
@@ -1,369 +1,366 @@
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.git;
import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.SitePaths;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.jcraft.jsch.Session;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ConfigConstants;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryCache;
import org.eclipse.jgit.lib.RepositoryCache.FileKey;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.storage.file.LockFile;
import org.eclipse.jgit.storage.file.WindowCache;
import org.eclipse.jgit.storage.file.WindowCacheConfig;
import org.eclipse.jgit.transport.JschConfigSessionFactory;
import org.eclipse.jgit.transport.OpenSshConfig;
import org.eclipse.jgit.transport.SshSessionFactory;
import org.eclipse.jgit.util.FS;
import org.eclipse.jgit.util.IO;
import org.eclipse.jgit.util.RawParseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/** Manages Git repositories stored on the local filesystem. */
@Singleton
public class LocalDiskRepositoryManager implements GitRepositoryManager {
private static final Logger log =
LoggerFactory.getLogger(LocalDiskRepositoryManager.class);
private static final String UNNAMED =
"Unnamed repository; edit this file to name it for gitweb.";
public static class Module extends AbstractModule {
@Override
protected void configure() {
bind(GitRepositoryManager.class).to(LocalDiskRepositoryManager.class);
install(new LifecycleModule() {
@Override
protected void configure() {
listener().to(LocalDiskRepositoryManager.Lifecycle.class);
}
});
}
}
public static class Lifecycle implements LifecycleListener {
private final Config cfg;
@Inject
Lifecycle(@GerritServerConfig final Config cfg) {
this.cfg = cfg;
}
@Override
public void start() {
// Install our own factory which always runs in batch mode, as we
// have no UI available for interactive prompting.
SshSessionFactory.setInstance(new JschConfigSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host hc, Session session) {
// Default configuration is batch mode.
}
});
final WindowCacheConfig c = new WindowCacheConfig();
c.fromConfig(cfg);
WindowCache.reconfigure(c);
}
@Override
public void stop() {
}
}
private final File basePath;
private final Lock namesUpdateLock;
private volatile SortedSet<Project.NameKey> names;
@Inject
LocalDiskRepositoryManager(final SitePaths site,
@GerritServerConfig final Config cfg) {
basePath = site.resolve(cfg.getString("gerrit", null, "basePath"));
if (basePath == null) {
throw new IllegalStateException("gerrit.basePath must be configured");
}
namesUpdateLock = new ReentrantLock(true /* fair */);
names = list();
}
/** @return base directory under which all projects are stored. */
public File getBasePath() {
return basePath;
}
private File gitDirOf(Project.NameKey name) {
return new File(getBasePath(), name.get());
}
public Repository openRepository(Project.NameKey name)
throws RepositoryNotFoundException {
if (isUnreasonableName(name)) {
throw new RepositoryNotFoundException("Invalid name: " + name);
}
if (!names.contains(name)) {
// The this.names list does not hold the project-name but it can still exist
// on disk; for instance when the project has been created directly on the
// file-system through replication.
//
if (FileKey.resolve(gitDirOf(name), FS.DETECTED) != null) {
onCreateProject(name);
} else {
throw new RepositoryNotFoundException(gitDirOf(name));
}
}
final FileKey loc = FileKey.lenient(gitDirOf(name), FS.DETECTED);
try {
return RepositoryCache.open(loc);
} catch (IOException e1) {
final RepositoryNotFoundException e2;
e2 = new RepositoryNotFoundException("Cannot open repository " + name);
e2.initCause(e1);
throw e2;
}
}
public Repository createRepository(final Project.NameKey name)
throws RepositoryNotFoundException, RepositoryCaseMismatchException {
if (isUnreasonableName(name)) {
throw new RepositoryNotFoundException("Invalid name: " + name);
}
File dir = FileKey.resolve(gitDirOf(name), FS.DETECTED);
FileKey loc;
if (dir != null) {
// Already exists on disk, use the repository we found.
//
loc = FileKey.exact(dir, FS.DETECTED);
if (!names.contains(name)) {
throw new RepositoryCaseMismatchException(name);
}
} else {
// It doesn't exist under any of the standard permutations
// of the repository name, so prefer the standard bare name.
//
- String n = name.get();
- if (!n.endsWith(Constants.DOT_GIT_EXT)) {
- n = n + Constants.DOT_GIT_EXT;
- }
+ String n = name.get() + Constants.DOT_GIT_EXT;
loc = FileKey.exact(new File(basePath, n), FS.DETECTED);
}
try {
Repository db = RepositoryCache.open(loc, false);
db.create(true /* bare */);
StoredConfig config = db.getConfig();
config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION,
null, ConfigConstants.CONFIG_KEY_LOGALLREFUPDATES, true);
config.save();
onCreateProject(name);
return db;
} catch (IOException e1) {
final RepositoryNotFoundException e2;
e2 = new RepositoryNotFoundException("Cannot create repository " + name);
e2.initCause(e1);
throw e2;
}
}
private void onCreateProject(final Project.NameKey newProjectName) {
namesUpdateLock.lock();
try {
SortedSet<Project.NameKey> n = new TreeSet<Project.NameKey>(names);
n.add(newProjectName);
names = Collections.unmodifiableSortedSet(n);
} finally {
namesUpdateLock.unlock();
}
}
public String getProjectDescription(final Project.NameKey name)
throws RepositoryNotFoundException, IOException {
final Repository e = openRepository(name);
try {
return getProjectDescription(e);
} finally {
e.close();
}
}
private String getProjectDescription(final Repository e) throws IOException {
final File d = new File(e.getDirectory(), "description");
String description;
try {
description = RawParseUtils.decode(IO.readFully(d));
} catch (FileNotFoundException err) {
return null;
}
if (description != null) {
description = description.trim();
if (description.isEmpty()) {
description = null;
}
if (UNNAMED.equals(description)) {
description = null;
}
}
return description;
}
public void setProjectDescription(final Project.NameKey name,
final String description) {
// Update git's description file, in case gitweb is being used
//
try {
final Repository e = openRepository(name);
try {
final String old = getProjectDescription(e);
if ((old == null && description == null)
|| (old != null && old.equals(description))) {
return;
}
final LockFile f = new LockFile(new File(e.getDirectory(), "description"), FS.DETECTED);
if (f.lock()) {
String d = description;
if (d != null) {
d = d.trim();
if (d.length() > 0) {
d += "\n";
}
} else {
d = "";
}
f.write(Constants.encode(d));
f.commit();
}
} finally {
e.close();
}
} catch (RepositoryNotFoundException e) {
log.error("Cannot update description for " + name, e);
} catch (IOException e) {
log.error("Cannot update description for " + name, e);
}
}
private boolean isUnreasonableName(final Project.NameKey nameKey) {
final String name = nameKey.get();
if (name.length() == 0) return true; // no empty paths
if (name.charAt(name.length() -1) == '/') return true; // no suffix
if (name.indexOf('\\') >= 0) return true; // no windows/dos stlye paths
if (name.charAt(0) == '/') return true; // no absolute paths
if (new File(name).isAbsolute()) return true; // no absolute paths
if (name.startsWith("../")) return true; // no "l../etc/passwd"
if (name.contains("/../")) return true; // no "foo/../etc/passwd"
if (name.contains("/./")) return true; // "foo/./foo" is insane to ask
if (name.contains("//")) return true; // windows UNC path can be "//..."
if (name.contains("?")) return true; // common unix wildcard
if (name.contains("%")) return true; // wildcard or string parameter
if (name.contains("*")) return true; // wildcard
if (name.contains(":")) return true; // Could be used for aboslute paths in windows?
if (name.contains("<")) return true; // redirect input
if (name.contains(">")) return true; // redirect output
if (name.contains("|")) return true; // pipe
if (name.contains("$")) return true; // dollar sign
if (name.contains("\r")) return true; // carriage return
return false; // is a reasonable name
}
@Override
public SortedSet<Project.NameKey> list() {
// The results of this method are cached by ProjectCacheImpl. Control only
// enters here if the cache was flushed by the administrator to force
// scanning the filesystem. Don't rely on the cached names collection.
namesUpdateLock.lock();
try {
SortedSet<Project.NameKey> n = new TreeSet<Project.NameKey>();
scanProjects(basePath, "", n);
names = Collections.unmodifiableSortedSet(n);
return n;
} finally {
namesUpdateLock.unlock();
}
}
private void scanProjects(final File dir, final String prefix,
final SortedSet<Project.NameKey> names) {
final File[] ls = dir.listFiles();
if (ls == null) {
return;
}
for (File f : ls) {
String fileName = f.getName();
if (FileKey.isGitRepository(f, FS.DETECTED)) {
Project.NameKey nameKey = getProjectName(prefix, fileName);
if (isUnreasonableName(nameKey)) {
log.warn("Ignoring unreasonably named repository " + f.getAbsolutePath());
} else {
names.add(nameKey);
}
} else if (f.isDirectory()) {
scanProjects(f, prefix + f.getName() + "/", names);
}
}
}
private Project.NameKey getProjectName(final String prefix,
final String fileName) {
final String projectName;
if (fileName.equals(Constants.DOT_GIT)) {
projectName = prefix.substring(0, prefix.length() - 1);
} else if (fileName.endsWith(Constants.DOT_GIT_EXT)) {
int newLen = fileName.length() - Constants.DOT_GIT_EXT.length();
projectName = prefix + fileName.substring(0, newLen);
} else {
projectName = prefix + fileName;
}
return new Project.NameKey(projectName);
}
}
| true | true | public Repository createRepository(final Project.NameKey name)
throws RepositoryNotFoundException, RepositoryCaseMismatchException {
if (isUnreasonableName(name)) {
throw new RepositoryNotFoundException("Invalid name: " + name);
}
File dir = FileKey.resolve(gitDirOf(name), FS.DETECTED);
FileKey loc;
if (dir != null) {
// Already exists on disk, use the repository we found.
//
loc = FileKey.exact(dir, FS.DETECTED);
if (!names.contains(name)) {
throw new RepositoryCaseMismatchException(name);
}
} else {
// It doesn't exist under any of the standard permutations
// of the repository name, so prefer the standard bare name.
//
String n = name.get();
if (!n.endsWith(Constants.DOT_GIT_EXT)) {
n = n + Constants.DOT_GIT_EXT;
}
loc = FileKey.exact(new File(basePath, n), FS.DETECTED);
}
try {
Repository db = RepositoryCache.open(loc, false);
db.create(true /* bare */);
StoredConfig config = db.getConfig();
config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION,
null, ConfigConstants.CONFIG_KEY_LOGALLREFUPDATES, true);
config.save();
onCreateProject(name);
return db;
} catch (IOException e1) {
final RepositoryNotFoundException e2;
e2 = new RepositoryNotFoundException("Cannot create repository " + name);
e2.initCause(e1);
throw e2;
}
}
| public Repository createRepository(final Project.NameKey name)
throws RepositoryNotFoundException, RepositoryCaseMismatchException {
if (isUnreasonableName(name)) {
throw new RepositoryNotFoundException("Invalid name: " + name);
}
File dir = FileKey.resolve(gitDirOf(name), FS.DETECTED);
FileKey loc;
if (dir != null) {
// Already exists on disk, use the repository we found.
//
loc = FileKey.exact(dir, FS.DETECTED);
if (!names.contains(name)) {
throw new RepositoryCaseMismatchException(name);
}
} else {
// It doesn't exist under any of the standard permutations
// of the repository name, so prefer the standard bare name.
//
String n = name.get() + Constants.DOT_GIT_EXT;
loc = FileKey.exact(new File(basePath, n), FS.DETECTED);
}
try {
Repository db = RepositoryCache.open(loc, false);
db.create(true /* bare */);
StoredConfig config = db.getConfig();
config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION,
null, ConfigConstants.CONFIG_KEY_LOGALLREFUPDATES, true);
config.save();
onCreateProject(name);
return db;
} catch (IOException e1) {
final RepositoryNotFoundException e2;
e2 = new RepositoryNotFoundException("Cannot create repository " + name);
e2.initCause(e1);
throw e2;
}
}
|
diff --git a/branches/prephase3/src/com/tinfoil/sms/ExchangeKey.java b/branches/prephase3/src/com/tinfoil/sms/ExchangeKey.java
index fd965efe..9d954e71 100644
--- a/branches/prephase3/src/com/tinfoil/sms/ExchangeKey.java
+++ b/branches/prephase3/src/com/tinfoil/sms/ExchangeKey.java
@@ -1,128 +1,128 @@
/**
* Copyright (C) 2011 Tinfoilhat
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.tinfoil.sms;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ProgressDialog;
import android.content.Context;
public class ExchangeKey implements Runnable {
private Context c;
public static ProgressDialog keyDialog;
private ArrayList<Number> untrusted;
private ArrayList<Number> trusted;
private HashMap<String, Boolean> subSelected;
private boolean[] selected;
private ArrayList<TrustedContact> tc;
public void startThread(Context c, ArrayList<TrustedContact> tc, HashMap<String, Boolean> subSelected, boolean[] selected) //ArrayList<Number> untrusted, ArrayList<Number> trusted)
{
this.c = c;
//TODO generate the trusted and untrusted list by checking if the number has a key
//this.untrusted = untrusted;
this.subSelected = subSelected;
this.selected = selected;
this.tc = tc;
//this.trusted = trusted;
this.trusted = null;
this.untrusted = null;
Thread thread = new Thread(this);
thread.start();
}
public void run() {
/*
* TODO create trusted and untrusted list
*/
ArrayList<Number> num = null;
if(trusted == null && untrusted == null)
{
trusted = new ArrayList<Number>();
untrusted = new ArrayList<Number>();
for(int i = 0; i < tc.size(); i++)
{
num = tc.get(i).getNumber();
if(selected[i])
{
if(num.size() == 1)
{
if(!MessageService.dba.isTrustedContact(num.get(0).getNumber()))
{
trusted.add(num.get(0));
}
else
{
untrusted.add(num.get(0));
}
}
else
{
for(int j = 0; j < num.size(); j++)
{
- if(subSelected.get(num.get(j)))
+ if(subSelected.get(num.get(j).getNumber()))
{
if(!MessageService.dba.isTrustedContact(num.get(j).getNumber()))
{
trusted.add(num.get(j));
}
else
{
untrusted.add(num.get(j));
}
}
}
}
}
}
}
/*
* This is actually how removing contacts from trusted should look since it is just a
* deletion of keys. We don't care if the contact will now fail to decrypt messages that
* is the user's problem
*/
if(untrusted != null)
{
for(int i = 0; i < untrusted.size(); i++)
{
untrusted.get(i).clearPublicKey();
MessageService.dba.updateKey(untrusted.get(i));
}
}
//TODO update to actually use proper key exchange (via sms)
//Start Key exchanges 1 by 1, using the user specified time out.
if(trusted != null)
{
for(int i = 0; i < trusted.size(); i++)
{
trusted.get(i).setPublicKey();
MessageService.dba.updateKey(trusted.get(i));
}
}
keyDialog.dismiss();
}
}
| true | true | public void run() {
/*
* TODO create trusted and untrusted list
*/
ArrayList<Number> num = null;
if(trusted == null && untrusted == null)
{
trusted = new ArrayList<Number>();
untrusted = new ArrayList<Number>();
for(int i = 0; i < tc.size(); i++)
{
num = tc.get(i).getNumber();
if(selected[i])
{
if(num.size() == 1)
{
if(!MessageService.dba.isTrustedContact(num.get(0).getNumber()))
{
trusted.add(num.get(0));
}
else
{
untrusted.add(num.get(0));
}
}
else
{
for(int j = 0; j < num.size(); j++)
{
if(subSelected.get(num.get(j)))
{
if(!MessageService.dba.isTrustedContact(num.get(j).getNumber()))
{
trusted.add(num.get(j));
}
else
{
untrusted.add(num.get(j));
}
}
}
}
}
}
}
/*
* This is actually how removing contacts from trusted should look since it is just a
* deletion of keys. We don't care if the contact will now fail to decrypt messages that
* is the user's problem
*/
if(untrusted != null)
{
for(int i = 0; i < untrusted.size(); i++)
{
untrusted.get(i).clearPublicKey();
MessageService.dba.updateKey(untrusted.get(i));
}
}
//TODO update to actually use proper key exchange (via sms)
//Start Key exchanges 1 by 1, using the user specified time out.
if(trusted != null)
{
for(int i = 0; i < trusted.size(); i++)
{
trusted.get(i).setPublicKey();
MessageService.dba.updateKey(trusted.get(i));
}
}
keyDialog.dismiss();
}
| public void run() {
/*
* TODO create trusted and untrusted list
*/
ArrayList<Number> num = null;
if(trusted == null && untrusted == null)
{
trusted = new ArrayList<Number>();
untrusted = new ArrayList<Number>();
for(int i = 0; i < tc.size(); i++)
{
num = tc.get(i).getNumber();
if(selected[i])
{
if(num.size() == 1)
{
if(!MessageService.dba.isTrustedContact(num.get(0).getNumber()))
{
trusted.add(num.get(0));
}
else
{
untrusted.add(num.get(0));
}
}
else
{
for(int j = 0; j < num.size(); j++)
{
if(subSelected.get(num.get(j).getNumber()))
{
if(!MessageService.dba.isTrustedContact(num.get(j).getNumber()))
{
trusted.add(num.get(j));
}
else
{
untrusted.add(num.get(j));
}
}
}
}
}
}
}
/*
* This is actually how removing contacts from trusted should look since it is just a
* deletion of keys. We don't care if the contact will now fail to decrypt messages that
* is the user's problem
*/
if(untrusted != null)
{
for(int i = 0; i < untrusted.size(); i++)
{
untrusted.get(i).clearPublicKey();
MessageService.dba.updateKey(untrusted.get(i));
}
}
//TODO update to actually use proper key exchange (via sms)
//Start Key exchanges 1 by 1, using the user specified time out.
if(trusted != null)
{
for(int i = 0; i < trusted.size(); i++)
{
trusted.get(i).setPublicKey();
MessageService.dba.updateKey(trusted.get(i));
}
}
keyDialog.dismiss();
}
|
diff --git a/src/org/liberty/android/fantastischmemo/converter/SupermemoXMLImporter.java b/src/org/liberty/android/fantastischmemo/converter/SupermemoXMLImporter.java
index e8b013ce..2d3c93e8 100644
--- a/src/org/liberty/android/fantastischmemo/converter/SupermemoXMLImporter.java
+++ b/src/org/liberty/android/fantastischmemo/converter/SupermemoXMLImporter.java
@@ -1,179 +1,190 @@
/*
Copyright (C) 2010 Haowen Ning
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.liberty.android.fantastischmemo.converter;
import org.apache.mycommons.lang3.time.DateUtils;
import org.liberty.android.fantastischmemo.*;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.liberty.android.fantastischmemo.dao.CardDao;
import org.liberty.android.fantastischmemo.domain.Card;
import org.liberty.android.fantastischmemo.domain.Category;
import org.liberty.android.fantastischmemo.domain.LearningData;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.util.Log;
import android.content.Context;
public class SupermemoXMLImporter extends org.xml.sax.helpers.DefaultHandler implements AbstractConverter{
public Locator mLocator;
private Context mContext;
private List<Card> cardList;
private Card card;
private LearningData ld;
private int count = 1;
private int interval;
private SimpleDateFormat supermemoFormat = new SimpleDateFormat("dd.MM.yy");
private StringBuffer characterBuf;
private final String TAG = "org.liberty.android.fantastischmemo.SupermemoXMLConverter";
public SupermemoXMLImporter(Context context){
mContext = context;
}
@Override
public void convert(String src, String dest) throws Exception{
URL mXMLUrl = new URL("file:///" + src);
cardList = new LinkedList<Card>();
System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(this);
xr.parse(new InputSource(mXMLUrl.openStream()));
AnyMemoDBOpenHelper helper = AnyMemoDBOpenHelperManager.getHelper(mContext, dest);
try {
CardDao cardDao = helper.getCardDao();
cardDao.createCards(cardList);
} finally {
AnyMemoDBOpenHelperManager.releaseHelper(helper);
}
}
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException{
if(localName.equals("SuperMemoElement")){
card = new Card();
card.setCategory(new Category());
ld = new LearningData();
card.setLearningData(ld);
// Set a default interval, in case of malformed the xml file
interval = 1;
}
characterBuf = new StringBuffer();
}
public void endElement(String namespaceURI, String localName, String qName) throws SAXException{
if(localName.equals("SuperMemoElement")){
card.setOrdinal(count);
- // Calculate the next learning date from interval
- ld.setNextLearnDate(DateUtils.addDays(ld.getLastLearnDate(), interval));
+ // If this is a new card and the learning data is like this:
+ // <LearningData>
+ // <Repetitions>0</Repetitions>
+ // <Lapses>0</Lapses>
+ // <AFactor>4.620</AFactor>
+ // <UFactor>2.500</UFactor>
+ // </LearningData>
+ // We will use the defualt learning data for missing fields.
+ // Otherwise, we will caluculate it here.
+ if (ld.getLastLearnDate() != null) {
+ // Calculate the next learning date from interval
+ ld.setNextLearnDate(DateUtils.addDays(ld.getLastLearnDate(), interval));
+ }
cardList.add(card);
card = null;
ld = null;
count += 1;
}
if(localName.equals("Question")){
card.setQuestion(characterBuf.toString());
}
if(localName.equals("Answer")){
card.setAnswer(characterBuf.toString());
}
if(localName.equals("Lapses")){
ld.setLapses(Integer.parseInt(characterBuf.toString()));
}
if(localName.equals("Repetitions")){
ld.setAcqReps(Integer.parseInt(characterBuf.toString()));
}
if(localName.equals("Interval")){
interval = Integer.parseInt(characterBuf.toString());
}
if(localName.equals("AFactor")){
double g = Double.parseDouble(characterBuf.toString());
if(g <= 1.5){
ld.setGrade(1);
}
else if(g <= 5.5){
ld.setGrade(2);
}
else{
ld.setGrade(3);
}
}
if(localName.equals("UFactor")){
float e = Float.parseFloat(characterBuf.toString());
ld.setEasiness(e);
}
if(localName.equals("LastRepetition")){
try {
Date date = supermemoFormat.parse(characterBuf.toString());
ld.setLastLearnDate(date);
}
catch(ParseException e){
Log.e(TAG, "Parsing date error: " + characterBuf.toString(), e);
}
}
}
public void setDocumentLocator(Locator locator){
mLocator = locator;
}
public void characters(char ch[], int start, int length){
characterBuf.append(ch, start, length);
}
public void startDocument() throws SAXException{
}
public void endDocument() throws SAXException{
}
}
| true | true | public void endElement(String namespaceURI, String localName, String qName) throws SAXException{
if(localName.equals("SuperMemoElement")){
card.setOrdinal(count);
// Calculate the next learning date from interval
ld.setNextLearnDate(DateUtils.addDays(ld.getLastLearnDate(), interval));
cardList.add(card);
card = null;
ld = null;
count += 1;
}
if(localName.equals("Question")){
card.setQuestion(characterBuf.toString());
}
if(localName.equals("Answer")){
card.setAnswer(characterBuf.toString());
}
if(localName.equals("Lapses")){
ld.setLapses(Integer.parseInt(characterBuf.toString()));
}
if(localName.equals("Repetitions")){
ld.setAcqReps(Integer.parseInt(characterBuf.toString()));
}
if(localName.equals("Interval")){
interval = Integer.parseInt(characterBuf.toString());
}
if(localName.equals("AFactor")){
double g = Double.parseDouble(characterBuf.toString());
if(g <= 1.5){
ld.setGrade(1);
}
else if(g <= 5.5){
ld.setGrade(2);
}
else{
ld.setGrade(3);
}
}
if(localName.equals("UFactor")){
float e = Float.parseFloat(characterBuf.toString());
ld.setEasiness(e);
}
if(localName.equals("LastRepetition")){
try {
Date date = supermemoFormat.parse(characterBuf.toString());
ld.setLastLearnDate(date);
}
catch(ParseException e){
Log.e(TAG, "Parsing date error: " + characterBuf.toString(), e);
}
}
}
| public void endElement(String namespaceURI, String localName, String qName) throws SAXException{
if(localName.equals("SuperMemoElement")){
card.setOrdinal(count);
// If this is a new card and the learning data is like this:
// <LearningData>
// <Repetitions>0</Repetitions>
// <Lapses>0</Lapses>
// <AFactor>4.620</AFactor>
// <UFactor>2.500</UFactor>
// </LearningData>
// We will use the defualt learning data for missing fields.
// Otherwise, we will caluculate it here.
if (ld.getLastLearnDate() != null) {
// Calculate the next learning date from interval
ld.setNextLearnDate(DateUtils.addDays(ld.getLastLearnDate(), interval));
}
cardList.add(card);
card = null;
ld = null;
count += 1;
}
if(localName.equals("Question")){
card.setQuestion(characterBuf.toString());
}
if(localName.equals("Answer")){
card.setAnswer(characterBuf.toString());
}
if(localName.equals("Lapses")){
ld.setLapses(Integer.parseInt(characterBuf.toString()));
}
if(localName.equals("Repetitions")){
ld.setAcqReps(Integer.parseInt(characterBuf.toString()));
}
if(localName.equals("Interval")){
interval = Integer.parseInt(characterBuf.toString());
}
if(localName.equals("AFactor")){
double g = Double.parseDouble(characterBuf.toString());
if(g <= 1.5){
ld.setGrade(1);
}
else if(g <= 5.5){
ld.setGrade(2);
}
else{
ld.setGrade(3);
}
}
if(localName.equals("UFactor")){
float e = Float.parseFloat(characterBuf.toString());
ld.setEasiness(e);
}
if(localName.equals("LastRepetition")){
try {
Date date = supermemoFormat.parse(characterBuf.toString());
ld.setLastLearnDate(date);
}
catch(ParseException e){
Log.e(TAG, "Parsing date error: " + characterBuf.toString(), e);
}
}
}
|
diff --git a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java
index 34311af9d..d8a068514 100644
--- a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java
+++ b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java
@@ -1,714 +1,714 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.graph_builder.impl.osm;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
import org.opentripplanner.common.model.P2;
import org.opentripplanner.graph_builder.GraphBuilderUtils;
import org.opentripplanner.graph_builder.model.osm.*;
import org.opentripplanner.graph_builder.services.GraphBuilder;
import org.opentripplanner.graph_builder.services.StreetUtils;
import org.opentripplanner.graph_builder.services.TurnRestriction;
import org.opentripplanner.graph_builder.services.TurnRestrictionType;
import org.opentripplanner.graph_builder.services.osm.OpenStreetMapContentHandler;
import org.opentripplanner.graph_builder.services.osm.OpenStreetMapProvider;
import org.opentripplanner.routing.core.Edge;
import org.opentripplanner.routing.core.Graph;
import org.opentripplanner.routing.core.Vertex;
import org.opentripplanner.routing.edgetype.EndpointVertex;
import org.opentripplanner.routing.edgetype.PlainStreetEdge;
import org.opentripplanner.routing.edgetype.StreetTraversalPermission;
import org.opentripplanner.routing.impl.DistanceLibrary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
/**
* Builds a street graph from OpenStreetMap data.
*
*/
public class OpenStreetMapGraphBuilderImpl implements GraphBuilder {
private static Logger _log = LoggerFactory.getLogger(OpenStreetMapGraphBuilderImpl.class);
private List<OpenStreetMapProvider> _providers = new ArrayList<OpenStreetMapProvider>();
private Map<Object, Object> _uniques = new HashMap<Object, Object>();
private WayPropertySet wayPropertySet = new WayPropertySet();
private double bikeSafetyFactor = 4.0;
/**
* The source for OSM map data
*/
public void setProvider(OpenStreetMapProvider provider) {
_providers.add(provider);
}
/**
* Multiple sources for OSM map data
*/
public void setProviders(List<OpenStreetMapProvider> providers) {
_providers.addAll(providers);
}
/**
* Set the way properties from a {@link WayPropertySetSource} source.
*
* @param source the way properties source
*/
public void setDefaultWayPropertySetSource(WayPropertySetSource source) {
wayPropertySet = source.getWayPropertySet();
}
@Override
public void buildGraph(Graph graph) {
Handler handler = new Handler();
for (OpenStreetMapProvider provider : _providers) {
_log.debug("gathering osm from provider: " + provider);
provider.readOSM(handler);
}
_log.debug("building osm street graph");
handler.buildGraph(graph);
}
@SuppressWarnings("unchecked")
private <T> T unique(T value) {
Object v = _uniques.get(value);
if (v == null) {
_uniques.put(value, value);
v = value;
}
return (T) v;
}
public void setWayPropertySet(WayPropertySet wayDataSet) {
this.wayPropertySet = wayDataSet;
}
public WayPropertySet getWayPropertySet() {
return wayPropertySet;
}
private class Handler implements OpenStreetMapContentHandler {
private Map<Long, OSMNode> _nodes = new HashMap<Long, OSMNode>();
private Map<Long, OSMWay> _ways = new HashMap<Long, OSMWay>();
private Map<Long, OSMRelation> _relations = new HashMap<Long, OSMRelation>();
private Set<Long> _nodesWithNeighbors = new HashSet<Long>();
private Map<Long, List<TurnRestrictionTag>> turnRestrictionsByFromWay = new HashMap<Long, List<TurnRestrictionTag>>();
private Map<Long, List<TurnRestrictionTag>> turnRestrictionsByToWay = new HashMap<Long, List<TurnRestrictionTag>>();
private Map<TurnRestrictionTag, TurnRestriction> turnRestrictionsByTag = new HashMap<TurnRestrictionTag, TurnRestriction>();
public void buildGraph(Graph graph) {
// Remove all simple islands
_nodes.keySet().retainAll(_nodesWithNeighbors);
long wayIndex = 0;
// figure out which nodes that are actually intersections
Set<Long> possibleIntersectionNodes = new HashSet<Long>();
Set<Long> intersectionNodes = new HashSet<Long>();
for (OSMWay way : _ways.values()) {
List<Long> nodes = way.getNodeRefs();
for (long node : nodes) {
if (possibleIntersectionNodes.contains(node)) {
intersectionNodes.add(node);
} else {
possibleIntersectionNodes.add(node);
}
}
}
GeometryFactory geometryFactory = new GeometryFactory();
/* build an ordinary graph, which we will convert to an edge-based graph */
ArrayList<Vertex> endpoints = new ArrayList<Vertex>();
for (OSMWay way : _ways.values()) {
if (wayIndex % 1000 == 0)
_log.debug("ways=" + wayIndex + "/" + _ways.size());
wayIndex++;
WayProperties wayData = wayPropertySet.getDataForWay(way);
String creativeName = wayPropertySet.getCreativeNameForWay(way);
if (creativeName != null) {
way.addTag("otp:gen_name", creativeName);
}
Set<String> note = wayPropertySet.getNoteForWay(way);
StreetTraversalPermission permissions = getPermissionsForEntity(way, wayData.getPermission());
if (permissions == StreetTraversalPermission.NONE)
continue;
List<Long> nodes = way.getNodeRefs();
Vertex startEndpoint = null, endEndpoint = null;
ArrayList<Coordinate> segmentCoordinates = new ArrayList<Coordinate>();
/*
* Traverse through all the nodes of this edge. For nodes which are not shared with
* any other edge, do not create endpoints -- just accumulate them for geometry. For
* nodes which are shared, create endpoints and StreetVertex instances.
*/
Long startNode = null;
OSMNode osmStartNode = null;
for (int i = 0; i < nodes.size() - 1; i++) {
Long endNode = nodes.get(i + 1);
if (osmStartNode == null) {
startNode = nodes.get(i);
osmStartNode = _nodes.get(startNode);
}
OSMNode osmEndNode = _nodes.get(endNode);
if (osmStartNode == null || osmEndNode == null)
continue;
LineString geometry;
/*
* skip vertices that are not intersections, except that we use them for
* geometry
*/
if (segmentCoordinates.size() == 0) {
segmentCoordinates.add(getCoordinate(osmStartNode));
}
if (intersectionNodes.contains(endNode) || i == nodes.size() - 2) {
segmentCoordinates.add(getCoordinate(osmEndNode));
geometry = geometryFactory.createLineString(segmentCoordinates
.toArray(new Coordinate[0]));
segmentCoordinates.clear();
} else {
segmentCoordinates.add(getCoordinate(osmEndNode));
continue;
}
/* generate endpoints */
if (startEndpoint == null) {
//first iteration on this way
String label = "osm node " + osmStartNode.getId();
startEndpoint = graph.getVertex(label);
if (startEndpoint == null) {
Coordinate coordinate = getCoordinate(osmStartNode);
startEndpoint = new EndpointVertex(label, coordinate.x, coordinate.y,
label);
graph.addVertex(startEndpoint);
endpoints.add(startEndpoint);
}
} else {
startEndpoint = endEndpoint;
}
String label = "osm node " + osmEndNode.getId();
endEndpoint = graph.getVertex(label);
if (endEndpoint == null) {
Coordinate coordinate = getCoordinate(osmEndNode);
endEndpoint = new EndpointVertex(label, coordinate.x, coordinate.y, label);
graph.addVertex(endEndpoint);
endpoints.add(endEndpoint);
}
P2<PlainStreetEdge> streets = getEdgesForStreet(startEndpoint, endEndpoint,
way, i, permissions, geometry);
PlainStreetEdge street = streets.getFirst();
if (street != null) {
graph.addEdge(street);
Double safety = wayData.getSafetyFeatures().getFirst();
street.setBicycleSafetyEffectiveLength(street.getLength() * safety * getBikeSafetyFactor());
if (note != null) {
street.setNote(note);
}
}
PlainStreetEdge backStreet = streets.getSecond();
if (backStreet != null) {
graph.addEdge(backStreet);
Double safety = wayData.getSafetyFeatures().getSecond();
backStreet.setBicycleSafetyEffectiveLength(backStreet.getLength() * safety * getBikeSafetyFactor());
if (note != null) {
backStreet.setNote(note);
}
}
/* Check if there are turn restrictions starting on this segment */
List<TurnRestrictionTag> restrictionTags = turnRestrictionsByFromWay.get(way.getId());
if (restrictionTags != null) {
for (TurnRestrictionTag tag : restrictionTags) {
if (tag.via == startNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.from = backStreet;
} else if (tag.via == endNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.from = street;
}
}
}
- restrictionTags = turnRestrictionsByToWay.get(way);
+ restrictionTags = turnRestrictionsByToWay.get(way.getId());
if (restrictionTags != null) {
for (TurnRestrictionTag tag : restrictionTags) {
if (tag.via == startNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.to = street;
} else if (tag.via == endNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.to = backStreet;
}
}
}
startNode = endNode;
osmStartNode = _nodes.get(startNode);
}
}
/* unify turn restrictions */
Map<Edge, TurnRestriction> turnRestrictions = new HashMap<Edge, TurnRestriction>();
for (TurnRestriction restriction : turnRestrictionsByTag.values()) {
turnRestrictions.put(restriction.from, restriction);
}
StreetUtils.pruneFloatingIslands(graph);
StreetUtils.makeEdgeBased(graph, endpoints, turnRestrictions);
}
private Coordinate getCoordinate(OSMNode osmNode) {
return new Coordinate(osmNode.getLon(), osmNode.getLat());
}
public void addNode(OSMNode node) {
if(!_nodesWithNeighbors.contains(node.getId()))
return;
if (_nodes.containsKey(node.getId()))
return;
_nodes.put(node.getId(), node);
if (_nodes.size() % 10000 == 0)
_log.debug("nodes=" + _nodes.size());
}
public void addWay(OSMWay way) {
if (_ways.containsKey(way.getId()))
return;
_ways.put(way.getId(), way);
if (_ways.size() % 1000 == 0)
_log.debug("ways=" + _ways.size());
}
public void addRelation(OSMRelation relation) {
if (_relations.containsKey(relation.getId()))
return;
/* Currently only type=route;route=road relations are handled */
if ( !(relation.isTag("type", "restriction" ))
&& !(relation.isTag("type", "route" ) && relation.isTag("route", "road"))
&& !(relation.isTag("type", "multipolygon") && relation.hasTag("highway"))) {
return;
}
_relations.put(relation.getId(), relation);
if (_relations.size() % 100 == 0)
_log.debug("relations=" + _relations.size());
}
public void secondPhase() {
int count = _ways.values().size();
processRelations();
for(Iterator<OSMWay> it = _ways.values().iterator(); it.hasNext(); ) {
OSMWay way = it.next();
if (!(way.hasTag("highway") || way.isTag("railway", "platform"))) {
it.remove();
} else if (way.isTag("highway", "conveyer") || way.isTag("highway", "proposed")) {
it.remove();
} else {
// Since the way is kept, update nodes-with-neighbots
List<Long> nodes = way.getNodeRefs();
if (nodes.size() > 1) {
_nodesWithNeighbors.addAll(nodes);
}
}
}
_log.debug("purged " + (count - _ways.values().size() ) + " ways out of " + count);
}
/** Copies useful metadata from relations to the relavant ways/nodes.
*/
private void processRelations() {
_log.debug("Processing relations...");
for(OSMRelation relation : _relations.values()) {
if (relation.isTag("type", "restriction" )) {
processRestriction(relation);
} else {
processRoad(relation);
}
}
}
/** A temporary holder for turn restrictions while we have only way/node ids but not yet edge objects */
class TurnRestrictionTag {
private long via;
private TurnRestrictionType type;
TurnRestrictionTag(long via, TurnRestrictionType type) {
this.via = via;
this.type = type;
}
}
/**
* Handle turn restrictions
* @param relation
*/
private void processRestriction(OSMRelation relation) {
long from = -1, to = -1, via = -1;
for (OSMRelationMember member : relation.getMembers()) {
String role = member.getRole();
if (role.equals("from")) {
from = member.getRef();
} else if (role.equals("to")) {
to = member.getRef();
} else if (role.equals("via")) {
via = member.getRef();
}
}
if (from == -1 || to == -1 || via == -1) {
_log.debug("Bad restriction " + relation.getId());
return;
}
TurnRestrictionTag tag;
if (relation.isTag("restriction", "no_right_turn")) {
tag = new TurnRestrictionTag(via, TurnRestrictionType.NO_TURN);
} else if (relation.isTag("restriction", "no_left_turn")) {
tag = new TurnRestrictionTag(via, TurnRestrictionType.NO_TURN);
} else if (relation.isTag("restriction", "no_straight_on")) {
tag = new TurnRestrictionTag(via, TurnRestrictionType.NO_TURN);
} else if (relation.isTag("restriction", "no_u_turn")) {
tag = new TurnRestrictionTag(via, TurnRestrictionType.NO_TURN);
} else if (relation.isTag("restriction", "only_straight_on")) {
tag = new TurnRestrictionTag(via, TurnRestrictionType.ONLY_TURN);
} else if (relation.isTag("restriction", "only_right_turn")) {
tag = new TurnRestrictionTag(via, TurnRestrictionType.ONLY_TURN);
} else if (relation.isTag("restriction", "only_left_turn")) {
tag = new TurnRestrictionTag(via, TurnRestrictionType.ONLY_TURN);
} else {
_log.debug("unknown restriction type " + relation.getTag("restriction"));
return;
}
TurnRestriction restriction = new TurnRestriction();
restriction.type = tag.type;
turnRestrictionsByTag.put(tag, restriction);
GraphBuilderUtils.addToMapList(turnRestrictionsByFromWay, from, tag);
GraphBuilderUtils.addToMapList(turnRestrictionsByToWay, to, tag);
}
private void processRoad(OSMRelation relation) {
for (OSMRelationMember member : relation.getMembers()) {
if ("way".equals(member.getType()) && _ways.containsKey(member.getRef())) {
OSMWay way = _ways.get(member.getRef());
if (way != null) {
if (relation.hasTag("name")) {
if (way.hasTag("otp:route_name")) {
way.addTag("otp:route_name", addUniqueName(way
.getTag("otp:route_name"), relation.getTag("name")));
} else {
way.addTag(new OSMTag("otp:route_name", relation.getTag("name")));
}
}
if (relation.hasTag("ref")) {
if (way.hasTag("otp:route_ref")) {
way.addTag("otp:route_ref", addUniqueName(way
.getTag("otp:route_ref"), relation.getTag("ref")));
} else {
way.addTag(new OSMTag("otp:route_ref", relation.getTag("ref")));
}
}
if (relation.hasTag("highway") && relation.isTag("type", "multipolygon")
&& !way.hasTag("highway")) {
way.addTag("highway", relation.getTag("highway"));
}
}
}
}
}
private String addUniqueName(String routes, String name) {
String[] names = routes.split(", ");
for (String existing : names) {
if (existing.equals(name)) {
return routes;
}
}
return routes + ", " + name;
}
/**
* Handle oneway streets, cycleways, and whatnot. See
* http://wiki.openstreetmap.org/wiki/Bicycle for various scenarios, along with
* http://wiki.openstreetmap.org/wiki/OSM_tags_for_routing#Oneway.
*
* @param end
* @param start
*/
private P2<PlainStreetEdge> getEdgesForStreet(Vertex start, Vertex end, OSMWay way,
long startNode, StreetTraversalPermission permissions, LineString geometry) {
// get geometry length in meters, irritatingly.
Coordinate[] coordinates = geometry.getCoordinates();
double d = 0;
for (int i = 1; i < coordinates.length; ++i) {
d += DistanceLibrary.distance(coordinates[i - 1], coordinates[i]);
}
LineString backGeometry = (LineString) geometry.reverse();
Map<String, String> tags = way.getTags();
if (permissions == StreetTraversalPermission.NONE)
return new P2<PlainStreetEdge>(null, null);
PlainStreetEdge street = null, backStreet = null;
/*
pedestrian rules: everything is two-way (assuming pedestrians
are allowed at all)
bicycle rules: default: permissions;
cycleway=dismount means walk your bike -- the engine will
automatically try walking bikes any time it is forbidden to
ride them, so the only thing to do here is to remove bike
permissions
oneway=... sets permissions for cars and bikes
oneway:bicycle overwrites these permissions for bikes only
now, cycleway=opposite_lane, opposite, opposite_track can allow
once oneway has been set by oneway:bicycle, but should give a
warning if it conflicts with oneway:bicycle
bicycle:backward=yes works like oneway:bicycle=no
bicycle:backwards=no works like oneway:bicycle=yes
*/
boolean forceBikes = false;
if (way.isTag("bicycle", "yes") || way.isTag("bicycle", "designated")) {
permissions = permissions.add(StreetTraversalPermission.BICYCLE);
forceBikes = true;
}
if (way.isTag("cycleway", "dismount")) {
permissions = permissions.remove(StreetTraversalPermission.BICYCLE);
if (forceBikes) {
_log.warn("conflicting tags bicycle:[yes|designated] and cycleway:dismount on way " + way.getId() + ", assuming dismount");
}
}
StreetTraversalPermission permissionsFront = permissions;
StreetTraversalPermission permissionsBack = permissions;
boolean oneWayBike = true;
if (way.isTagTrue("oneway") || "roundabout".equals(tags.get("junction"))) {
permissionsBack = permissionsBack.remove(StreetTraversalPermission.BICYCLE_AND_CAR);
}
if (way.isTag("oneway", "-1")) {
permissionsFront = permissionsFront.remove(StreetTraversalPermission.BICYCLE_AND_CAR);
}
if (way.isTagTrue("oneway:bicycle") || way.isTagFalse("bicycle:backwards")) {
permissionsBack = permissionsBack.remove(StreetTraversalPermission.BICYCLE);
oneWayBike = true;
}
if (way.isTag("oneway:bicycle", "-1")) {
permissionsFront = permissionsFront.remove(StreetTraversalPermission.BICYCLE);
}
if (way.isTagFalse("oneway:bicycle") || way.isTagTrue("bicycle:backwards")) {
if (permissions.allows(StreetTraversalPermission.BICYCLE)) {
permissionsFront = permissionsFront.add(StreetTraversalPermission.BICYCLE);
permissionsBack = permissionsBack.add(StreetTraversalPermission.BICYCLE);
}
}
if (way.isTag("cycleway", "opposite") ||
way.isTag("cycleway", "opposite_lane") ||
way.isTag("cycleway", "opposite_track")) {
if (oneWayBike) {
_log.warn("conflicting tags oneway:bicycle and cycleway:opposite* on way " + way.getId() + ", assuming opposite");
}
if (permissions.allows(StreetTraversalPermission.BICYCLE)) {
permissionsBack = permissionsBack.add(StreetTraversalPermission.BICYCLE);
}
}
boolean noThruTraffic = way.isTag("access", "destination");
if (permissionsFront != StreetTraversalPermission.NONE) {
street = getEdgeForStreet(start, end, way, startNode, d, permissionsFront, geometry,
false);
street.setNoThruTraffic(noThruTraffic);
}
if (permissionsBack != StreetTraversalPermission.NONE) {
backStreet = getEdgeForStreet(end, start, way, startNode, d, permissionsBack, backGeometry,
true);
backStreet.setNoThruTraffic(noThruTraffic);
}
/* mark edges that are on roundabouts */
if ("roundabout".equals(tags.get("junction"))) {
if (street != null) street.setRoundabout(true);
if (backStreet != null) backStreet.setRoundabout(true);
}
return new P2<PlainStreetEdge>(street, backStreet);
}
private PlainStreetEdge getEdgeForStreet(Vertex start, Vertex end, OSMWay way,
long startNode, double length, StreetTraversalPermission permissions,
LineString geometry, boolean back) {
String id = "way " + way.getId() + " from " + startNode;
id = unique(id);
String name = way.getAssumedName();
if (name == null) {
name = id;
}
PlainStreetEdge street = new PlainStreetEdge(start, end, geometry, name, length,
permissions, back);
street.setId(id);
if (!way.hasTag("name")) {
street.setBogusName(true);
}
/* TODO: This should probably generalized somehow? */
if (way.isTagFalse("wheelchair") || ("steps".equals(way.getTag("highway")) && !way.isTagTrue("wheelchair"))) {
street.setWheelchairAccessible(false);
}
street.setSlopeOverride(wayPropertySet.getSlopeOverride(way));
return street;
}
private StreetTraversalPermission getPermissionsForEntity(OSMWithTags entity, StreetTraversalPermission def) {
Map<String, String> tags = entity.getTags();
StreetTraversalPermission permission = null;
String access = tags.get("access");
String motorcar = tags.get("motorcar");
String bicycle = tags.get("bicycle");
String foot = tags.get("foot");
/*
* Only access=*, motorcar=*, bicycle=*, and foot=* is examined, since those are the
* only modes supported by OTP (wheelchairs are not of concern here)
*
* Only a few values are checked for, all other values are presumed to be
* permissive (=> This may not be perfect, but is closer to reality, since most people
* don't follow the rules perfectly ;-)
*/
if (access != null) {
if ("no".equals(access) || "private".equals(access) || "delivery".equals(access) || "agricultural".equals(access)) {
permission = StreetTraversalPermission.NONE;
} else {
permission = def;
}
} else if (motorcar != null || bicycle != null || foot != null) {
permission = def;
}
if (motorcar != null) {
if ("no".equals(motorcar) || "private".equals(motorcar)) {
permission = permission.remove(StreetTraversalPermission.CAR);
} else {
permission = permission.add(StreetTraversalPermission.CAR);
}
}
if (bicycle != null) {
if ("no".equals(bicycle) || "private".equals(bicycle)) {
permission = permission.remove(StreetTraversalPermission.BICYCLE);
} else {
permission = permission.add(StreetTraversalPermission.BICYCLE);
}
}
if (foot != null) {
if ("no".equals(foot) || "private".equals(foot)) {
permission = permission.remove(StreetTraversalPermission.PEDESTRIAN);
} else {
permission = permission.add(StreetTraversalPermission.PEDESTRIAN);
}
}
if (permission == null)
return def;
return permission;
}
}
/**
* How much safer transit is than biking along an ordinary street. The default is 4.0, which
* probably does not reflect reality (especially for rail), but should generate plausible
* routes. Do not lower this value below the reciprocal of the safety of the safest street
* according to your bicycle safety settings.
*
* @param bikeSafetyFactor
*/
public void setBikeSafetyFactor(double bikeSafetyFactor) {
this.bikeSafetyFactor = bikeSafetyFactor;
}
public double getBikeSafetyFactor() {
return bikeSafetyFactor;
}
}
| true | true | public void buildGraph(Graph graph) {
// Remove all simple islands
_nodes.keySet().retainAll(_nodesWithNeighbors);
long wayIndex = 0;
// figure out which nodes that are actually intersections
Set<Long> possibleIntersectionNodes = new HashSet<Long>();
Set<Long> intersectionNodes = new HashSet<Long>();
for (OSMWay way : _ways.values()) {
List<Long> nodes = way.getNodeRefs();
for (long node : nodes) {
if (possibleIntersectionNodes.contains(node)) {
intersectionNodes.add(node);
} else {
possibleIntersectionNodes.add(node);
}
}
}
GeometryFactory geometryFactory = new GeometryFactory();
/* build an ordinary graph, which we will convert to an edge-based graph */
ArrayList<Vertex> endpoints = new ArrayList<Vertex>();
for (OSMWay way : _ways.values()) {
if (wayIndex % 1000 == 0)
_log.debug("ways=" + wayIndex + "/" + _ways.size());
wayIndex++;
WayProperties wayData = wayPropertySet.getDataForWay(way);
String creativeName = wayPropertySet.getCreativeNameForWay(way);
if (creativeName != null) {
way.addTag("otp:gen_name", creativeName);
}
Set<String> note = wayPropertySet.getNoteForWay(way);
StreetTraversalPermission permissions = getPermissionsForEntity(way, wayData.getPermission());
if (permissions == StreetTraversalPermission.NONE)
continue;
List<Long> nodes = way.getNodeRefs();
Vertex startEndpoint = null, endEndpoint = null;
ArrayList<Coordinate> segmentCoordinates = new ArrayList<Coordinate>();
/*
* Traverse through all the nodes of this edge. For nodes which are not shared with
* any other edge, do not create endpoints -- just accumulate them for geometry. For
* nodes which are shared, create endpoints and StreetVertex instances.
*/
Long startNode = null;
OSMNode osmStartNode = null;
for (int i = 0; i < nodes.size() - 1; i++) {
Long endNode = nodes.get(i + 1);
if (osmStartNode == null) {
startNode = nodes.get(i);
osmStartNode = _nodes.get(startNode);
}
OSMNode osmEndNode = _nodes.get(endNode);
if (osmStartNode == null || osmEndNode == null)
continue;
LineString geometry;
/*
* skip vertices that are not intersections, except that we use them for
* geometry
*/
if (segmentCoordinates.size() == 0) {
segmentCoordinates.add(getCoordinate(osmStartNode));
}
if (intersectionNodes.contains(endNode) || i == nodes.size() - 2) {
segmentCoordinates.add(getCoordinate(osmEndNode));
geometry = geometryFactory.createLineString(segmentCoordinates
.toArray(new Coordinate[0]));
segmentCoordinates.clear();
} else {
segmentCoordinates.add(getCoordinate(osmEndNode));
continue;
}
/* generate endpoints */
if (startEndpoint == null) {
//first iteration on this way
String label = "osm node " + osmStartNode.getId();
startEndpoint = graph.getVertex(label);
if (startEndpoint == null) {
Coordinate coordinate = getCoordinate(osmStartNode);
startEndpoint = new EndpointVertex(label, coordinate.x, coordinate.y,
label);
graph.addVertex(startEndpoint);
endpoints.add(startEndpoint);
}
} else {
startEndpoint = endEndpoint;
}
String label = "osm node " + osmEndNode.getId();
endEndpoint = graph.getVertex(label);
if (endEndpoint == null) {
Coordinate coordinate = getCoordinate(osmEndNode);
endEndpoint = new EndpointVertex(label, coordinate.x, coordinate.y, label);
graph.addVertex(endEndpoint);
endpoints.add(endEndpoint);
}
P2<PlainStreetEdge> streets = getEdgesForStreet(startEndpoint, endEndpoint,
way, i, permissions, geometry);
PlainStreetEdge street = streets.getFirst();
if (street != null) {
graph.addEdge(street);
Double safety = wayData.getSafetyFeatures().getFirst();
street.setBicycleSafetyEffectiveLength(street.getLength() * safety * getBikeSafetyFactor());
if (note != null) {
street.setNote(note);
}
}
PlainStreetEdge backStreet = streets.getSecond();
if (backStreet != null) {
graph.addEdge(backStreet);
Double safety = wayData.getSafetyFeatures().getSecond();
backStreet.setBicycleSafetyEffectiveLength(backStreet.getLength() * safety * getBikeSafetyFactor());
if (note != null) {
backStreet.setNote(note);
}
}
/* Check if there are turn restrictions starting on this segment */
List<TurnRestrictionTag> restrictionTags = turnRestrictionsByFromWay.get(way.getId());
if (restrictionTags != null) {
for (TurnRestrictionTag tag : restrictionTags) {
if (tag.via == startNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.from = backStreet;
} else if (tag.via == endNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.from = street;
}
}
}
restrictionTags = turnRestrictionsByToWay.get(way);
if (restrictionTags != null) {
for (TurnRestrictionTag tag : restrictionTags) {
if (tag.via == startNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.to = street;
} else if (tag.via == endNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.to = backStreet;
}
}
}
startNode = endNode;
osmStartNode = _nodes.get(startNode);
}
}
/* unify turn restrictions */
Map<Edge, TurnRestriction> turnRestrictions = new HashMap<Edge, TurnRestriction>();
for (TurnRestriction restriction : turnRestrictionsByTag.values()) {
turnRestrictions.put(restriction.from, restriction);
}
StreetUtils.pruneFloatingIslands(graph);
StreetUtils.makeEdgeBased(graph, endpoints, turnRestrictions);
}
| public void buildGraph(Graph graph) {
// Remove all simple islands
_nodes.keySet().retainAll(_nodesWithNeighbors);
long wayIndex = 0;
// figure out which nodes that are actually intersections
Set<Long> possibleIntersectionNodes = new HashSet<Long>();
Set<Long> intersectionNodes = new HashSet<Long>();
for (OSMWay way : _ways.values()) {
List<Long> nodes = way.getNodeRefs();
for (long node : nodes) {
if (possibleIntersectionNodes.contains(node)) {
intersectionNodes.add(node);
} else {
possibleIntersectionNodes.add(node);
}
}
}
GeometryFactory geometryFactory = new GeometryFactory();
/* build an ordinary graph, which we will convert to an edge-based graph */
ArrayList<Vertex> endpoints = new ArrayList<Vertex>();
for (OSMWay way : _ways.values()) {
if (wayIndex % 1000 == 0)
_log.debug("ways=" + wayIndex + "/" + _ways.size());
wayIndex++;
WayProperties wayData = wayPropertySet.getDataForWay(way);
String creativeName = wayPropertySet.getCreativeNameForWay(way);
if (creativeName != null) {
way.addTag("otp:gen_name", creativeName);
}
Set<String> note = wayPropertySet.getNoteForWay(way);
StreetTraversalPermission permissions = getPermissionsForEntity(way, wayData.getPermission());
if (permissions == StreetTraversalPermission.NONE)
continue;
List<Long> nodes = way.getNodeRefs();
Vertex startEndpoint = null, endEndpoint = null;
ArrayList<Coordinate> segmentCoordinates = new ArrayList<Coordinate>();
/*
* Traverse through all the nodes of this edge. For nodes which are not shared with
* any other edge, do not create endpoints -- just accumulate them for geometry. For
* nodes which are shared, create endpoints and StreetVertex instances.
*/
Long startNode = null;
OSMNode osmStartNode = null;
for (int i = 0; i < nodes.size() - 1; i++) {
Long endNode = nodes.get(i + 1);
if (osmStartNode == null) {
startNode = nodes.get(i);
osmStartNode = _nodes.get(startNode);
}
OSMNode osmEndNode = _nodes.get(endNode);
if (osmStartNode == null || osmEndNode == null)
continue;
LineString geometry;
/*
* skip vertices that are not intersections, except that we use them for
* geometry
*/
if (segmentCoordinates.size() == 0) {
segmentCoordinates.add(getCoordinate(osmStartNode));
}
if (intersectionNodes.contains(endNode) || i == nodes.size() - 2) {
segmentCoordinates.add(getCoordinate(osmEndNode));
geometry = geometryFactory.createLineString(segmentCoordinates
.toArray(new Coordinate[0]));
segmentCoordinates.clear();
} else {
segmentCoordinates.add(getCoordinate(osmEndNode));
continue;
}
/* generate endpoints */
if (startEndpoint == null) {
//first iteration on this way
String label = "osm node " + osmStartNode.getId();
startEndpoint = graph.getVertex(label);
if (startEndpoint == null) {
Coordinate coordinate = getCoordinate(osmStartNode);
startEndpoint = new EndpointVertex(label, coordinate.x, coordinate.y,
label);
graph.addVertex(startEndpoint);
endpoints.add(startEndpoint);
}
} else {
startEndpoint = endEndpoint;
}
String label = "osm node " + osmEndNode.getId();
endEndpoint = graph.getVertex(label);
if (endEndpoint == null) {
Coordinate coordinate = getCoordinate(osmEndNode);
endEndpoint = new EndpointVertex(label, coordinate.x, coordinate.y, label);
graph.addVertex(endEndpoint);
endpoints.add(endEndpoint);
}
P2<PlainStreetEdge> streets = getEdgesForStreet(startEndpoint, endEndpoint,
way, i, permissions, geometry);
PlainStreetEdge street = streets.getFirst();
if (street != null) {
graph.addEdge(street);
Double safety = wayData.getSafetyFeatures().getFirst();
street.setBicycleSafetyEffectiveLength(street.getLength() * safety * getBikeSafetyFactor());
if (note != null) {
street.setNote(note);
}
}
PlainStreetEdge backStreet = streets.getSecond();
if (backStreet != null) {
graph.addEdge(backStreet);
Double safety = wayData.getSafetyFeatures().getSecond();
backStreet.setBicycleSafetyEffectiveLength(backStreet.getLength() * safety * getBikeSafetyFactor());
if (note != null) {
backStreet.setNote(note);
}
}
/* Check if there are turn restrictions starting on this segment */
List<TurnRestrictionTag> restrictionTags = turnRestrictionsByFromWay.get(way.getId());
if (restrictionTags != null) {
for (TurnRestrictionTag tag : restrictionTags) {
if (tag.via == startNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.from = backStreet;
} else if (tag.via == endNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.from = street;
}
}
}
restrictionTags = turnRestrictionsByToWay.get(way.getId());
if (restrictionTags != null) {
for (TurnRestrictionTag tag : restrictionTags) {
if (tag.via == startNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.to = street;
} else if (tag.via == endNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.to = backStreet;
}
}
}
startNode = endNode;
osmStartNode = _nodes.get(startNode);
}
}
/* unify turn restrictions */
Map<Edge, TurnRestriction> turnRestrictions = new HashMap<Edge, TurnRestriction>();
for (TurnRestriction restriction : turnRestrictionsByTag.values()) {
turnRestrictions.put(restriction.from, restriction);
}
StreetUtils.pruneFloatingIslands(graph);
StreetUtils.makeEdgeBased(graph, endpoints, turnRestrictions);
}
|
diff --git a/fabric/fabric-core/src/main/scala/org/fusesource/fabric/service/ChildContainerProvider.java b/fabric/fabric-core/src/main/scala/org/fusesource/fabric/service/ChildContainerProvider.java
index 4d94d1eda..5a25b0671 100644
--- a/fabric/fabric-core/src/main/scala/org/fusesource/fabric/service/ChildContainerProvider.java
+++ b/fabric/fabric-core/src/main/scala/org/fusesource/fabric/service/ChildContainerProvider.java
@@ -1,140 +1,141 @@
/**
* Copyright (C) FuseSource, Inc.
* http://fusesource.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fusesource.fabric.service;
import java.util.LinkedHashSet;
import java.util.Set;
import org.apache.karaf.admin.management.AdminServiceMBean;
import org.fusesource.fabric.api.Container;
import org.fusesource.fabric.api.ContainerProvider;
import org.fusesource.fabric.api.CreateContainerChildMetadata;
import org.fusesource.fabric.api.CreateContainerChildOptions;
import org.fusesource.fabric.internal.FabricConstants;
public class ChildContainerProvider implements ContainerProvider<CreateContainerChildOptions, CreateContainerChildMetadata> {
final FabricServiceImpl service;
public ChildContainerProvider(FabricServiceImpl service) {
this.service = service;
}
@Override
public Set<CreateContainerChildMetadata> create(final CreateContainerChildOptions options) throws Exception {
final Set<CreateContainerChildMetadata> result = new LinkedHashSet<CreateContainerChildMetadata>();
String parentName = options.getParent();
final Container parent = service.getContainer(parentName);
ContainerTemplate containerTemplate = service.getContainerTemplate(parent);
//Retrieve the credentials from the URI if available.
if (options.getProviderURI() != null && options.getProviderURI().getUserInfo() != null) {
String ui = options.getProviderURI().getUserInfo();
String[] uip = ui != null ? ui.split(":") : null;
if (uip != null) {
containerTemplate.setLogin(uip[0]);
containerTemplate.setPassword(uip[1]);
}
}
containerTemplate.execute(new ContainerTemplate.AdminServiceCallback<Object>() {
public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
StringBuilder jvmOptsBuilder = new StringBuilder();
jvmOptsBuilder.append("-server -Dcom.sun.management.jmxremote ")
- .append(options.getJvmOpts()).append(" ")
.append(options.getZookeeperUrl() != null ? "-Dzookeeper.url=\"" + options.getZookeeperUrl() + "\"" : "");
if (options.getJvmOpts() == null || !options.getJvmOpts().contains("-Xmx")) {
- jvmOptsBuilder.append("-Xmx512m");
+ jvmOptsBuilder.append(" -Xmx512m");
+ } else if (options.getJvmOpts() != null) {
+ jvmOptsBuilder.append(" ").append(options.getJvmOpts());
}
if (options.isDebugContainer()) {
jvmOptsBuilder.append(" ").append(DEBUG_CONTAINER);
}
if (options.isEnsembleServer()) {
jvmOptsBuilder.append(" ").append(ENSEMBLE_SERVER_CONTAINER);
}
String features = "fabric-agent";
String featuresUrls = "mvn:org.fusesource.fabric/fuse-fabric/" + FabricConstants.FABRIC_VERSION + "/xml/features";
for (int i = 1; i <= options.getNumber(); i++) {
String containerName = options.getName();
if (options.getNumber() > 1) {
containerName += i;
}
CreateContainerChildMetadata metadata = new CreateContainerChildMetadata();
metadata.setCreateOptions(options);
metadata.setContainerName(containerName);
try {
adminService.createInstance(containerName, 0, 0, 0, null, jvmOptsBuilder.toString(), features, featuresUrls);
adminService.startInstance(containerName, null);
} catch (Throwable t) {
metadata.setFailure(t);
}
result.add(metadata);
}
return null;
}
});
return result;
}
@Override
public void start(final Container container) {
getContainerTemplate(container.getParent()).execute(new ContainerTemplate.AdminServiceCallback<Object>() {
public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
adminService.startInstance(container.getId(), null);
return null;
}
});
}
@Override
public void stop(final Container container) {
getContainerTemplate(container.getParent()).execute(new ContainerTemplate.AdminServiceCallback<Object>() {
public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
adminService.stopInstance(container.getId());
return null;
}
});
}
@Override
public void destroy(final Container container) {
getContainerTemplate(container.getParent()).execute(new ContainerTemplate.AdminServiceCallback<Object>() {
public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
try {
if (container.isAlive()) {
adminService.stopInstance(container.getId());
}
} catch (Exception e) {
// Ignore if the container is stopped
if (container.isAlive()) {
throw e;
}
}
adminService.destroyInstance(container.getId());
return null;
}
});
}
protected ContainerTemplate getContainerTemplate(Container container) {
return new ContainerTemplate(container, false, service.getUserName(), service.getPassword());
}
}
| false | true | public Set<CreateContainerChildMetadata> create(final CreateContainerChildOptions options) throws Exception {
final Set<CreateContainerChildMetadata> result = new LinkedHashSet<CreateContainerChildMetadata>();
String parentName = options.getParent();
final Container parent = service.getContainer(parentName);
ContainerTemplate containerTemplate = service.getContainerTemplate(parent);
//Retrieve the credentials from the URI if available.
if (options.getProviderURI() != null && options.getProviderURI().getUserInfo() != null) {
String ui = options.getProviderURI().getUserInfo();
String[] uip = ui != null ? ui.split(":") : null;
if (uip != null) {
containerTemplate.setLogin(uip[0]);
containerTemplate.setPassword(uip[1]);
}
}
containerTemplate.execute(new ContainerTemplate.AdminServiceCallback<Object>() {
public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
StringBuilder jvmOptsBuilder = new StringBuilder();
jvmOptsBuilder.append("-server -Dcom.sun.management.jmxremote ")
.append(options.getJvmOpts()).append(" ")
.append(options.getZookeeperUrl() != null ? "-Dzookeeper.url=\"" + options.getZookeeperUrl() + "\"" : "");
if (options.getJvmOpts() == null || !options.getJvmOpts().contains("-Xmx")) {
jvmOptsBuilder.append("-Xmx512m");
}
if (options.isDebugContainer()) {
jvmOptsBuilder.append(" ").append(DEBUG_CONTAINER);
}
if (options.isEnsembleServer()) {
jvmOptsBuilder.append(" ").append(ENSEMBLE_SERVER_CONTAINER);
}
String features = "fabric-agent";
String featuresUrls = "mvn:org.fusesource.fabric/fuse-fabric/" + FabricConstants.FABRIC_VERSION + "/xml/features";
for (int i = 1; i <= options.getNumber(); i++) {
String containerName = options.getName();
if (options.getNumber() > 1) {
containerName += i;
}
CreateContainerChildMetadata metadata = new CreateContainerChildMetadata();
metadata.setCreateOptions(options);
metadata.setContainerName(containerName);
try {
adminService.createInstance(containerName, 0, 0, 0, null, jvmOptsBuilder.toString(), features, featuresUrls);
adminService.startInstance(containerName, null);
} catch (Throwable t) {
metadata.setFailure(t);
}
result.add(metadata);
}
return null;
}
});
return result;
}
| public Set<CreateContainerChildMetadata> create(final CreateContainerChildOptions options) throws Exception {
final Set<CreateContainerChildMetadata> result = new LinkedHashSet<CreateContainerChildMetadata>();
String parentName = options.getParent();
final Container parent = service.getContainer(parentName);
ContainerTemplate containerTemplate = service.getContainerTemplate(parent);
//Retrieve the credentials from the URI if available.
if (options.getProviderURI() != null && options.getProviderURI().getUserInfo() != null) {
String ui = options.getProviderURI().getUserInfo();
String[] uip = ui != null ? ui.split(":") : null;
if (uip != null) {
containerTemplate.setLogin(uip[0]);
containerTemplate.setPassword(uip[1]);
}
}
containerTemplate.execute(new ContainerTemplate.AdminServiceCallback<Object>() {
public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
StringBuilder jvmOptsBuilder = new StringBuilder();
jvmOptsBuilder.append("-server -Dcom.sun.management.jmxremote ")
.append(options.getZookeeperUrl() != null ? "-Dzookeeper.url=\"" + options.getZookeeperUrl() + "\"" : "");
if (options.getJvmOpts() == null || !options.getJvmOpts().contains("-Xmx")) {
jvmOptsBuilder.append(" -Xmx512m");
} else if (options.getJvmOpts() != null) {
jvmOptsBuilder.append(" ").append(options.getJvmOpts());
}
if (options.isDebugContainer()) {
jvmOptsBuilder.append(" ").append(DEBUG_CONTAINER);
}
if (options.isEnsembleServer()) {
jvmOptsBuilder.append(" ").append(ENSEMBLE_SERVER_CONTAINER);
}
String features = "fabric-agent";
String featuresUrls = "mvn:org.fusesource.fabric/fuse-fabric/" + FabricConstants.FABRIC_VERSION + "/xml/features";
for (int i = 1; i <= options.getNumber(); i++) {
String containerName = options.getName();
if (options.getNumber() > 1) {
containerName += i;
}
CreateContainerChildMetadata metadata = new CreateContainerChildMetadata();
metadata.setCreateOptions(options);
metadata.setContainerName(containerName);
try {
adminService.createInstance(containerName, 0, 0, 0, null, jvmOptsBuilder.toString(), features, featuresUrls);
adminService.startInstance(containerName, null);
} catch (Throwable t) {
metadata.setFailure(t);
}
result.add(metadata);
}
return null;
}
});
return result;
}
|
diff --git a/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java b/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java
index c94001a..ab21b5c 100644
--- a/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java
+++ b/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java
@@ -1,183 +1,186 @@
/*
* Created on Jul 27, 2005
*/
package uk.org.ponder.rsf.renderer.html;
import java.util.HashMap;
import java.util.Map;
import uk.org.ponder.rsf.components.UIBasicListMember;
import uk.org.ponder.rsf.components.UIComponent;
import uk.org.ponder.rsf.renderer.ComponentRenderer;
import uk.org.ponder.rsf.renderer.RenderSystem;
import uk.org.ponder.rsf.renderer.RenderSystemContext;
import uk.org.ponder.rsf.renderer.RenderUtil;
import uk.org.ponder.rsf.renderer.TagRenderContext;
import uk.org.ponder.rsf.renderer.decorator.DecoratorManager;
import uk.org.ponder.rsf.renderer.scr.NullRewriteSCR;
import uk.org.ponder.rsf.renderer.scr.StaticComponentRenderer;
import uk.org.ponder.rsf.renderer.scr.StaticRendererCollection;
import uk.org.ponder.rsf.request.FossilizedConverter;
import uk.org.ponder.rsf.request.SubmittedValueEntry;
import uk.org.ponder.rsf.template.XMLLump;
import uk.org.ponder.rsf.template.XMLLumpList;
import uk.org.ponder.util.Constants;
import uk.org.ponder.util.Logger;
import uk.org.ponder.util.UniversalRuntimeException;
/**
* The implementation of the standard XHTML rendering System. This class is due
* for basic refactoring since it contains logic that belongs in a) a "base
* System-independent" lookup bean, and b) in a number of individual
* ComponentRenderer objects.
*
* @author Antranig Basman ([email protected])
*
*/
public class BasicHTMLRenderSystem implements RenderSystem {
private StaticRendererCollection scrc;
private DecoratorManager decoratormanager;
private ComponentRenderer componentRenderer;
public void setComponentRenderer(ComponentRenderer componentRenderer) {
this.componentRenderer = componentRenderer;
}
public void setStaticRenderers(StaticRendererCollection scrc) {
this.scrc = scrc;
}
public void setDecoratorManager(DecoratorManager decoratormanager) {
this.decoratormanager = decoratormanager;
}
// two methods for the RenderSystemDecoder interface
public void normalizeRequestMap(Map requestparams) {
String key = RenderUtil.findCommandParams(requestparams);
if (key != null) {
String params = key.substring(FossilizedConverter.COMMAND_LINK_PARAMETERS
.length());
RenderUtil.unpackCommandLink(params, requestparams);
requestparams.remove(key);
}
}
public void fixupUIType(SubmittedValueEntry sve) {
if (sve.oldvalue instanceof Boolean) {
if (sve.newvalue == null)
sve.newvalue = Boolean.FALSE;
}
else if (sve.oldvalue instanceof String[]) {
if (sve.newvalue == null)
sve.newvalue = new String[] {};
}
else if (sve.oldvalue instanceof String) {
if (sve.newvalue instanceof String
&& Constants.NULL_STRING.equals(sve.newvalue)
|| sve.newvalue instanceof String[]
&& Constants.NULL_STRING.equals(((String[]) sve.newvalue)[0])) {
sve.newvalue = null;
}
}
}
public void renderDebugMessage(RenderSystemContext rsc, String string) {
rsc.pos.print("<span style=\"background-color:#FF466B;color:white;padding:1px;\">");
rsc.xmlw.write(string);
rsc.pos.print("</span><br/>");
}
// This method is almost entirely dialect-invariant - awaiting final
// factorisation of RenderSystem
public int renderComponent(RenderSystemContext rsc, UIComponent torendero, XMLLump lump) {
int lumpindex = lump.lumpindex;
XMLLump[] lumps = lump.parent.lumps;
int nextpos = -1;
XMLLump outerendopen = lump.open_end;
XMLLump outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
XMLLumpList payloadlist = lump.downmap == null ? null
: lump.downmap.headsForID(XMLLump.PAYLOAD_COMPONENT);
XMLLump payload = payloadlist == null ? null
: payloadlist.lumpAt(0);
// if there is no peer component, it might still be a static resource holder
// that needs URLs rewriting.
// we assume there is no payload component here, since there is no producer
// ID that might govern selection. So we use "outer" indices.
if (torendero == null) {
if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) {
String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length());
StaticComponentRenderer scr = scrc.getSCR(scrname);
if (scr == null) {
Logger.log
.info("Warning: unrecognised static component renderer reference with key "
+ scrname + " at lump " + lump.toString());
scr = NullRewriteSCR.instance;
}
int tagtype = RenderUtil.renderSCR(scr, lump, rsc.xmlw, rsc.collecteds);
nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1
: outerendopen.lumpindex + 1;
}
else {
if (rsc.debugrender) {
renderDebugMessage(rsc, "Leaf component missing which was expected with template id " +
lump.rsfID + " at " + lump.toString());
}
}
}
else {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
XMLLump endopen = outerendopen;
XMLLump close = outerclose;
XMLLump uselump = lump;
if (payload != null) {
endopen = payload.open_end;
close = payload.close_tag;
uselump = payload;
RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, rsc.pos);
lumpindex = payload.lumpindex;
}
HashMap attrcopy = new HashMap();
attrcopy.putAll(uselump.attributemap);
rsc.IDassigner.adjustForID(attrcopy, torendero);
decoratormanager.decorate(torendero.decorators, uselump.getTag(),
attrcopy);
TagRenderContext rendercontext = new TagRenderContext(attrcopy, uselump,
endopen, close, rsc.pos, rsc.xmlw, nextpos);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
rsc.pos.write(uselump.parent.buffer, uselump.start, uselump.length);
if (torendero instanceof UIBasicListMember) {
torendero = RenderUtil.resolveListMember(rsc.view,
(UIBasicListMember) torendero);
}
try {
componentRenderer.renderComponent(torendero, rsc.view, rendercontext);
}
catch (Exception e) {
throw UniversalRuntimeException.accumulate(e,
"Error rendering component " + torendero.getClass()
+ " with full ID " + torendero.getFullID()
+ " at template location " + rendercontext.uselump);
}
// if there is a payload, dump the postamble.
if (payload != null) {
- RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
+ // the default case is initialised to tag close
+ if (rendercontext.nextpos == nextpos) {
+ RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
outerclose.lumpindex + 1, rsc.pos);
+ }
}
nextpos = rendercontext.nextpos;
}
return nextpos;
}
}
| false | true | public int renderComponent(RenderSystemContext rsc, UIComponent torendero, XMLLump lump) {
int lumpindex = lump.lumpindex;
XMLLump[] lumps = lump.parent.lumps;
int nextpos = -1;
XMLLump outerendopen = lump.open_end;
XMLLump outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
XMLLumpList payloadlist = lump.downmap == null ? null
: lump.downmap.headsForID(XMLLump.PAYLOAD_COMPONENT);
XMLLump payload = payloadlist == null ? null
: payloadlist.lumpAt(0);
// if there is no peer component, it might still be a static resource holder
// that needs URLs rewriting.
// we assume there is no payload component here, since there is no producer
// ID that might govern selection. So we use "outer" indices.
if (torendero == null) {
if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) {
String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length());
StaticComponentRenderer scr = scrc.getSCR(scrname);
if (scr == null) {
Logger.log
.info("Warning: unrecognised static component renderer reference with key "
+ scrname + " at lump " + lump.toString());
scr = NullRewriteSCR.instance;
}
int tagtype = RenderUtil.renderSCR(scr, lump, rsc.xmlw, rsc.collecteds);
nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1
: outerendopen.lumpindex + 1;
}
else {
if (rsc.debugrender) {
renderDebugMessage(rsc, "Leaf component missing which was expected with template id " +
lump.rsfID + " at " + lump.toString());
}
}
}
else {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
XMLLump endopen = outerendopen;
XMLLump close = outerclose;
XMLLump uselump = lump;
if (payload != null) {
endopen = payload.open_end;
close = payload.close_tag;
uselump = payload;
RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, rsc.pos);
lumpindex = payload.lumpindex;
}
HashMap attrcopy = new HashMap();
attrcopy.putAll(uselump.attributemap);
rsc.IDassigner.adjustForID(attrcopy, torendero);
decoratormanager.decorate(torendero.decorators, uselump.getTag(),
attrcopy);
TagRenderContext rendercontext = new TagRenderContext(attrcopy, uselump,
endopen, close, rsc.pos, rsc.xmlw, nextpos);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
rsc.pos.write(uselump.parent.buffer, uselump.start, uselump.length);
if (torendero instanceof UIBasicListMember) {
torendero = RenderUtil.resolveListMember(rsc.view,
(UIBasicListMember) torendero);
}
try {
componentRenderer.renderComponent(torendero, rsc.view, rendercontext);
}
catch (Exception e) {
throw UniversalRuntimeException.accumulate(e,
"Error rendering component " + torendero.getClass()
+ " with full ID " + torendero.getFullID()
+ " at template location " + rendercontext.uselump);
}
// if there is a payload, dump the postamble.
if (payload != null) {
RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
outerclose.lumpindex + 1, rsc.pos);
}
nextpos = rendercontext.nextpos;
}
return nextpos;
}
| public int renderComponent(RenderSystemContext rsc, UIComponent torendero, XMLLump lump) {
int lumpindex = lump.lumpindex;
XMLLump[] lumps = lump.parent.lumps;
int nextpos = -1;
XMLLump outerendopen = lump.open_end;
XMLLump outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
XMLLumpList payloadlist = lump.downmap == null ? null
: lump.downmap.headsForID(XMLLump.PAYLOAD_COMPONENT);
XMLLump payload = payloadlist == null ? null
: payloadlist.lumpAt(0);
// if there is no peer component, it might still be a static resource holder
// that needs URLs rewriting.
// we assume there is no payload component here, since there is no producer
// ID that might govern selection. So we use "outer" indices.
if (torendero == null) {
if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) {
String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length());
StaticComponentRenderer scr = scrc.getSCR(scrname);
if (scr == null) {
Logger.log
.info("Warning: unrecognised static component renderer reference with key "
+ scrname + " at lump " + lump.toString());
scr = NullRewriteSCR.instance;
}
int tagtype = RenderUtil.renderSCR(scr, lump, rsc.xmlw, rsc.collecteds);
nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1
: outerendopen.lumpindex + 1;
}
else {
if (rsc.debugrender) {
renderDebugMessage(rsc, "Leaf component missing which was expected with template id " +
lump.rsfID + " at " + lump.toString());
}
}
}
else {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
XMLLump endopen = outerendopen;
XMLLump close = outerclose;
XMLLump uselump = lump;
if (payload != null) {
endopen = payload.open_end;
close = payload.close_tag;
uselump = payload;
RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, rsc.pos);
lumpindex = payload.lumpindex;
}
HashMap attrcopy = new HashMap();
attrcopy.putAll(uselump.attributemap);
rsc.IDassigner.adjustForID(attrcopy, torendero);
decoratormanager.decorate(torendero.decorators, uselump.getTag(),
attrcopy);
TagRenderContext rendercontext = new TagRenderContext(attrcopy, uselump,
endopen, close, rsc.pos, rsc.xmlw, nextpos);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
rsc.pos.write(uselump.parent.buffer, uselump.start, uselump.length);
if (torendero instanceof UIBasicListMember) {
torendero = RenderUtil.resolveListMember(rsc.view,
(UIBasicListMember) torendero);
}
try {
componentRenderer.renderComponent(torendero, rsc.view, rendercontext);
}
catch (Exception e) {
throw UniversalRuntimeException.accumulate(e,
"Error rendering component " + torendero.getClass()
+ " with full ID " + torendero.getFullID()
+ " at template location " + rendercontext.uselump);
}
// if there is a payload, dump the postamble.
if (payload != null) {
// the default case is initialised to tag close
if (rendercontext.nextpos == nextpos) {
RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
outerclose.lumpindex + 1, rsc.pos);
}
}
nextpos = rendercontext.nextpos;
}
return nextpos;
}
|
diff --git a/src/com/nloko/android/syncmypix/SyncMyPixProvider.java b/src/com/nloko/android/syncmypix/SyncMyPixProvider.java
index 0a9d425..4ad37c4 100644
--- a/src/com/nloko/android/syncmypix/SyncMyPixProvider.java
+++ b/src/com/nloko/android/syncmypix/SyncMyPixProvider.java
@@ -1,461 +1,465 @@
//
// SyncMyPixProvider.java is part of SyncMyPix
//
// Authors:
// Neil Loknath <[email protected]>
//
// Copyright (c) 2009 Neil Loknath
//
// SyncMyPix is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SyncMyPix is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SyncMyPix. If not, see <http://www.gnu.org/licenses/>.
//
package com.nloko.android.syncmypix;
import java.util.HashMap;
import com.nloko.android.Log;
import com.nloko.android.syncmypix.SyncMyPix.Contacts;
import com.nloko.android.syncmypix.SyncMyPix.Results;
import com.nloko.android.syncmypix.SyncMyPix.Sync;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
// TODO this probably should not have even been a ContentProvider. Change?
public class SyncMyPixProvider extends ContentProvider {
private static final String TAG = "SyncMyPixProvider";
private static final String DATABASE_NAME = "syncpix.db";
private static final int DATABASE_VERSION = 7;
private static final String CONTACTS_TABLE_NAME = "contacts";
private static final String RESULTS_TABLE_NAME = "results";
private static final String SYNC_TABLE_NAME = "sync";
private static HashMap<String, String> contactsProjection;
private static HashMap<String, String> resultsProjection;
private static HashMap<String, String> syncProjection;
private static final int CONTACTS = 1;
private static final int CONTACTS_ID = 2;
private static final int RESULTS = 3;
private static final int RESULTS_ID = 4;
private static final int SYNC = 5;
private static final int SYNC_ID = 6;
private static final UriMatcher uriMatcher;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(SyncMyPix.AUTHORITY, "contacts", CONTACTS);
uriMatcher.addURI(SyncMyPix.AUTHORITY, "contacts/#", CONTACTS_ID);
uriMatcher.addURI(SyncMyPix.AUTHORITY, "results", RESULTS);
uriMatcher.addURI(SyncMyPix.AUTHORITY, "results/#", RESULTS_ID);
uriMatcher.addURI(SyncMyPix.AUTHORITY, "sync", SYNC);
uriMatcher.addURI(SyncMyPix.AUTHORITY, "sync/#", SYNC_ID);
// Map columns to resolve ambiguity
contactsProjection = new HashMap<String, String>();
contactsProjection.put(Contacts._ID, Contacts._ID);
contactsProjection.put(Contacts.LOOKUP_KEY, Contacts.LOOKUP_KEY);
contactsProjection.put(Contacts.PIC_URL, Contacts.PIC_URL);
contactsProjection.put(Contacts.PHOTO_HASH, Contacts.PHOTO_HASH);
contactsProjection.put(Contacts.NETWORK_PHOTO_HASH, Contacts.NETWORK_PHOTO_HASH);
contactsProjection.put(Contacts.FRIEND_ID, Contacts.FRIEND_ID);
contactsProjection.put(Contacts.SOURCE, Contacts.SOURCE);
syncProjection = new HashMap<String, String>();
syncProjection.put(Sync._ID, SYNC_TABLE_NAME + "." + Sync._ID);
syncProjection.put(Sync.SOURCE, Sync.SOURCE);
syncProjection.put(Sync.DATE_STARTED, Sync.DATE_STARTED);
syncProjection.put(Sync.DATE_COMPLETED, Sync.DATE_COMPLETED);
syncProjection.put(Sync.UPDATED, Sync.UPDATED);
syncProjection.put(Sync.SKIPPED, Sync.SKIPPED);
syncProjection.put(Sync.NOT_FOUND, Sync.NOT_FOUND);
resultsProjection = new HashMap<String, String>();
resultsProjection.put(Sync._ID, SYNC_TABLE_NAME + "." + Sync._ID);
resultsProjection.put(Sync.SOURCE, Sync.SOURCE);
resultsProjection.put(Sync.DATE_STARTED, Sync.DATE_STARTED);
resultsProjection.put(Sync.DATE_COMPLETED, Sync.DATE_COMPLETED);
resultsProjection.put(Sync.UPDATED, Sync.UPDATED);
resultsProjection.put(Sync.SKIPPED, Sync.SKIPPED);
resultsProjection.put(Sync.NOT_FOUND, Sync.NOT_FOUND);
resultsProjection.put(Results._ID, RESULTS_TABLE_NAME + "." + Results._ID);
resultsProjection.put(Results.SYNC_ID, Results.SYNC_ID);
resultsProjection.put(Results.NAME, Results.NAME);
resultsProjection.put(Results.PIC_URL, Results.PIC_URL);
resultsProjection.put(Results.DESCRIPTION, Results.DESCRIPTION);
resultsProjection.put(Results.CONTACT_ID, Results.CONTACT_ID);
resultsProjection.put(Results.LOOKUP_KEY, Results.LOOKUP_KEY);
resultsProjection.put(Results.FRIEND_ID, Results.FRIEND_ID);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + CONTACTS_TABLE_NAME + " ("
+ Contacts._ID + " INTEGER PRIMARY KEY,"
+ Contacts.LOOKUP_KEY + " TEXT DEFAULT NULL,"
+ Contacts.PIC_URL + " TEXT DEFAULT NULL,"
+ Contacts.PHOTO_HASH + " TEXT,"
+ Contacts.NETWORK_PHOTO_HASH + " TEXT,"
+ Contacts.FRIEND_ID + " TEXT DEFAULT NULL,"
+ Contacts.SOURCE + " TEXT"
+ ");");
db.execSQL("CREATE TABLE " + RESULTS_TABLE_NAME + " ("
+ Results._ID + " INTEGER PRIMARY KEY,"
+ Results.SYNC_ID + " INTEGER,"
+ Results.NAME + " TEXT DEFAULT NULL,"
+ Results.DESCRIPTION + " TEXT DEFAULT NULL,"
+ Results.PIC_URL + " TEXT DEFAULT NULL,"
+ Results.CONTACT_ID + " INTEGER,"
+ Results.LOOKUP_KEY + " TEXT DEFAULT NULL,"
+ Results.FRIEND_ID + " TEXT DEFAULT NULL"
+ ");");
db.execSQL("CREATE TABLE " + SYNC_TABLE_NAME + " ("
+ Sync._ID + " INTEGER PRIMARY KEY,"
+ Sync.SOURCE + " TEXT DEFAULT NULL,"
+ Sync.DATE_STARTED + " INTEGER,"
+ Sync.DATE_COMPLETED + " INTEGER,"
+ Sync.UPDATED + " INTEGER,"
+ Sync.SKIPPED + " INTEGER,"
+ Sync.NOT_FOUND + " INTEGER"
+ ");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
if (oldVersion >= 2) {
db.execSQL("CREATE TABLE results_new ("
+ Results._ID + " INTEGER PRIMARY KEY,"
+ Results.SYNC_ID + " INTEGER,"
+ Results.NAME + " TEXT DEFAULT NULL,"
+ Results.DESCRIPTION + " TEXT DEFAULT NULL,"
+ Results.PIC_URL + " TEXT DEFAULT NULL,"
+ Results.CONTACT_ID + " INTEGER,"
+ Results.LOOKUP_KEY + " TEXT DEFAULT NULL,"
+ Results.FRIEND_ID + " TEXT DEFAULT NULL"
+ ");");
db.execSQL("CREATE TABLE sync_new ("
+ Sync._ID + " INTEGER PRIMARY KEY,"
+ Sync.SOURCE + " TEXT DEFAULT NULL,"
+ Sync.DATE_STARTED + " INTEGER,"
+ Sync.DATE_COMPLETED + " INTEGER,"
+ Sync.UPDATED + " INTEGER,"
+ Sync.SKIPPED + " INTEGER,"
+ Sync.NOT_FOUND + " INTEGER"
+ ");");
db.execSQL("DROP TABLE IF EXISTS sync;");
db.execSQL("ALTER TABLE sync_new RENAME TO " + SYNC_TABLE_NAME +";");
db.execSQL("DROP TABLE IF EXISTS results;");
db.execSQL("ALTER TABLE results_new RENAME TO " + RESULTS_TABLE_NAME +";");
}
db.execSQL("CREATE TABLE contacts_new ("
+ Contacts._ID + " INTEGER PRIMARY KEY,"
+ Contacts.LOOKUP_KEY + " TEXT DEFAULT NULL,"
+ Contacts.PIC_URL + " TEXT DEFAULT NULL,"
+ Contacts.PHOTO_HASH + " TEXT,"
+ Contacts.NETWORK_PHOTO_HASH + " TEXT,"
+ Contacts.FRIEND_ID + " TEXT DEFAULT NULL,"
+ Contacts.SOURCE + " TEXT"
+ ");");
if (oldVersion < 4) {
db.execSQL("INSERT INTO contacts_new ("
+ Contacts._ID + ","
+ Contacts.PHOTO_HASH + ")"
+ "SELECT "
+ Contacts._ID + ","
+ Contacts.PHOTO_HASH
+ " FROM " + CONTACTS_TABLE_NAME + ";");
} else {
db.execSQL("INSERT INTO contacts_new ("
+ Contacts._ID + ","
+ Contacts.NETWORK_PHOTO_HASH + ","
+ + Contacts.FRIEND_ID + ","
+ + Contacts.SOURCE + ","
+ Contacts.PHOTO_HASH + ")"
+ "SELECT "
+ Contacts._ID + ","
+ Contacts.NETWORK_PHOTO_HASH + ","
+ + Contacts.FRIEND_ID + ","
+ + Contacts.SOURCE + ","
+ Contacts.PHOTO_HASH
+ " FROM " + CONTACTS_TABLE_NAME + ";");
}
db.execSQL("DROP TABLE IF EXISTS contacts;");
db.execSQL("ALTER TABLE contacts_new RENAME TO " + CONTACTS_TABLE_NAME +";");
}
}
private DatabaseHelper openHelper;
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = openHelper.getWritableDatabase();
int count;
String Id;
switch (uriMatcher.match(uri)) {
case CONTACTS:
count = db.delete(CONTACTS_TABLE_NAME, selection, selectionArgs);
break;
case CONTACTS_ID:
Id = uri.getPathSegments().get(1);
count = db.delete(CONTACTS_TABLE_NAME, Contacts._ID + "=" + Id
+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
break;
case RESULTS:
case SYNC:
// just wipe out everything
count = db.delete(SYNC_TABLE_NAME, null, null);
count = db.delete(RESULTS_TABLE_NAME, null, null);
break;
case SYNC_ID:
Id = uri.getPathSegments().get(1);
count = db.delete(SYNC_TABLE_NAME, Sync._ID + "=" + Id, null);
count = db.delete(RESULTS_TABLE_NAME, Results.SYNC_ID + "=" + Id, null);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case CONTACTS:
return Contacts.CONTENT_TYPE;
case CONTACTS_ID:
return Contacts.CONTENT_ITEM_TYPE;
case RESULTS:
return Results.CONTENT_TYPE;
case SYNC:
return Sync.CONTENT_TYPE;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues initialValues) {
// Validate the requested uri
if (uriMatcher.match(uri) != CONTACTS &&
uriMatcher.match(uri) != RESULTS &&
uriMatcher.match(uri) != SYNC) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues values;
if (initialValues != null) {
values = new ContentValues(initialValues);
} else {
values = new ContentValues();
}
String nullCol = null;
String table = null;
Uri baseUri = null;
Long now = Long.valueOf(System.currentTimeMillis());
if (uriMatcher.match(uri) == CONTACTS) {
table = CONTACTS_TABLE_NAME;
baseUri = Contacts.CONTENT_URI;
nullCol = Contacts.PHOTO_HASH;
}
if (uriMatcher.match(uri) == RESULTS) {
table = RESULTS_TABLE_NAME;
baseUri = Results.CONTENT_URI;
nullCol = Results.DESCRIPTION;
}
if (uriMatcher.match(uri) == SYNC) {
table = SYNC_TABLE_NAME;
baseUri = Sync.CONTENT_URI;
nullCol = Sync.SOURCE;
if (values.containsKey(Sync.DATE_STARTED) == false) {
values.put(Sync.DATE_STARTED, now);
}
}
SQLiteDatabase db = openHelper.getWritableDatabase();
long rowId = db.insert(table, nullCol, values);
if (rowId > 0) {
Uri rowUri = ContentUris.withAppendedId(baseUri, rowId);
getContext().getContentResolver().notifyChange(rowUri, null);
return rowUri;
}
throw new SQLException("Failed to insert row into " + uri);
}
@Override
public boolean onCreate() {
openHelper = new DatabaseHelper(getContext());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String orderBy;
switch (uriMatcher.match(uri)) {
case CONTACTS:
qb.setTables(CONTACTS_TABLE_NAME);
qb.setProjectionMap(contactsProjection);
orderBy = Contacts.DEFAULT_SORT_ORDER;
break;
case CONTACTS_ID:
qb.setTables(CONTACTS_TABLE_NAME);
qb.setProjectionMap(contactsProjection);
qb.appendWhere(Contacts._ID + "=" + uri.getPathSegments().get(1));
orderBy = Contacts.DEFAULT_SORT_ORDER;
break;
case RESULTS:
qb.setProjectionMap(resultsProjection);
qb.setTables(RESULTS_TABLE_NAME
+ " LEFT OUTER JOIN "
+ SYNC_TABLE_NAME
+ " ON ("
+ RESULTS_TABLE_NAME + "." + Results.SYNC_ID + "=" + SYNC_TABLE_NAME + "." + Sync._ID
+ ")");
orderBy = Results.DEFAULT_SORT_ORDER;
break;
case RESULTS_ID:
qb.setProjectionMap(resultsProjection);
qb.setTables(RESULTS_TABLE_NAME
+ " LEFT OUTER JOIN "
+ SYNC_TABLE_NAME
+ " ON ("
+ RESULTS_TABLE_NAME + "." + Results.SYNC_ID + "=" + SYNC_TABLE_NAME + "." + Sync._ID
+ ")");
qb.appendWhere(RESULTS_TABLE_NAME + "." + Results._ID + "=" + uri.getPathSegments().get(1));
orderBy = Results.DEFAULT_SORT_ORDER;
break;
case SYNC:
qb.setTables(SYNC_TABLE_NAME);
qb.setProjectionMap(syncProjection);
orderBy = Sync.DEFAULT_SORT_ORDER;
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (!TextUtils.isEmpty(sortOrder)) {
orderBy = sortOrder;
}
SQLiteDatabase db = openHelper.getWritableDatabase();
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
// Tell the cursor what uri to watch, so it knows when its source data changes
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
SQLiteDatabase db = openHelper.getWritableDatabase();
String Id;
int count;
switch (uriMatcher.match(uri)) {
case CONTACTS:
count = db.update(CONTACTS_TABLE_NAME, values, selection, selectionArgs);
break;
case CONTACTS_ID:
Id = uri.getPathSegments().get(1);
count = db.update(CONTACTS_TABLE_NAME, values, Contacts._ID + "=" + Id
+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
break;
case RESULTS:
count = db.update(RESULTS_TABLE_NAME, values, selection, selectionArgs);
break;
case RESULTS_ID:
Id = uri.getPathSegments().get(1);
count = db.update(RESULTS_TABLE_NAME, values, Results._ID + "=" + Id
+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
break;
case SYNC:
count = db.update(SYNC_TABLE_NAME, values, selection, selectionArgs);
break;
case SYNC_ID:
Id = uri.getPathSegments().get(1);
count = db.update(SYNC_TABLE_NAME, values, Sync._ID + "=" + Id
+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
}
| false | true | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
if (oldVersion >= 2) {
db.execSQL("CREATE TABLE results_new ("
+ Results._ID + " INTEGER PRIMARY KEY,"
+ Results.SYNC_ID + " INTEGER,"
+ Results.NAME + " TEXT DEFAULT NULL,"
+ Results.DESCRIPTION + " TEXT DEFAULT NULL,"
+ Results.PIC_URL + " TEXT DEFAULT NULL,"
+ Results.CONTACT_ID + " INTEGER,"
+ Results.LOOKUP_KEY + " TEXT DEFAULT NULL,"
+ Results.FRIEND_ID + " TEXT DEFAULT NULL"
+ ");");
db.execSQL("CREATE TABLE sync_new ("
+ Sync._ID + " INTEGER PRIMARY KEY,"
+ Sync.SOURCE + " TEXT DEFAULT NULL,"
+ Sync.DATE_STARTED + " INTEGER,"
+ Sync.DATE_COMPLETED + " INTEGER,"
+ Sync.UPDATED + " INTEGER,"
+ Sync.SKIPPED + " INTEGER,"
+ Sync.NOT_FOUND + " INTEGER"
+ ");");
db.execSQL("DROP TABLE IF EXISTS sync;");
db.execSQL("ALTER TABLE sync_new RENAME TO " + SYNC_TABLE_NAME +";");
db.execSQL("DROP TABLE IF EXISTS results;");
db.execSQL("ALTER TABLE results_new RENAME TO " + RESULTS_TABLE_NAME +";");
}
db.execSQL("CREATE TABLE contacts_new ("
+ Contacts._ID + " INTEGER PRIMARY KEY,"
+ Contacts.LOOKUP_KEY + " TEXT DEFAULT NULL,"
+ Contacts.PIC_URL + " TEXT DEFAULT NULL,"
+ Contacts.PHOTO_HASH + " TEXT,"
+ Contacts.NETWORK_PHOTO_HASH + " TEXT,"
+ Contacts.FRIEND_ID + " TEXT DEFAULT NULL,"
+ Contacts.SOURCE + " TEXT"
+ ");");
if (oldVersion < 4) {
db.execSQL("INSERT INTO contacts_new ("
+ Contacts._ID + ","
+ Contacts.PHOTO_HASH + ")"
+ "SELECT "
+ Contacts._ID + ","
+ Contacts.PHOTO_HASH
+ " FROM " + CONTACTS_TABLE_NAME + ";");
} else {
db.execSQL("INSERT INTO contacts_new ("
+ Contacts._ID + ","
+ Contacts.NETWORK_PHOTO_HASH + ","
+ Contacts.PHOTO_HASH + ")"
+ "SELECT "
+ Contacts._ID + ","
+ Contacts.NETWORK_PHOTO_HASH + ","
+ Contacts.PHOTO_HASH
+ " FROM " + CONTACTS_TABLE_NAME + ";");
}
db.execSQL("DROP TABLE IF EXISTS contacts;");
db.execSQL("ALTER TABLE contacts_new RENAME TO " + CONTACTS_TABLE_NAME +";");
}
| public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
if (oldVersion >= 2) {
db.execSQL("CREATE TABLE results_new ("
+ Results._ID + " INTEGER PRIMARY KEY,"
+ Results.SYNC_ID + " INTEGER,"
+ Results.NAME + " TEXT DEFAULT NULL,"
+ Results.DESCRIPTION + " TEXT DEFAULT NULL,"
+ Results.PIC_URL + " TEXT DEFAULT NULL,"
+ Results.CONTACT_ID + " INTEGER,"
+ Results.LOOKUP_KEY + " TEXT DEFAULT NULL,"
+ Results.FRIEND_ID + " TEXT DEFAULT NULL"
+ ");");
db.execSQL("CREATE TABLE sync_new ("
+ Sync._ID + " INTEGER PRIMARY KEY,"
+ Sync.SOURCE + " TEXT DEFAULT NULL,"
+ Sync.DATE_STARTED + " INTEGER,"
+ Sync.DATE_COMPLETED + " INTEGER,"
+ Sync.UPDATED + " INTEGER,"
+ Sync.SKIPPED + " INTEGER,"
+ Sync.NOT_FOUND + " INTEGER"
+ ");");
db.execSQL("DROP TABLE IF EXISTS sync;");
db.execSQL("ALTER TABLE sync_new RENAME TO " + SYNC_TABLE_NAME +";");
db.execSQL("DROP TABLE IF EXISTS results;");
db.execSQL("ALTER TABLE results_new RENAME TO " + RESULTS_TABLE_NAME +";");
}
db.execSQL("CREATE TABLE contacts_new ("
+ Contacts._ID + " INTEGER PRIMARY KEY,"
+ Contacts.LOOKUP_KEY + " TEXT DEFAULT NULL,"
+ Contacts.PIC_URL + " TEXT DEFAULT NULL,"
+ Contacts.PHOTO_HASH + " TEXT,"
+ Contacts.NETWORK_PHOTO_HASH + " TEXT,"
+ Contacts.FRIEND_ID + " TEXT DEFAULT NULL,"
+ Contacts.SOURCE + " TEXT"
+ ");");
if (oldVersion < 4) {
db.execSQL("INSERT INTO contacts_new ("
+ Contacts._ID + ","
+ Contacts.PHOTO_HASH + ")"
+ "SELECT "
+ Contacts._ID + ","
+ Contacts.PHOTO_HASH
+ " FROM " + CONTACTS_TABLE_NAME + ";");
} else {
db.execSQL("INSERT INTO contacts_new ("
+ Contacts._ID + ","
+ Contacts.NETWORK_PHOTO_HASH + ","
+ Contacts.FRIEND_ID + ","
+ Contacts.SOURCE + ","
+ Contacts.PHOTO_HASH + ")"
+ "SELECT "
+ Contacts._ID + ","
+ Contacts.NETWORK_PHOTO_HASH + ","
+ Contacts.FRIEND_ID + ","
+ Contacts.SOURCE + ","
+ Contacts.PHOTO_HASH
+ " FROM " + CONTACTS_TABLE_NAME + ";");
}
db.execSQL("DROP TABLE IF EXISTS contacts;");
db.execSQL("ALTER TABLE contacts_new RENAME TO " + CONTACTS_TABLE_NAME +";");
}
|
diff --git a/src/test/hdfs/org/apache/hadoop/hdfs/TestCrcCorruption.java b/src/test/hdfs/org/apache/hadoop/hdfs/TestCrcCorruption.java
index 9d990df648..30d4ccf473 100644
--- a/src/test/hdfs/org/apache/hadoop/hdfs/TestCrcCorruption.java
+++ b/src/test/hdfs/org/apache/hadoop/hdfs/TestCrcCorruption.java
@@ -1,225 +1,225 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Random;
import junit.framework.TestCase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
/**
* A JUnit test for corrupted file handling.
* This test creates a bunch of files/directories with replication
* factor of 2. Then verifies that a client can automatically
* access the remaining valid replica inspite of the following
* types of simulated errors:
*
* 1. Delete meta file on one replica
* 2. Truncates meta file on one replica
* 3. Corrupts the meta file header on one replica
* 4. Corrupts any random offset and portion of the meta file
* 5. Swaps two meta files, i.e the format of the meta files
* are valid but their CRCs do not match with their corresponding
* data blocks
* The above tests are run for varied values of dfs.bytes-per-checksum
* and dfs.blocksize. It tests for the case when the meta file is
* multiple blocks.
*
* Another portion of the test is commented out till HADOOP-1557
* is addressed:
* 1. Create file with 2 replica, corrupt the meta file of replica,
* decrease replication factor from 2 to 1. Validate that the
* remaining replica is the good one.
* 2. Create file with 2 replica, corrupt the meta file of one replica,
* increase replication factor of file to 3. verify that the new
* replica was created from the non-corrupted replica.
*/
public class TestCrcCorruption extends TestCase {
public TestCrcCorruption(String testName) {
super(testName);
}
protected void setUp() throws Exception {
}
protected void tearDown() throws Exception {
}
/**
* check if DFS can handle corrupted CRC blocks
*/
private void thistest(Configuration conf, DFSTestUtil util) throws Exception {
MiniDFSCluster cluster = null;
int numDataNodes = 2;
short replFactor = 2;
Random random = new Random();
try {
cluster = new MiniDFSCluster(conf, numDataNodes, true, null);
cluster.waitActive();
FileSystem fs = cluster.getFileSystem();
util.createFiles(fs, "/srcdat", replFactor);
util.waitReplication(fs, "/srcdat", (short)2);
// Now deliberately remove/truncate meta blocks from the first
// directory of the first datanode. The complete absense of a meta
// file disallows this Datanode to send data to another datanode.
// However, a client is alowed access to this block.
//
File data_dir = new File(System.getProperty("test.build.data"),
- "dfs/data/data1/current");
+ "dfs/data/data1" + MiniDFSCluster.FINALIZED_DIR_NAME);
assertTrue("data directory does not exist", data_dir.exists());
File[] blocks = data_dir.listFiles();
assertTrue("Blocks do not exist in data-dir", (blocks != null) && (blocks.length > 0));
int num = 0;
for (int idx = 0; idx < blocks.length; idx++) {
if (blocks[idx].getName().startsWith("blk_") &&
blocks[idx].getName().endsWith(".meta")) {
num++;
if (num % 3 == 0) {
//
// remove .meta file
//
System.out.println("Deliberately removing file " + blocks[idx].getName());
assertTrue("Cannot remove file.", blocks[idx].delete());
} else if (num % 3 == 1) {
//
// shorten .meta file
//
RandomAccessFile file = new RandomAccessFile(blocks[idx], "rw");
FileChannel channel = file.getChannel();
int newsize = random.nextInt((int)channel.size()/2);
System.out.println("Deliberately truncating file " +
blocks[idx].getName() +
" to size " + newsize + " bytes.");
channel.truncate(newsize);
file.close();
} else {
//
// corrupt a few bytes of the metafile
//
RandomAccessFile file = new RandomAccessFile(blocks[idx], "rw");
FileChannel channel = file.getChannel();
long position = 0;
//
// The very first time, corrupt the meta header at offset 0
//
if (num != 2) {
position = (long)random.nextInt((int)channel.size());
}
int length = random.nextInt((int)(channel.size() - position + 1));
byte[] buffer = new byte[length];
random.nextBytes(buffer);
channel.write(ByteBuffer.wrap(buffer), position);
System.out.println("Deliberately corrupting file " +
blocks[idx].getName() +
" at offset " + position +
" length " + length);
file.close();
}
}
}
//
// Now deliberately corrupt all meta blocks from the second
// directory of the first datanode
//
data_dir = new File(System.getProperty("test.build.data"),
- "dfs/data/data2/current");
+ "dfs/data/data2" + MiniDFSCluster.FINALIZED_DIR_NAME);
assertTrue("data directory does not exist", data_dir.exists());
blocks = data_dir.listFiles();
assertTrue("Blocks do not exist in data-dir", (blocks != null) && (blocks.length > 0));
int count = 0;
File previous = null;
for (int idx = 0; idx < blocks.length; idx++) {
if (blocks[idx].getName().startsWith("blk_") &&
blocks[idx].getName().endsWith(".meta")) {
//
// Move the previous metafile into the current one.
//
count++;
if (count % 2 == 0) {
System.out.println("Deliberately insertimg bad crc into files " +
blocks[idx].getName() + " " + previous.getName());
assertTrue("Cannot remove file.", blocks[idx].delete());
assertTrue("Cannot corrupt meta file.", previous.renameTo(blocks[idx]));
assertTrue("Cannot recreate empty meta file.", previous.createNewFile());
previous = null;
} else {
previous = blocks[idx];
}
}
}
//
// Only one replica is possibly corrupted. The other replica should still
// be good. Verify.
//
assertTrue("Corrupted replicas not handled properly.",
util.checkFiles(fs, "/srcdat"));
System.out.println("All File still have a valid replica");
//
// set replication factor back to 1. This causes only one replica of
// of each block to remain in HDFS. The check is to make sure that
// the corrupted replica generated above is the one that gets deleted.
// This test is currently disabled until HADOOP-1557 is solved.
//
util.setReplication(fs, "/srcdat", (short)1);
//util.waitReplication(fs, "/srcdat", (short)1);
//System.out.println("All Files done with removing replicas");
//assertTrue("Excess replicas deleted. Corrupted replicas found.",
// util.checkFiles(fs, "/srcdat"));
System.out.println("The excess-corrupted-replica test is disabled " +
" pending HADOOP-1557");
util.cleanup(fs, "/srcdat");
} finally {
if (cluster != null) { cluster.shutdown(); }
}
}
public void testCrcCorruption() throws Exception {
//
// default parameters
//
System.out.println("TestCrcCorruption with default parameters");
Configuration conf1 = new HdfsConfiguration();
conf1.setInt("dfs.blockreport.intervalMsec", 3 * 1000);
DFSTestUtil util1 = new DFSTestUtil("TestCrcCorruption", 40, 3, 8*1024);
thistest(conf1, util1);
//
// specific parameters
//
System.out.println("TestCrcCorruption with specific parameters");
Configuration conf2 = new HdfsConfiguration();
conf2.setInt(DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY, 17);
conf2.setInt(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, 34);
DFSTestUtil util2 = new DFSTestUtil("TestCrcCorruption", 40, 3, 400);
thistest(conf2, util2);
}
}
| false | true | private void thistest(Configuration conf, DFSTestUtil util) throws Exception {
MiniDFSCluster cluster = null;
int numDataNodes = 2;
short replFactor = 2;
Random random = new Random();
try {
cluster = new MiniDFSCluster(conf, numDataNodes, true, null);
cluster.waitActive();
FileSystem fs = cluster.getFileSystem();
util.createFiles(fs, "/srcdat", replFactor);
util.waitReplication(fs, "/srcdat", (short)2);
// Now deliberately remove/truncate meta blocks from the first
// directory of the first datanode. The complete absense of a meta
// file disallows this Datanode to send data to another datanode.
// However, a client is alowed access to this block.
//
File data_dir = new File(System.getProperty("test.build.data"),
"dfs/data/data1/current");
assertTrue("data directory does not exist", data_dir.exists());
File[] blocks = data_dir.listFiles();
assertTrue("Blocks do not exist in data-dir", (blocks != null) && (blocks.length > 0));
int num = 0;
for (int idx = 0; idx < blocks.length; idx++) {
if (blocks[idx].getName().startsWith("blk_") &&
blocks[idx].getName().endsWith(".meta")) {
num++;
if (num % 3 == 0) {
//
// remove .meta file
//
System.out.println("Deliberately removing file " + blocks[idx].getName());
assertTrue("Cannot remove file.", blocks[idx].delete());
} else if (num % 3 == 1) {
//
// shorten .meta file
//
RandomAccessFile file = new RandomAccessFile(blocks[idx], "rw");
FileChannel channel = file.getChannel();
int newsize = random.nextInt((int)channel.size()/2);
System.out.println("Deliberately truncating file " +
blocks[idx].getName() +
" to size " + newsize + " bytes.");
channel.truncate(newsize);
file.close();
} else {
//
// corrupt a few bytes of the metafile
//
RandomAccessFile file = new RandomAccessFile(blocks[idx], "rw");
FileChannel channel = file.getChannel();
long position = 0;
//
// The very first time, corrupt the meta header at offset 0
//
if (num != 2) {
position = (long)random.nextInt((int)channel.size());
}
int length = random.nextInt((int)(channel.size() - position + 1));
byte[] buffer = new byte[length];
random.nextBytes(buffer);
channel.write(ByteBuffer.wrap(buffer), position);
System.out.println("Deliberately corrupting file " +
blocks[idx].getName() +
" at offset " + position +
" length " + length);
file.close();
}
}
}
//
// Now deliberately corrupt all meta blocks from the second
// directory of the first datanode
//
data_dir = new File(System.getProperty("test.build.data"),
"dfs/data/data2/current");
assertTrue("data directory does not exist", data_dir.exists());
blocks = data_dir.listFiles();
assertTrue("Blocks do not exist in data-dir", (blocks != null) && (blocks.length > 0));
int count = 0;
File previous = null;
for (int idx = 0; idx < blocks.length; idx++) {
if (blocks[idx].getName().startsWith("blk_") &&
blocks[idx].getName().endsWith(".meta")) {
//
// Move the previous metafile into the current one.
//
count++;
if (count % 2 == 0) {
System.out.println("Deliberately insertimg bad crc into files " +
blocks[idx].getName() + " " + previous.getName());
assertTrue("Cannot remove file.", blocks[idx].delete());
assertTrue("Cannot corrupt meta file.", previous.renameTo(blocks[idx]));
assertTrue("Cannot recreate empty meta file.", previous.createNewFile());
previous = null;
} else {
previous = blocks[idx];
}
}
}
//
// Only one replica is possibly corrupted. The other replica should still
// be good. Verify.
//
assertTrue("Corrupted replicas not handled properly.",
util.checkFiles(fs, "/srcdat"));
System.out.println("All File still have a valid replica");
//
// set replication factor back to 1. This causes only one replica of
// of each block to remain in HDFS. The check is to make sure that
// the corrupted replica generated above is the one that gets deleted.
// This test is currently disabled until HADOOP-1557 is solved.
//
util.setReplication(fs, "/srcdat", (short)1);
//util.waitReplication(fs, "/srcdat", (short)1);
//System.out.println("All Files done with removing replicas");
//assertTrue("Excess replicas deleted. Corrupted replicas found.",
// util.checkFiles(fs, "/srcdat"));
System.out.println("The excess-corrupted-replica test is disabled " +
" pending HADOOP-1557");
util.cleanup(fs, "/srcdat");
} finally {
if (cluster != null) { cluster.shutdown(); }
}
}
| private void thistest(Configuration conf, DFSTestUtil util) throws Exception {
MiniDFSCluster cluster = null;
int numDataNodes = 2;
short replFactor = 2;
Random random = new Random();
try {
cluster = new MiniDFSCluster(conf, numDataNodes, true, null);
cluster.waitActive();
FileSystem fs = cluster.getFileSystem();
util.createFiles(fs, "/srcdat", replFactor);
util.waitReplication(fs, "/srcdat", (short)2);
// Now deliberately remove/truncate meta blocks from the first
// directory of the first datanode. The complete absense of a meta
// file disallows this Datanode to send data to another datanode.
// However, a client is alowed access to this block.
//
File data_dir = new File(System.getProperty("test.build.data"),
"dfs/data/data1" + MiniDFSCluster.FINALIZED_DIR_NAME);
assertTrue("data directory does not exist", data_dir.exists());
File[] blocks = data_dir.listFiles();
assertTrue("Blocks do not exist in data-dir", (blocks != null) && (blocks.length > 0));
int num = 0;
for (int idx = 0; idx < blocks.length; idx++) {
if (blocks[idx].getName().startsWith("blk_") &&
blocks[idx].getName().endsWith(".meta")) {
num++;
if (num % 3 == 0) {
//
// remove .meta file
//
System.out.println("Deliberately removing file " + blocks[idx].getName());
assertTrue("Cannot remove file.", blocks[idx].delete());
} else if (num % 3 == 1) {
//
// shorten .meta file
//
RandomAccessFile file = new RandomAccessFile(blocks[idx], "rw");
FileChannel channel = file.getChannel();
int newsize = random.nextInt((int)channel.size()/2);
System.out.println("Deliberately truncating file " +
blocks[idx].getName() +
" to size " + newsize + " bytes.");
channel.truncate(newsize);
file.close();
} else {
//
// corrupt a few bytes of the metafile
//
RandomAccessFile file = new RandomAccessFile(blocks[idx], "rw");
FileChannel channel = file.getChannel();
long position = 0;
//
// The very first time, corrupt the meta header at offset 0
//
if (num != 2) {
position = (long)random.nextInt((int)channel.size());
}
int length = random.nextInt((int)(channel.size() - position + 1));
byte[] buffer = new byte[length];
random.nextBytes(buffer);
channel.write(ByteBuffer.wrap(buffer), position);
System.out.println("Deliberately corrupting file " +
blocks[idx].getName() +
" at offset " + position +
" length " + length);
file.close();
}
}
}
//
// Now deliberately corrupt all meta blocks from the second
// directory of the first datanode
//
data_dir = new File(System.getProperty("test.build.data"),
"dfs/data/data2" + MiniDFSCluster.FINALIZED_DIR_NAME);
assertTrue("data directory does not exist", data_dir.exists());
blocks = data_dir.listFiles();
assertTrue("Blocks do not exist in data-dir", (blocks != null) && (blocks.length > 0));
int count = 0;
File previous = null;
for (int idx = 0; idx < blocks.length; idx++) {
if (blocks[idx].getName().startsWith("blk_") &&
blocks[idx].getName().endsWith(".meta")) {
//
// Move the previous metafile into the current one.
//
count++;
if (count % 2 == 0) {
System.out.println("Deliberately insertimg bad crc into files " +
blocks[idx].getName() + " " + previous.getName());
assertTrue("Cannot remove file.", blocks[idx].delete());
assertTrue("Cannot corrupt meta file.", previous.renameTo(blocks[idx]));
assertTrue("Cannot recreate empty meta file.", previous.createNewFile());
previous = null;
} else {
previous = blocks[idx];
}
}
}
//
// Only one replica is possibly corrupted. The other replica should still
// be good. Verify.
//
assertTrue("Corrupted replicas not handled properly.",
util.checkFiles(fs, "/srcdat"));
System.out.println("All File still have a valid replica");
//
// set replication factor back to 1. This causes only one replica of
// of each block to remain in HDFS. The check is to make sure that
// the corrupted replica generated above is the one that gets deleted.
// This test is currently disabled until HADOOP-1557 is solved.
//
util.setReplication(fs, "/srcdat", (short)1);
//util.waitReplication(fs, "/srcdat", (short)1);
//System.out.println("All Files done with removing replicas");
//assertTrue("Excess replicas deleted. Corrupted replicas found.",
// util.checkFiles(fs, "/srcdat"));
System.out.println("The excess-corrupted-replica test is disabled " +
" pending HADOOP-1557");
util.cleanup(fs, "/srcdat");
} finally {
if (cluster != null) { cluster.shutdown(); }
}
}
|
diff --git a/jwamp-core/src/main/java/com/github/ghetolay/jwamp/utils/TimeoutHashMap.java b/jwamp-core/src/main/java/com/github/ghetolay/jwamp/utils/TimeoutHashMap.java
index 8d74997..a7a7db2 100644
--- a/jwamp-core/src/main/java/com/github/ghetolay/jwamp/utils/TimeoutHashMap.java
+++ b/jwamp-core/src/main/java/com/github/ghetolay/jwamp/utils/TimeoutHashMap.java
@@ -1,162 +1,164 @@
/**
*Copyright [2012] [Ghetolay]
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
*http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/
package com.github.ghetolay.jwamp.utils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class TimeoutHashMap<K,V> extends HashMap<K,V>{
private static final long serialVersionUID = 3164054746684312958L;
private TimeoutThread updater;
Set<TimeoutListener<K,V>> listeners = new HashSet<TimeoutListener<K,V>>();
public TimeoutHashMap() {
updater = new TimeoutThread();
updater.start();
}
public void addListener(TimeoutListener<K,V> listener){
listeners.add(listener);
}
public void removeListener(TimeoutListener<K,V> listener){
listeners.remove(listener);
}
public void put(K key, V value, long timeout){
if(timeout > 0)
updater.add(key,timeout);
super.put(key, value);
}
@SuppressWarnings("unchecked")
protected V remove(Object key, boolean deleteToRemove){
V result = super.remove(key);
if(deleteToRemove)
updater.removeFromSet(key);
else
for(TimeoutListener<K,V> l : listeners)
l.timedOut((K)key, result);
return result;
}
@Override
public V remove(Object key){
return remove(key,true);
}
@Override
public void finalize(){
updater.interrupt();
}
private class TimeoutThread extends Thread{
//TODO change to FieldMap when finish
HashMap<K,ToRemove> toRemove = new HashMap<K,ToRemove>();
long minimalWait = -1;
long sleepUntil = 0;
public synchronized void add(K key, long timeout){
if(toRemove.isEmpty())
notify();
if(System.currentTimeMillis() + timeout < sleepUntil)
minimalWait = timeout;
notify();
synchronized(toRemove){
toRemove.put(key,new ToRemove(key,timeout));
}
}
public void removeFromSet(Object key){
synchronized(toRemove){
toRemove.remove(key);
}
}
public synchronized void run() {
try{
while(!isInterrupted()){
- if(toRemove.isEmpty())
+ if(toRemove.isEmpty()){
+ minimalWait = -1;
wait();
+ }
//if minimalWait is >0 it means it has been set by add(key,timeout)
if(minimalWait < 0){
long currentTime = System.currentTimeMillis();
minimalWait = Long.MAX_VALUE;
sleepUntil = 0;
synchronized(toRemove){
for(Iterator<Map.Entry<K, ToRemove>> it = toRemove.entrySet().iterator(); it.hasNext();){
ToRemove tr = it.next().getValue();
long timeleft = tr.timeLeft(currentTime);
if(timeleft <= 0){
it.remove();
remove(tr.key, false);
}else
if(timeleft < minimalWait)
minimalWait = timeleft;
}
}
}
if(minimalWait != Long.MAX_VALUE){
//we reset minimalWait before the wait
long gowait = minimalWait;
minimalWait = -1;
sleepUntil = System.currentTimeMillis() + gowait;
wait(gowait);
}
}
}catch(InterruptedException e){}
}
}
private class ToRemove{
long timeout;
long startTime;
K key;
private ToRemove(K key, long timeout){
startTime = System.currentTimeMillis();
this.timeout = timeout;
this.key = key;
}
private long timeLeft(long currentTime){
return timeout - (currentTime - startTime);
}
}
public static interface TimeoutListener<K,V>{
public void timedOut(K key, V value);
}
}
| false | true | public synchronized void run() {
try{
while(!isInterrupted()){
if(toRemove.isEmpty())
wait();
//if minimalWait is >0 it means it has been set by add(key,timeout)
if(minimalWait < 0){
long currentTime = System.currentTimeMillis();
minimalWait = Long.MAX_VALUE;
sleepUntil = 0;
synchronized(toRemove){
for(Iterator<Map.Entry<K, ToRemove>> it = toRemove.entrySet().iterator(); it.hasNext();){
ToRemove tr = it.next().getValue();
long timeleft = tr.timeLeft(currentTime);
if(timeleft <= 0){
it.remove();
remove(tr.key, false);
}else
if(timeleft < minimalWait)
minimalWait = timeleft;
}
}
}
if(minimalWait != Long.MAX_VALUE){
//we reset minimalWait before the wait
long gowait = minimalWait;
minimalWait = -1;
sleepUntil = System.currentTimeMillis() + gowait;
wait(gowait);
}
}
}catch(InterruptedException e){}
}
| public synchronized void run() {
try{
while(!isInterrupted()){
if(toRemove.isEmpty()){
minimalWait = -1;
wait();
}
//if minimalWait is >0 it means it has been set by add(key,timeout)
if(minimalWait < 0){
long currentTime = System.currentTimeMillis();
minimalWait = Long.MAX_VALUE;
sleepUntil = 0;
synchronized(toRemove){
for(Iterator<Map.Entry<K, ToRemove>> it = toRemove.entrySet().iterator(); it.hasNext();){
ToRemove tr = it.next().getValue();
long timeleft = tr.timeLeft(currentTime);
if(timeleft <= 0){
it.remove();
remove(tr.key, false);
}else
if(timeleft < minimalWait)
minimalWait = timeleft;
}
}
}
if(minimalWait != Long.MAX_VALUE){
//we reset minimalWait before the wait
long gowait = minimalWait;
minimalWait = -1;
sleepUntil = System.currentTimeMillis() + gowait;
wait(gowait);
}
}
}catch(InterruptedException e){}
}
|
diff --git a/common/src/org/bedework/timezones/common/ZipCachedData.java b/common/src/org/bedework/timezones/common/ZipCachedData.java
index 95cfc8c..0ae8489 100644
--- a/common/src/org/bedework/timezones/common/ZipCachedData.java
+++ b/common/src/org/bedework/timezones/common/ZipCachedData.java
@@ -1,330 +1,335 @@
/* ********************************************************************
Licensed to Jasig under one or more contributor license
agreements. See the NOTICE file distributed with this work
for additional information regarding copyright ownership.
Jasig licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a
copy of the License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.bedework.timezones.common;
import org.bedework.timezones.common.Differ.DiffListEntry;
import edu.rpi.cmt.calendar.XcalUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/** Cached data affected by the source data.
*
* @author douglm
*/
public class ZipCachedData extends AbstractCachedData {
private String tzdataUrl;
private ZipFile tzDefsZipFile;
private File tzDefsFile;
/**
* @param tzdataUrl
* @throws TzException
*/
public ZipCachedData(final String tzdataUrl) throws TzException {
super("Zip");
this.tzdataUrl = tzdataUrl;
loadData();
}
@Override
public void stop() throws TzException {
}
@Override
public void setPrimaryUrl(final String val) throws TzException {
// Ignore
}
@Override
public String getPrimaryUrl() throws TzException {
return TzServerUtil.getInitialPrimaryUrl();
}
@Override
public void setPrimaryServer(final boolean val) throws TzException {
// Ignore
}
@Override
public boolean getPrimaryServer() throws TzException {
return TzServerUtil.getInitialPrimaryServer();
}
@Override
public void setRefreshInterval(final long val) throws TzException {
// Ignore
}
@Override
public long getRefreshInterval() throws TzException {
return TzServerUtil.getInitialRefreshInterval();
}
@Override
public void checkData() throws TzException {
loadData();
}
@Override
public void updateData(final String dtstamp,
final List<DiffListEntry> dles) throws TzException {
// XXX ??
}
@Override
public List<String> findIds(final String val) throws TzException {
List<String> ids = new ArrayList<String>();
return ids;
}
private synchronized void loadData() throws TzException {
try {
long smillis = System.currentTimeMillis();
/* ======================== First get the data file =================== */
File f = getdata();
/* ============================ open a zip file ======================= */
ZipFile zf = new ZipFile(f);
if (tzDefsZipFile != null) {
try {
tzDefsZipFile.close();
} catch (Throwable t) {
}
}
if (tzDefsFile != null) {
try {
tzDefsFile.delete();
} catch (Throwable t) {
}
}
tzDefsFile = f;
tzDefsZipFile = zf;
TzServerUtil.lastDataFetch = System.currentTimeMillis();
/* ========================= get the data info ======================== */
ZipEntry ze = tzDefsZipFile.getEntry("info.txt");
String info = entryToString(ze);
String[] infoLines = info.split("\n");
for (String s: infoLines) {
if (s.startsWith("buildTime=")) {
- dtstamp = XcalUtil.getXmlFormatDateTime(s.substring("buildTime=".length()));
+ String bt = s.substring("buildTime=".length());
+ if (!bt.endsWith("Z")) {
+ // Pretend it's UTC
+ bt += "Z";
+ }
+ dtstamp = XcalUtil.getXmlFormatDateTime(bt);
}
}
/* ===================== Rebuild the alias maps ======================= */
aliasMaps = buildAliasMaps(tzDefsZipFile);
/* ===================== All tzs into the table ======================= */
unzipTzs(tzDefsZipFile, dtstamp);
expansions.clear();
TzServerUtil.reloadsMillis += System.currentTimeMillis() - smillis;
TzServerUtil.reloads++;
} catch (Throwable t) {
throw new TzException(t);
}
}
private AliasMaps buildAliasMaps(final ZipFile tzDefsZipFile) throws TzException {
try {
ZipEntry ze = tzDefsZipFile.getEntry("aliases.txt");
AliasMaps maps = new AliasMaps();
maps.aliasesStr = entryToString(ze);
maps.byTzid = new HashMap<String, SortedSet<String>>();
maps.byAlias = new HashMap<String, String>();
maps.aliases = new Properties();
StringReader sr = new StringReader(maps.aliasesStr);
maps.aliases.load(sr);
for (String a: maps.aliases.stringPropertyNames()) {
String id = maps.aliases.getProperty(a);
maps.byAlias.put(a, id);
SortedSet<String> as = maps.byTzid.get(id);
if (as == null) {
as = new TreeSet<String>();
maps.byTzid.put(id, as);
}
as.add(a);
}
return maps;
} catch (Throwable t) {
throw new TzException(t);
}
}
private void unzipTzs(final ZipFile tzDefsZipFile,
final String dtstamp) throws TzException {
try {
resetTzs();
Enumeration<? extends ZipEntry> zes = tzDefsZipFile.entries();
while (zes.hasMoreElements()) {
ZipEntry ze = zes.nextElement();
if (ze.isDirectory()) {
continue;
}
String n = ze.getName();
if (!(n.startsWith("zoneinfo/") && n.endsWith(".ics"))) {
continue;
}
String id = n.substring(9, n.length() - 4);
processSpec(id, entryToString(ze), null);
}
} catch (Throwable t) {
throw new TzException(t);
}
}
/** Retrieve the data and store in a temp file. Return the file object.
*
* @return File
* @throws TzException
*/
private File getdata() throws TzException {
try {
String dataUrl = tzdataUrl;
if (dataUrl == null) {
throw new TzException("No data url defined");
}
if (!dataUrl.startsWith("http:")) {
return new File(dataUrl);
}
/* Fetch the data */
HttpClient client = new DefaultHttpClient();
HttpRequestBase get = new HttpGet(dataUrl);
HttpResponse resp = client.execute(get);
InputStream is = null;
FileOutputStream fos = null;
try {
is = resp.getEntity().getContent();
File f = File.createTempFile("bwtzserver", "zip");
fos = new FileOutputStream(f);
byte[] buff = new byte[4096];
for (;;) {
int num = is.read(buff);
if (num < 0) {
break;
}
if (num > 0) {
fos.write(buff, 0, num);
}
}
return f;
} finally {
try {
fos.close();
} finally {}
try {
is.close();
} finally {}
}
} catch (Throwable t) {
throw new TzException(t);
}
}
private String entryToString(final ZipEntry ze) throws Throwable {
InputStreamReader is = new InputStreamReader(tzDefsZipFile.getInputStream(ze),
"UTF-8");
StringWriter sw = new StringWriter();
char[] buff = new char[4096];
for (;;) {
int num = is.read(buff);
if (num < 0) {
break;
}
if (num > 0) {
sw.write(buff, 0, num);
}
}
is.close();
return sw.toString();
}
}
| true | true | private synchronized void loadData() throws TzException {
try {
long smillis = System.currentTimeMillis();
/* ======================== First get the data file =================== */
File f = getdata();
/* ============================ open a zip file ======================= */
ZipFile zf = new ZipFile(f);
if (tzDefsZipFile != null) {
try {
tzDefsZipFile.close();
} catch (Throwable t) {
}
}
if (tzDefsFile != null) {
try {
tzDefsFile.delete();
} catch (Throwable t) {
}
}
tzDefsFile = f;
tzDefsZipFile = zf;
TzServerUtil.lastDataFetch = System.currentTimeMillis();
/* ========================= get the data info ======================== */
ZipEntry ze = tzDefsZipFile.getEntry("info.txt");
String info = entryToString(ze);
String[] infoLines = info.split("\n");
for (String s: infoLines) {
if (s.startsWith("buildTime=")) {
dtstamp = XcalUtil.getXmlFormatDateTime(s.substring("buildTime=".length()));
}
}
/* ===================== Rebuild the alias maps ======================= */
aliasMaps = buildAliasMaps(tzDefsZipFile);
/* ===================== All tzs into the table ======================= */
unzipTzs(tzDefsZipFile, dtstamp);
expansions.clear();
TzServerUtil.reloadsMillis += System.currentTimeMillis() - smillis;
TzServerUtil.reloads++;
} catch (Throwable t) {
throw new TzException(t);
}
}
| private synchronized void loadData() throws TzException {
try {
long smillis = System.currentTimeMillis();
/* ======================== First get the data file =================== */
File f = getdata();
/* ============================ open a zip file ======================= */
ZipFile zf = new ZipFile(f);
if (tzDefsZipFile != null) {
try {
tzDefsZipFile.close();
} catch (Throwable t) {
}
}
if (tzDefsFile != null) {
try {
tzDefsFile.delete();
} catch (Throwable t) {
}
}
tzDefsFile = f;
tzDefsZipFile = zf;
TzServerUtil.lastDataFetch = System.currentTimeMillis();
/* ========================= get the data info ======================== */
ZipEntry ze = tzDefsZipFile.getEntry("info.txt");
String info = entryToString(ze);
String[] infoLines = info.split("\n");
for (String s: infoLines) {
if (s.startsWith("buildTime=")) {
String bt = s.substring("buildTime=".length());
if (!bt.endsWith("Z")) {
// Pretend it's UTC
bt += "Z";
}
dtstamp = XcalUtil.getXmlFormatDateTime(bt);
}
}
/* ===================== Rebuild the alias maps ======================= */
aliasMaps = buildAliasMaps(tzDefsZipFile);
/* ===================== All tzs into the table ======================= */
unzipTzs(tzDefsZipFile, dtstamp);
expansions.clear();
TzServerUtil.reloadsMillis += System.currentTimeMillis() - smillis;
TzServerUtil.reloads++;
} catch (Throwable t) {
throw new TzException(t);
}
}
|
diff --git a/src/me/reddy360/theholyflint/listeners/WorldListener.java b/src/me/reddy360/theholyflint/listeners/WorldListener.java
index e836815..3a83d44 100644
--- a/src/me/reddy360/theholyflint/listeners/WorldListener.java
+++ b/src/me/reddy360/theholyflint/listeners/WorldListener.java
@@ -1,183 +1,180 @@
package me.reddy360.theholyflint.listeners;
import me.reddy360.theholyflint.PluginMain;
import net.minecraft.server.v1_4_6.Block;
import net.minecraft.server.v1_4_6.Item;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.block.Chest;
import org.bukkit.block.Dispenser;
import org.bukkit.block.Sign;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Painting;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDispenseEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.Vector;
import de.bananaco.bpermissions.api.ApiLayer;
import de.bananaco.bpermissions.api.util.CalculableType;
public class WorldListener implements Listener {
PluginMain pluginMain;
public WorldListener(PluginMain pluginMain) {
this.pluginMain = pluginMain;
}
@EventHandler
public void onBlockBreak(BlockBreakEvent e){
Player player = e.getPlayer();
if(e.isCancelled()){
return;
}
if(!player.hasPermission(pluginMain.pluginManager.getPermission("thf.world.modify"))){
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to break blocks!");
e.setCancelled(true);
}
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent e){
Player player = e.getPlayer();
if(e.isCancelled()){
return;
}
if(!player.hasPermission(pluginMain.pluginManager.getPermission("thf.world.modify"))){
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to place blocks!");
e.setCancelled(true);
}
}
@EventHandler
public void onBlockDispense(BlockDispenseEvent e){
if(e.isCancelled()){
return;
}
Dispenser dispenser = (Dispenser) e.getBlock().getState();
dispenser.getInventory().addItem(e.getItem());
}
@EventHandler
public void onWeatherChange(WeatherChangeEvent e){
if(e.toWeatherState()){
e.setCancelled(true);
}
}
@EventHandler
public void onSignChange(SignChangeEvent e){
if(e.getLine(1).equalsIgnoreCase("[THF]")){
if(!(e.getPlayer().hasPermission(pluginMain.pluginManager.getPermission("thf.makesign")))){
e.setCancelled(true);
e.getPlayer().sendMessage(ChatColor.DARK_RED + "You do not have permission to create [THF] signs.");
}
}
for(int x = 0; x < 4; x++){
e.setLine(x, ChatColor.translateAlternateColorCodes('&', e.getLine(x)));
}
}
@EventHandler
public void onEntityInteract(PlayerInteractEntityEvent e){
Player player = e.getPlayer();
if(e.getRightClicked() instanceof ItemFrame || e.getRightClicked() instanceof Painting){
if(player.hasPermission(pluginMain.pluginManager.getPermission("thf.world.modify"))){
}
}
}
@EventHandler
public void onItemDrop(PlayerDropItemEvent e){
Player player = e.getPlayer();
if(player.hasPermission(pluginMain.pluginManager.getPermission("thf.drop"))){
if(e.getItemDrop().getItemStack().getTypeId() != Item.FLINT.id){
player.sendMessage(ChatColor.DARK_RED + "You can only drop Flint!");
e.setCancelled(true);
}
}else if(player.hasPermission(pluginMain.pluginManager.getPermission("thf.drop.destroy"))){
if(e.getItemDrop().getItemStack().getTypeId() != Item.FLINT.id){
player.sendMessage(ChatColor.DARK_RED + "You can only drop Flint!");
e.setCancelled(true);
e.getItemDrop().setItemStack(new ItemStack(0, 0));
}
}else{
e.setCancelled(true);
}
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent e){
Player player = e.getPlayer();
if(e.getFrom().getBlock().getLocation().equals(e.getTo().getBlock().getLocation())){
return;
}
Location location = e.getTo();
location.setY(location.getY() - 2);
if(location.getBlock().getState() instanceof Sign){
Sign sign = (Sign) location.getBlock().getState();
if(sign.getLine(1).equalsIgnoreCase("[THF]")){
if(sign.getLine(3).equalsIgnoreCase("")){
doSignEvent(sign.getLine(2), player, location);
return;
}else if(ApiLayer.hasGroup("world", CalculableType.USER, e.getPlayer().getName(), sign.getLine(3))){
doSignEvent(sign.getLine(2), player, location);
return;
}else{
player.sendMessage(ChatColor.DARK_RED + "You do not have permission to use this sign. :(");
}
}
}
}
private void doSignEvent(String line, Player player, Location signLocation) {
if(line.startsWith("Launch:")){
if(line.split(":").length == 1){
return;
}
player.getWorld().createExplosion(player.getLocation(), 0F);
Location location = player.getLocation().clone();
location.setPitch(-90);
Vector direction = location.getDirection();
try{
player.setVelocity(direction.multiply(Float.parseFloat(line.split(":")[1])));
/* player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, Integer.parseInt(line.split(":")[1]) * 2 * 20, 5)
, true); */
player.setFallDistance(Float.parseFloat(line.split(":")[1]) - (Float.parseFloat(line.split(":")[1]) * 2));
}catch(NumberFormatException e){
}
- }else if(line.startsWith("Chest:")){
- if(line.split(":").length == 1){
- return;
- }
+ }else if(line.startsWith("Chest")){
Location location = signLocation;
location.setY(location.getY() - 1);
if(location.getBlock().getTypeId() == Block.CHEST.id){
Chest chest = (Chest) location.getBlock().getState();
player.getInventory().setContents(chest.getBlockInventory().getContents());
}
}else if(line.startsWith("Potion:")){
if(line.split(":").length < 4){
return;
}
String[] lines = line.split(":");
player.addPotionEffect(new PotionEffect(PotionEffectType.getById(Integer.parseInt(lines[1])), Integer.parseInt(lines[2]), Integer.parseInt(lines[3]), true));
}
}
}
| true | true | private void doSignEvent(String line, Player player, Location signLocation) {
if(line.startsWith("Launch:")){
if(line.split(":").length == 1){
return;
}
player.getWorld().createExplosion(player.getLocation(), 0F);
Location location = player.getLocation().clone();
location.setPitch(-90);
Vector direction = location.getDirection();
try{
player.setVelocity(direction.multiply(Float.parseFloat(line.split(":")[1])));
/* player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, Integer.parseInt(line.split(":")[1]) * 2 * 20, 5)
, true); */
player.setFallDistance(Float.parseFloat(line.split(":")[1]) - (Float.parseFloat(line.split(":")[1]) * 2));
}catch(NumberFormatException e){
}
}else if(line.startsWith("Chest:")){
if(line.split(":").length == 1){
return;
}
Location location = signLocation;
location.setY(location.getY() - 1);
if(location.getBlock().getTypeId() == Block.CHEST.id){
Chest chest = (Chest) location.getBlock().getState();
player.getInventory().setContents(chest.getBlockInventory().getContents());
}
}else if(line.startsWith("Potion:")){
if(line.split(":").length < 4){
return;
}
String[] lines = line.split(":");
player.addPotionEffect(new PotionEffect(PotionEffectType.getById(Integer.parseInt(lines[1])), Integer.parseInt(lines[2]), Integer.parseInt(lines[3]), true));
}
}
| private void doSignEvent(String line, Player player, Location signLocation) {
if(line.startsWith("Launch:")){
if(line.split(":").length == 1){
return;
}
player.getWorld().createExplosion(player.getLocation(), 0F);
Location location = player.getLocation().clone();
location.setPitch(-90);
Vector direction = location.getDirection();
try{
player.setVelocity(direction.multiply(Float.parseFloat(line.split(":")[1])));
/* player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, Integer.parseInt(line.split(":")[1]) * 2 * 20, 5)
, true); */
player.setFallDistance(Float.parseFloat(line.split(":")[1]) - (Float.parseFloat(line.split(":")[1]) * 2));
}catch(NumberFormatException e){
}
}else if(line.startsWith("Chest")){
Location location = signLocation;
location.setY(location.getY() - 1);
if(location.getBlock().getTypeId() == Block.CHEST.id){
Chest chest = (Chest) location.getBlock().getState();
player.getInventory().setContents(chest.getBlockInventory().getContents());
}
}else if(line.startsWith("Potion:")){
if(line.split(":").length < 4){
return;
}
String[] lines = line.split(":");
player.addPotionEffect(new PotionEffect(PotionEffectType.getById(Integer.parseInt(lines[1])), Integer.parseInt(lines[2]), Integer.parseInt(lines[3]), true));
}
}
|
diff --git a/src/evopaint/gui/rulesetmanager/JConditionTargetPanel.java b/src/evopaint/gui/rulesetmanager/JConditionTargetPanel.java
index 6fc9576..595b4d6 100644
--- a/src/evopaint/gui/rulesetmanager/JConditionTargetPanel.java
+++ b/src/evopaint/gui/rulesetmanager/JConditionTargetPanel.java
@@ -1,190 +1,190 @@
/*
* Copyright (C) 2010 Markus Echterhoff <[email protected]>
*
* This file is part of EvoPaint.
*
* EvoPaint is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EvoPaint. If not, see <http://www.gnu.org/licenses/>.
*/
package evopaint.gui.rulesetmanager;
import evopaint.gui.rulesetmanager.util.JRangeSlider;
import evopaint.pixel.rulebased.targeting.ActionMetaTarget;
import evopaint.pixel.rulebased.targeting.IConditionTarget;
import evopaint.pixel.rulebased.targeting.ConditionMetaTarget;
import evopaint.pixel.rulebased.targeting.ConditionTarget;
import evopaint.pixel.rulebased.targeting.ITarget;
import evopaint.pixel.rulebased.targeting.MetaTarget;
import evopaint.pixel.rulebased.targeting.SingleTarget;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
*
* @author Markus Echterhoff <[email protected]>
*/
public class JConditionTargetPanel extends JPanel {
private JRangeSlider jRangeSlider;
private JLabel lowValueLabel;
private JLabel highValueLabel;
private JTarget jTarget;
public JConditionTargetPanel(ITarget target) {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5);
final JPanel rangePanel = new JPanel();
rangePanel.setLayout(new BorderLayout());
JPanel lowAlignmentPanel = new JPanel();
lowAlignmentPanel.setLayout(new BorderLayout());
JPanel lowPanel = new JPanel();
final JLabel lowTextLabel = new JLabel("Min:");
lowPanel.add(lowTextLabel);
lowValueLabel = new JLabel();
lowPanel.add(lowValueLabel);
lowAlignmentPanel.add(lowPanel, BorderLayout.SOUTH);
rangePanel.add(lowAlignmentPanel, BorderLayout.WEST);
jRangeSlider = new JRangeSlider(0, 0, 0, 0, JRangeSlider.VERTICAL,
JRangeSlider.RIGHTLEFT_BOTTOMTOP);
if (target instanceof ConditionMetaTarget) {
jRangeSlider.setMinimum(0);
- jRangeSlider.setMaximum(((ConditionMetaTarget)target).getMax());
+ jRangeSlider.setMaximum(((ConditionMetaTarget)target).getDirections().size());
jRangeSlider.setLowValue(((ConditionMetaTarget)target).getMin());
jRangeSlider.setHighValue(((ConditionMetaTarget)target).getMax());
} else {
if (((SingleTarget)target).getDirection() == null) {
jRangeSlider.setMinimum(0);
jRangeSlider.setMaximum(0);
jRangeSlider.setLowValue(0);
jRangeSlider.setHighValue(0);
} else {
jRangeSlider.setMinimum(0);
jRangeSlider.setMaximum(1);
jRangeSlider.setLowValue(1);
jRangeSlider.setHighValue(1);
}
}
lowValueLabel.setText(Integer.toString(jRangeSlider.getLowValue()));
jRangeSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
lowValueLabel.setText(Integer.toString(jRangeSlider.getLowValue()));
highValueLabel.setText(Integer.toString(jRangeSlider.getHighValue()));
}
});
rangePanel.add(jRangeSlider, BorderLayout.CENTER);
JPanel highPanel = new JPanel();
final JLabel highTextLabel = new JLabel("Max:");
highPanel.add(highTextLabel);
highValueLabel = new JLabel();
highPanel.add(highValueLabel);
rangePanel.add(highPanel, BorderLayout.EAST);
add(rangePanel, c);
final JLabel ofLabel = new JLabel("of");
c.gridx = 1;
add(ofLabel, c);
jTarget = new JTarget(target, new ActionListener(){
public void actionPerformed(ActionEvent e) {
int currentMax = (Integer)(jRangeSlider.getMaximum());
int newMax = ((JToggleButton)e.getSource()).isSelected() ? currentMax + 1 : currentMax - 1;
jRangeSlider.setMaximum(newMax);
if (jRangeSlider.getHighValue() == currentMax) {
jRangeSlider.setHighValue(newMax);
}
if (jRangeSlider.getLowValue() == currentMax) {
jRangeSlider.setLowValue(newMax);
}
if (newMax > 0) {
jRangeSlider.setEmpty(false);
lowValueLabel.setEnabled(true);
highValueLabel.setEnabled(true);
lowTextLabel.setEnabled(true);
highTextLabel.setEnabled(true);
ofLabel.setEnabled(true);
} else {
jRangeSlider.setEmpty(true);
lowValueLabel.setEnabled(false);
highValueLabel.setEnabled(false);
lowTextLabel.setEnabled(false);
highTextLabel.setEnabled(false);
ofLabel.setEnabled(false);
}
}
});
c.gridx = 2;
add(jTarget, c);
lowValueLabel.setText(Integer.toString(jRangeSlider.getLowValue()));
highValueLabel.setText(Integer.toString(jRangeSlider.getHighValue()));
if (jRangeSlider.getMaximum() > 0) {
jRangeSlider.setEmpty(false);
lowValueLabel.setEnabled(true);
highValueLabel.setEnabled(true);
lowTextLabel.setEnabled(true);
highTextLabel.setEnabled(true);
ofLabel.setEnabled(true);
} else {
jRangeSlider.setEmpty(true);
lowValueLabel.setEnabled(false);
highValueLabel.setEnabled(false);
lowTextLabel.setEnabled(false);
highTextLabel.setEnabled(false);
ofLabel.setEnabled(false);
}
}
public IConditionTarget createConditionTarget() {
ITarget target = jTarget.getTarget();
if (target == null) {
return new ConditionTarget();
}
if (target instanceof MetaTarget) {
return new ConditionMetaTarget(
((MetaTarget)target).getDirections(), jRangeSlider.getLowValue(),
jRangeSlider.getHighValue());
}
return new ConditionTarget(((SingleTarget)target).getDirection());
}
public ActionMetaTarget createQuantifiedActionTarget() {
assert (false);
return null;
}
}
| true | true | public JConditionTargetPanel(ITarget target) {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5);
final JPanel rangePanel = new JPanel();
rangePanel.setLayout(new BorderLayout());
JPanel lowAlignmentPanel = new JPanel();
lowAlignmentPanel.setLayout(new BorderLayout());
JPanel lowPanel = new JPanel();
final JLabel lowTextLabel = new JLabel("Min:");
lowPanel.add(lowTextLabel);
lowValueLabel = new JLabel();
lowPanel.add(lowValueLabel);
lowAlignmentPanel.add(lowPanel, BorderLayout.SOUTH);
rangePanel.add(lowAlignmentPanel, BorderLayout.WEST);
jRangeSlider = new JRangeSlider(0, 0, 0, 0, JRangeSlider.VERTICAL,
JRangeSlider.RIGHTLEFT_BOTTOMTOP);
if (target instanceof ConditionMetaTarget) {
jRangeSlider.setMinimum(0);
jRangeSlider.setMaximum(((ConditionMetaTarget)target).getMax());
jRangeSlider.setLowValue(((ConditionMetaTarget)target).getMin());
jRangeSlider.setHighValue(((ConditionMetaTarget)target).getMax());
} else {
if (((SingleTarget)target).getDirection() == null) {
jRangeSlider.setMinimum(0);
jRangeSlider.setMaximum(0);
jRangeSlider.setLowValue(0);
jRangeSlider.setHighValue(0);
} else {
jRangeSlider.setMinimum(0);
jRangeSlider.setMaximum(1);
jRangeSlider.setLowValue(1);
jRangeSlider.setHighValue(1);
}
}
lowValueLabel.setText(Integer.toString(jRangeSlider.getLowValue()));
jRangeSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
lowValueLabel.setText(Integer.toString(jRangeSlider.getLowValue()));
highValueLabel.setText(Integer.toString(jRangeSlider.getHighValue()));
}
});
rangePanel.add(jRangeSlider, BorderLayout.CENTER);
JPanel highPanel = new JPanel();
final JLabel highTextLabel = new JLabel("Max:");
highPanel.add(highTextLabel);
highValueLabel = new JLabel();
highPanel.add(highValueLabel);
rangePanel.add(highPanel, BorderLayout.EAST);
add(rangePanel, c);
final JLabel ofLabel = new JLabel("of");
c.gridx = 1;
add(ofLabel, c);
jTarget = new JTarget(target, new ActionListener(){
public void actionPerformed(ActionEvent e) {
int currentMax = (Integer)(jRangeSlider.getMaximum());
int newMax = ((JToggleButton)e.getSource()).isSelected() ? currentMax + 1 : currentMax - 1;
jRangeSlider.setMaximum(newMax);
if (jRangeSlider.getHighValue() == currentMax) {
jRangeSlider.setHighValue(newMax);
}
if (jRangeSlider.getLowValue() == currentMax) {
jRangeSlider.setLowValue(newMax);
}
if (newMax > 0) {
jRangeSlider.setEmpty(false);
lowValueLabel.setEnabled(true);
highValueLabel.setEnabled(true);
lowTextLabel.setEnabled(true);
highTextLabel.setEnabled(true);
ofLabel.setEnabled(true);
} else {
jRangeSlider.setEmpty(true);
lowValueLabel.setEnabled(false);
highValueLabel.setEnabled(false);
lowTextLabel.setEnabled(false);
highTextLabel.setEnabled(false);
ofLabel.setEnabled(false);
}
}
});
c.gridx = 2;
add(jTarget, c);
lowValueLabel.setText(Integer.toString(jRangeSlider.getLowValue()));
highValueLabel.setText(Integer.toString(jRangeSlider.getHighValue()));
if (jRangeSlider.getMaximum() > 0) {
jRangeSlider.setEmpty(false);
lowValueLabel.setEnabled(true);
highValueLabel.setEnabled(true);
lowTextLabel.setEnabled(true);
highTextLabel.setEnabled(true);
ofLabel.setEnabled(true);
} else {
jRangeSlider.setEmpty(true);
lowValueLabel.setEnabled(false);
highValueLabel.setEnabled(false);
lowTextLabel.setEnabled(false);
highTextLabel.setEnabled(false);
ofLabel.setEnabled(false);
}
}
| public JConditionTargetPanel(ITarget target) {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5);
final JPanel rangePanel = new JPanel();
rangePanel.setLayout(new BorderLayout());
JPanel lowAlignmentPanel = new JPanel();
lowAlignmentPanel.setLayout(new BorderLayout());
JPanel lowPanel = new JPanel();
final JLabel lowTextLabel = new JLabel("Min:");
lowPanel.add(lowTextLabel);
lowValueLabel = new JLabel();
lowPanel.add(lowValueLabel);
lowAlignmentPanel.add(lowPanel, BorderLayout.SOUTH);
rangePanel.add(lowAlignmentPanel, BorderLayout.WEST);
jRangeSlider = new JRangeSlider(0, 0, 0, 0, JRangeSlider.VERTICAL,
JRangeSlider.RIGHTLEFT_BOTTOMTOP);
if (target instanceof ConditionMetaTarget) {
jRangeSlider.setMinimum(0);
jRangeSlider.setMaximum(((ConditionMetaTarget)target).getDirections().size());
jRangeSlider.setLowValue(((ConditionMetaTarget)target).getMin());
jRangeSlider.setHighValue(((ConditionMetaTarget)target).getMax());
} else {
if (((SingleTarget)target).getDirection() == null) {
jRangeSlider.setMinimum(0);
jRangeSlider.setMaximum(0);
jRangeSlider.setLowValue(0);
jRangeSlider.setHighValue(0);
} else {
jRangeSlider.setMinimum(0);
jRangeSlider.setMaximum(1);
jRangeSlider.setLowValue(1);
jRangeSlider.setHighValue(1);
}
}
lowValueLabel.setText(Integer.toString(jRangeSlider.getLowValue()));
jRangeSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
lowValueLabel.setText(Integer.toString(jRangeSlider.getLowValue()));
highValueLabel.setText(Integer.toString(jRangeSlider.getHighValue()));
}
});
rangePanel.add(jRangeSlider, BorderLayout.CENTER);
JPanel highPanel = new JPanel();
final JLabel highTextLabel = new JLabel("Max:");
highPanel.add(highTextLabel);
highValueLabel = new JLabel();
highPanel.add(highValueLabel);
rangePanel.add(highPanel, BorderLayout.EAST);
add(rangePanel, c);
final JLabel ofLabel = new JLabel("of");
c.gridx = 1;
add(ofLabel, c);
jTarget = new JTarget(target, new ActionListener(){
public void actionPerformed(ActionEvent e) {
int currentMax = (Integer)(jRangeSlider.getMaximum());
int newMax = ((JToggleButton)e.getSource()).isSelected() ? currentMax + 1 : currentMax - 1;
jRangeSlider.setMaximum(newMax);
if (jRangeSlider.getHighValue() == currentMax) {
jRangeSlider.setHighValue(newMax);
}
if (jRangeSlider.getLowValue() == currentMax) {
jRangeSlider.setLowValue(newMax);
}
if (newMax > 0) {
jRangeSlider.setEmpty(false);
lowValueLabel.setEnabled(true);
highValueLabel.setEnabled(true);
lowTextLabel.setEnabled(true);
highTextLabel.setEnabled(true);
ofLabel.setEnabled(true);
} else {
jRangeSlider.setEmpty(true);
lowValueLabel.setEnabled(false);
highValueLabel.setEnabled(false);
lowTextLabel.setEnabled(false);
highTextLabel.setEnabled(false);
ofLabel.setEnabled(false);
}
}
});
c.gridx = 2;
add(jTarget, c);
lowValueLabel.setText(Integer.toString(jRangeSlider.getLowValue()));
highValueLabel.setText(Integer.toString(jRangeSlider.getHighValue()));
if (jRangeSlider.getMaximum() > 0) {
jRangeSlider.setEmpty(false);
lowValueLabel.setEnabled(true);
highValueLabel.setEnabled(true);
lowTextLabel.setEnabled(true);
highTextLabel.setEnabled(true);
ofLabel.setEnabled(true);
} else {
jRangeSlider.setEmpty(true);
lowValueLabel.setEnabled(false);
highValueLabel.setEnabled(false);
lowTextLabel.setEnabled(false);
highTextLabel.setEnabled(false);
ofLabel.setEnabled(false);
}
}
|
diff --git a/weasis-dicom/weasis-dicom-explorer/src/main/java/org/weasis/dicom/explorer/DicomModel.java b/weasis-dicom/weasis-dicom-explorer/src/main/java/org/weasis/dicom/explorer/DicomModel.java
index 8445e797..67b0d555 100644
--- a/weasis-dicom/weasis-dicom-explorer/src/main/java/org/weasis/dicom/explorer/DicomModel.java
+++ b/weasis-dicom/weasis-dicom-explorer/src/main/java/org/weasis/dicom/explorer/DicomModel.java
@@ -1,662 +1,664 @@
/*******************************************************************************
* Copyright (c) 2010 Nicolas Roduit.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Nicolas Roduit - initial API and implementation
******************************************************************************/
package org.weasis.dicom.explorer;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.swing.SwingUtilities;
import org.noos.xing.mydoggy.plaf.persistence.xml.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.weasis.core.api.command.Option;
import org.weasis.core.api.command.Options;
import org.weasis.core.api.explorer.ObservableEvent;
import org.weasis.core.api.explorer.model.DataExplorerModel;
import org.weasis.core.api.explorer.model.Tree;
import org.weasis.core.api.explorer.model.TreeModel;
import org.weasis.core.api.explorer.model.TreeModelNode;
import org.weasis.core.api.gui.util.AbstractProperties;
import org.weasis.core.api.gui.util.GuiExecutor;
import org.weasis.core.api.media.data.Codec;
import org.weasis.core.api.media.data.MediaElement;
import org.weasis.core.api.media.data.MediaSeries;
import org.weasis.core.api.media.data.MediaSeriesGroup;
import org.weasis.core.api.media.data.MediaSeriesGroupNode;
import org.weasis.core.api.media.data.Series;
import org.weasis.core.api.media.data.TagW;
import org.weasis.core.api.media.data.Thumbnail;
import org.weasis.core.api.service.BundleTools;
import org.weasis.core.api.util.FileUtil;
import org.weasis.dicom.codec.DicomEncapDocElement;
import org.weasis.dicom.codec.DicomEncapDocSeries;
import org.weasis.dicom.codec.DicomImageElement;
import org.weasis.dicom.codec.DicomMediaIO;
import org.weasis.dicom.codec.DicomSeries;
import org.weasis.dicom.codec.DicomVideoElement;
import org.weasis.dicom.codec.DicomVideoSeries;
import org.weasis.dicom.codec.SortSeriesStack;
import org.weasis.dicom.codec.display.Modality;
import org.weasis.dicom.explorer.wado.LoadRemoteDicomManifest;
import org.weasis.dicom.explorer.wado.LoadRemoteDicomURL;
public class DicomModel implements TreeModel, DataExplorerModel {
private static final Logger LOGGER = LoggerFactory.getLogger(DicomModel.class);
public static final String[] functions = { "get", "close" }; //$NON-NLS-1$ //$NON-NLS-2$
public static final String NAME = "DICOM"; //$NON-NLS-1$
public static final String PREFERENCE_NODE = "dicom.model"; //$NON-NLS-1$
public static final TreeModelNode patient = new TreeModelNode(1, 0, TagW.PatientPseudoUID);
public static final TreeModelNode study = new TreeModelNode(2, 0, TagW.StudyInstanceUID);
public static final TreeModelNode series = new TreeModelNode(3, 0, TagW.SubseriesInstanceUID);
public static final ArrayList<TreeModelNode> modelStrucure = new ArrayList<TreeModelNode>(5);
static {
modelStrucure.add(root);
modelStrucure.add(patient);
modelStrucure.add(study);
modelStrucure.add(series);
}
public static final Executor loadingExecutor = Executors.newSingleThreadExecutor();
private final Tree<MediaSeriesGroup> model;
private PropertyChangeSupport propertyChange = null;
private final TagW[] multiframeSplittingRules = new TagW[] { TagW.ImageType, TagW.SOPInstanceUID, TagW.FrameType,
TagW.FrameAcquisitionNumber, TagW.StackID };
private final HashMap<Modality, TagW[]> splittingRules = new HashMap<Modality, TagW[]>();
public DicomModel() {
model = new Tree<MediaSeriesGroup>(rootNode);
// Preferences prefs = Activator.PREFERENCES.getDefaultPreferences();
// if (prefs == null) {
// } else {
// Preferences p = prefs.node(PREFERENCE_NODE);
// }
splittingRules.put(Modality.Default, new TagW[] { TagW.ImageType, TagW.ContrastBolusAgent, TagW.SOPClassUID });
splittingRules.put(Modality.CT, new TagW[] { TagW.ImageType, TagW.ContrastBolusAgent, TagW.SOPClassUID,
TagW.ImageOrientationPlane, TagW.GantryDetectorTilt, TagW.ConvolutionKernel });
splittingRules.put(Modality.PT, splittingRules.get(Modality.CT));
splittingRules.put(Modality.MR, new TagW[] { TagW.ImageType, TagW.ContrastBolusAgent, TagW.SOPClassUID,
TagW.ImageOrientationPlane, TagW.ScanningSequence, TagW.SequenceVariant, TagW.ScanOptions,
TagW.RepetitionTime, TagW.EchoTime, TagW.InversionTime, TagW.FlipAngle });
}
@Override
public synchronized List<Codec> getCodecPlugins() {
ArrayList<Codec> codecPlugins = new ArrayList<Codec>(1);
synchronized (BundleTools.CODEC_PLUGINS) {
for (Codec codec : BundleTools.CODEC_PLUGINS) {
if (codec != null && codec.isMimeTypeSupported("application/dicom") && !codecPlugins.contains(codec)) { //$NON-NLS-1$
codecPlugins.add(codec);
}
}
}
return codecPlugins;
}
@Override
public Collection<MediaSeriesGroup> getChildren(MediaSeriesGroup node) {
return model.getSuccessors(node);
}
@Override
public MediaSeriesGroup getHierarchyNode(MediaSeriesGroup parent, Object value) {
if (parent != null || value != null) {
synchronized (model) {
for (MediaSeriesGroup node : model.getSuccessors(parent)) {
if (node.equals(value))
return node;
}
}
}
return null;
}
@Override
public void addHierarchyNode(MediaSeriesGroup root, MediaSeriesGroup leaf) {
synchronized (model) {
model.addLeaf(root, leaf);
}
}
@Override
public void removeHierarchyNode(MediaSeriesGroup root, MediaSeriesGroup leaf) {
synchronized (model) {
Tree<MediaSeriesGroup> tree = model.getTree(root);
if (tree != null) {
tree.removeLeaf(leaf);
}
}
}
@Override
public MediaSeriesGroup getParent(MediaSeriesGroup node, TreeModelNode modelNode) {
if (null != node && modelNode != null) {
synchronized (model) {
Tree<MediaSeriesGroup> tree = model.getTree(node);
if (tree != null) {
Tree<MediaSeriesGroup> parent = null;
while ((parent = tree.getParent()) != null) {
if (parent.getHead().getTagID().equals(modelNode.getTagElement()))
return parent.getHead();
tree = parent;
}
}
}
}
return null;
}
public void dispose() {
synchronized (model) {
for (Iterator<MediaSeriesGroup> iterator = this.getChildren(TreeModel.rootNode).iterator(); iterator
.hasNext();) {
MediaSeriesGroup pt = iterator.next();
Collection<MediaSeriesGroup> studies = this.getChildren(pt);
for (Iterator<MediaSeriesGroup> iterator2 = studies.iterator(); iterator2.hasNext();) {
MediaSeriesGroup study = iterator2.next();
Collection<MediaSeriesGroup> seriesList = this.getChildren(study);
for (Iterator<MediaSeriesGroup> it = seriesList.iterator(); it.hasNext();) {
Object item = it.next();
if (item instanceof Series) {
((Series) item).dispose();
}
}
}
}
}
}
@Override
public String toString() {
return NAME;
}
@Override
public List<TreeModelNode> getModelStructure() {
return modelStrucure;
}
@Override
public void addPropertyChangeListener(PropertyChangeListener propertychangelistener) {
if (propertyChange == null) {
propertyChange = new PropertyChangeSupport(this);
}
propertyChange.addPropertyChangeListener(propertychangelistener);
}
@Override
public void removePropertyChangeListener(PropertyChangeListener propertychangelistener) {
if (propertyChange != null) {
propertyChange.removePropertyChangeListener(propertychangelistener);
}
}
@Override
public void firePropertyChange(final ObservableEvent event) {
if (propertyChange != null) {
if (event == null)
throw new NullPointerException();
if (SwingUtilities.isEventDispatchThread()) {
propertyChange.firePropertyChange(event);
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
propertyChange.firePropertyChange(event);
}
});
}
}
}
public void mergeSeries(List<MediaSeries> seriesList) {
if (seriesList != null && seriesList.size() > 1) {
String uid = (String) seriesList.get(0).getTagValue(TagW.SeriesInstanceUID);
boolean sameOrigin = true;
if (uid != null) {
for (int i = 1; i < seriesList.size(); i++) {
if (!uid.equals(seriesList.get(i).getTagValue(TagW.SeriesInstanceUID))) {
sameOrigin = false;
break;
}
}
}
if (sameOrigin) {
int min = Integer.MAX_VALUE;
MediaSeries base = seriesList.get(0);
for (MediaSeries series : seriesList) {
Integer splitNb = (Integer) series.getTagValue(TagW.SplitSeriesNumber);
if (splitNb != null && min > splitNb) {
min = splitNb;
base = series;
}
}
for (MediaSeries series : seriesList) {
if (series != base) {
base.addAll(series.getMedias());
removeSeries(series);
}
}
base.sort(SortSeriesStack.instanceNumber);
// update observer
this.firePropertyChange(new ObservableEvent(ObservableEvent.BasicAction.Replace, DicomModel.this, base,
base));
}
}
}
public void removeSeries(MediaSeriesGroup dicomSeries) {
if (dicomSeries != null) {
if (LoadRemoteDicomManifest.currentTasks.size() > 0) {
if (dicomSeries instanceof DicomSeries) {
LoadRemoteDicomManifest.stopDownloading((DicomSeries) dicomSeries);
}
}
// remove first series in UI (Dicom Explorer, Viewer using this series)
firePropertyChange(new ObservableEvent(ObservableEvent.BasicAction.Remove, DicomModel.this, null,
dicomSeries));
// remove in the data model
MediaSeriesGroup studyGroup = getParent(dicomSeries, DicomModel.study);
removeHierarchyNode(studyGroup, dicomSeries);
LOGGER.info("Remove Series: {}", dicomSeries); //$NON-NLS-1$
dicomSeries.dispose();
}
}
public void removeStudy(MediaSeriesGroup studyGroup) {
if (studyGroup != null) {
if (LoadRemoteDicomManifest.currentTasks.size() > 0) {
Collection<MediaSeriesGroup> seriesList = getChildren(studyGroup);
for (Iterator<MediaSeriesGroup> it = seriesList.iterator(); it.hasNext();) {
MediaSeriesGroup group = it.next();
if (group instanceof DicomSeries) {
LoadRemoteDicomManifest.stopDownloading((DicomSeries) group);
}
}
}
firePropertyChange(new ObservableEvent(ObservableEvent.BasicAction.Remove, DicomModel.this, null,
studyGroup));
MediaSeriesGroup patientGroup = getParent(studyGroup, DicomModel.patient);
removeHierarchyNode(patientGroup, studyGroup);
LOGGER.info("Remove Study: {}", studyGroup); //$NON-NLS-1$
}
}
public void removePatient(MediaSeriesGroup patientGroup) {
if (patientGroup != null) {
if (LoadRemoteDicomManifest.currentTasks.size() > 0) {
Collection<MediaSeriesGroup> studyList = getChildren(patientGroup);
for (Iterator<MediaSeriesGroup> it = studyList.iterator(); it.hasNext();) {
MediaSeriesGroup studyGroup = it.next();
Collection<MediaSeriesGroup> seriesList = getChildren(studyGroup);
for (Iterator<MediaSeriesGroup> it2 = seriesList.iterator(); it2.hasNext();) {
MediaSeriesGroup group = it2.next();
if (group instanceof DicomSeries) {
LoadRemoteDicomManifest.stopDownloading((DicomSeries) group);
}
}
}
}
firePropertyChange(new ObservableEvent(ObservableEvent.BasicAction.Remove, DicomModel.this, null,
patientGroup));
removeHierarchyNode(rootNode, patientGroup);
LOGGER.info("Remove Patient: {}", patientGroup); //$NON-NLS-1$
}
}
public static boolean isSpecialModality(Series series) {
String modality = series == null ? null : (String) series.getTagValue(TagW.Modality);
return (modality != null && ("PR".equals(modality) || "KO".equals(modality) || "SR".equals(modality))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
private void splitSeries(DicomMediaIO dicomReader, Series original, MediaElement media) {
MediaSeriesGroup study = getParent(original, DicomModel.study);
String seriesUID = (String) original.getTagValue(TagW.SeriesInstanceUID);
int k = 1;
while (true) {
String uid = "#" + k + "." + seriesUID; //$NON-NLS-1$ //$NON-NLS-2$
MediaSeriesGroup group = getHierarchyNode(study, uid);
if (group == null) {
break;
}
k++;
}
String uid = "#" + k + "." + seriesUID; //$NON-NLS-1$ //$NON-NLS-2$
Series s = dicomReader.buildSeries(uid);
dicomReader.writeMetaData(s);
Object val = original.getTagValue(TagW.SplitSeriesNumber);
if (val == null) {
original.setTag(TagW.SplitSeriesNumber, 1);
}
s.setTag(TagW.SplitSeriesNumber, k + 1);
s.setTag(TagW.ExplorerModel, this);
addHierarchyNode(study, s);
s.addMedia(media);
LOGGER.info("Series splitting: {}", s); //$NON-NLS-1$
}
private void replaceSeries(DicomMediaIO dicomReader, Series original, MediaElement media) {
MediaSeriesGroup study = getParent(original, DicomModel.study);
String seriesUID = (String) original.getTagValue(TagW.SeriesInstanceUID);
int k = 1;
while (true) {
String uid = "#" + k + "." + seriesUID; //$NON-NLS-1$ //$NON-NLS-2$
MediaSeriesGroup group = getHierarchyNode(study, uid);
if (group == null) {
break;
}
k++;
}
String uid = "#" + k + "." + seriesUID; //$NON-NLS-1$ //$NON-NLS-2$
Series s = dicomReader.buildSeries(uid);
dicomReader.writeMetaData(s);
Object val = original.getTagValue(TagW.SplitSeriesNumber);
if (val == null) {
// -1 convention to exclude this Series
original.setTag(TagW.SplitSeriesNumber, -1);
}
s.setTag(TagW.SplitSeriesNumber, k);
s.setTag(TagW.ExplorerModel, this);
addHierarchyNode(study, s);
s.addMedia(media);
LOGGER.info("Replace Series: {}", s); //$NON-NLS-1$
}
private void rebuildSeries(DicomMediaIO dicomReader, MediaElement media) {
String patientPseudoUID = (String) dicomReader.getTagValue(TagW.PatientPseudoUID);
MediaSeriesGroup patient = getHierarchyNode(TreeModel.rootNode, patientPseudoUID);
if (patient == null) {
patient = new MediaSeriesGroupNode(TagW.PatientPseudoUID, patientPseudoUID, TagW.PatientName);
dicomReader.writeMetaData(patient);
addHierarchyNode(TreeModel.rootNode, patient);
LOGGER.info(Messages.getString("LoadLocalDicom.add_pat") + patient); //$NON-NLS-1$
}
String studyUID = (String) dicomReader.getTagValue(TagW.StudyInstanceUID);
MediaSeriesGroup study = getHierarchyNode(patient, studyUID);
if (study == null) {
study = new MediaSeriesGroupNode(TagW.StudyInstanceUID, studyUID, TagW.StudyDate);
dicomReader.writeMetaData(study);
addHierarchyNode(patient, study);
}
String seriesUID = (String) dicomReader.getTagValue(TagW.SeriesInstanceUID);
Series dicomSeries = (Series) getHierarchyNode(study, seriesUID);
if (dicomSeries == null) {
dicomSeries = dicomReader.buildSeries(seriesUID);
dicomReader.writeMetaData(dicomSeries);
dicomSeries.setTag(TagW.ExplorerModel, this);
addHierarchyNode(study, dicomSeries);
LOGGER.info("Series rebuilding: {}", dicomSeries); //$NON-NLS-1$
}
dicomSeries.addMedia(media);
// Load image and create thumbnail in this Thread
Thumbnail t = (Thumbnail) dicomSeries.getTagValue(TagW.Thumbnail);
if (t == null) {
t = DicomExplorer.createThumbnail(dicomSeries, this, Thumbnail.DEFAULT_SIZE);
dicomSeries.setTag(TagW.Thumbnail, t);
}
firePropertyChange(new ObservableEvent(ObservableEvent.BasicAction.Add, this, null, dicomSeries));
}
@Override
public boolean applySplittingRules(Series original, MediaElement media) {
if (media != null && media.getMediaReader() instanceof DicomMediaIO) {
DicomMediaIO dicomReader = (DicomMediaIO) media.getMediaReader();
String seriesUID = (String) original.getTagValue(TagW.SeriesInstanceUID);
if (!seriesUID.equals(dicomReader.getTagValue(TagW.SeriesInstanceUID))) {
rebuildSeries(dicomReader, media);
return true;
}
if (original instanceof DicomSeries) {
// Handle cases when the Series is created before getting the image (downloading)
if (media instanceof DicomVideoElement || media instanceof DicomEncapDocElement) {
replaceSeries(dicomReader, original, media);
return true;
}
DicomSeries initialSeries = (DicomSeries) original;
int frames = dicomReader.getMediaElementNumber();
if (frames < 1) {
initialSeries.addMedia(media);
} else {
Modality modality = Modality.getModality((String) initialSeries.getTagValue(TagW.Modality));
TagW[] rules = frames > 1 ? multiframeSplittingRules : splittingRules.get(modality);
if (rules == null) {
rules = splittingRules.get(Modality.Default);
}
if (isSimilar(rules, initialSeries, media)) {
initialSeries.addMedia(media);
return false;
}
MediaSeriesGroup study = getParent(initialSeries, DicomModel.study);
int k = 1;
while (true) {
String uid = "#" + k + "." + seriesUID; //$NON-NLS-1$ //$NON-NLS-2$
MediaSeriesGroup group = getHierarchyNode(study, uid);
if (group instanceof DicomSeries) {
if (isSimilar(rules, (DicomSeries) group, media)) {
((DicomSeries) group).addMedia(media);
return false;
}
} else {
break;
}
k++;
}
splitSeries(dicomReader, initialSeries, media);
return true;
}
} else if (original instanceof DicomVideoSeries || original instanceof DicomEncapDocSeries) {
if (original.getMedias().size() > 0) {
splitSeries(dicomReader, original, media);
return true;
} else {
original.addMedia(media);
}
}
}
return false;
}
private boolean isSimilar(TagW[] rules, DicomSeries series, final MediaElement media) {
final DicomImageElement firstMedia = series.getMedia(0);
if (firstMedia == null)
// no image
return true;
for (TagW tagElement : rules) {
Object tag = media.getTagValue(tagElement);
Object tag2 = firstMedia.getTagValue(tagElement);
// special case if both are null
if (tag == null && tag2 == null) {
continue;
}
if (tag != null && !tag.equals(tag2))
return false;
}
return true;
}
public void get(String[] argv) throws IOException {
final String[] usage = { "Load DICOM files remotely or locally", "Usage: dicom:get [Options] SOURCE", //$NON-NLS-1$ //$NON-NLS-2$
" -l --local Open DICOMs from local disk", //$NON-NLS-1$
" -r --remote Open DICOMs from an URL", //$NON-NLS-1$
" -p --portable Open DICOMs from default directories at the same level of the executable", //$NON-NLS-1$
" -i --iwado Open DICOMs from an XML (GZIP, Base64) file containing UIDs", //$NON-NLS-1$
" -w --wado Open DICOMs from an XML (URL) file containing UIDs", " -? --help show help" }; //$NON-NLS-1$ //$NON-NLS-2$
final Option opt = Options.compile(usage).parse(argv);
final List<String> args = opt.args();
if (opt.isSet("help") || (args.isEmpty() && !opt.isSet("portable"))) { //$NON-NLS-1$ //$NON-NLS-2$
opt.usage();
return;
}
GuiExecutor.instance().execute(new Runnable() {
@Override
public void run() {
firePropertyChange(new ObservableEvent(ObservableEvent.BasicAction.Select, DicomModel.this, null,
DicomModel.this));
// start importing local dicom series list
if (opt.isSet("local")) { //$NON-NLS-1$
File[] files = new File[args.size()];
for (int i = 0; i < files.length; i++) {
files[i] = new File(args.get(i));
}
loadingExecutor.execute(new LoadLocalDicom(files, true, DicomModel.this, false));
} else if (opt.isSet("remote")) { //$NON-NLS-1$
loadingExecutor.execute(new LoadRemoteDicomURL(args.toArray(new String[args.size()]),
DicomModel.this));
}
// build WADO series list to download
else if (opt.isSet("wado")) { //$NON-NLS-1$
loadingExecutor.execute(new LoadRemoteDicomManifest(args.toArray(new String[args.size()]),
DicomModel.this));
} else if (opt.isSet("iwado")) { //$NON-NLS-1$
String[] xmlRef = args.toArray(new String[args.size()]);
File[] xmlFiles = new File[args.size()];
for (int i = 0; i < xmlFiles.length; i++) {
try {
File tempFile = File.createTempFile("wado_", ".xml", AbstractProperties.APP_TEMP_DIR); //$NON-NLS-1$ //$NON-NLS-2$
if (FileUtil.writeFile(new ByteArrayInputStream(Base64.decode(xmlRef[i])),
new FileOutputStream(tempFile)) == -1) {
xmlFiles[i] = tempFile;
}
} catch (Exception e) {
e.printStackTrace();
}
}
loadingExecutor.execute(new LoadRemoteDicomManifest(xmlFiles, DicomModel.this));
}
// Get DICOM folder (by default DICOM, dicom, IHE_PDI, ihe_pdi) at the same level at the Weasis
// executable file
else if (opt.isSet("portable")) { //$NON-NLS-1$
String prop = System.getProperty("weasis.portable.dicom.directory"); //$NON-NLS-1$
String baseDir = System.getProperty("weasis.portable.dir"); //$NON-NLS-1$
if (prop != null && baseDir != null) {
String[] dirs = prop.split(","); //$NON-NLS-1$
+ for (int i = 0; i < dirs.length; i++) {
+ dirs[i] = dirs[i].trim().replaceAll("/", File.separator);
+ }
File[] files = new File[dirs.length];
boolean notCaseSensitive = AbstractProperties.OPERATING_SYSTEM.startsWith("win");//$NON-NLS-1$
if (notCaseSensitive) {
- Arrays.sort(files);
+ Arrays.sort(dirs, String.CASE_INSENSITIVE_ORDER);
}
String last = null;
for (int i = 0; i < files.length; i++) {
- String dir = dirs[i].trim().replaceAll("/", File.separator);
- if (notCaseSensitive && last != null && dir.equalsIgnoreCase(last)) {
+ if (notCaseSensitive && last != null && dirs[i].equalsIgnoreCase(last)) {
last = null;
} else {
- last = dir;
- files[i] = new File(baseDir, dir); //$NON-NLS-1$
+ last = dirs[i];
+ files[i] = new File(baseDir, dirs[i]);
}
}
loadingExecutor.execute(new LoadLocalDicom(files, true, DicomModel.this, true));
}
}
}
});
}
public void close(String[] argv) throws IOException {
final String[] usage = { "Remove DICOM files in Dicom Explorer", //$NON-NLS-1$
"Usage: dicom:close [patient | study | series] [ARGS]", //$NON-NLS-1$
" -p --patient <args> Close patient, [arg] is patientUID (PatientID + Patient Birth Date, by default)", //$NON-NLS-1$
" -y --study <args> Close study, [arg] is Study Instance UID", //$NON-NLS-1$
" -s --series <args> Close series, [arg] is Series Instance UID", " -? --help show help" }; //$NON-NLS-1$ //$NON-NLS-2$
final Option opt = Options.compile(usage).parse(argv);
final List<String> args = opt.args();
if (opt.isSet("help") || args.isEmpty()) { //$NON-NLS-1$
opt.usage();
return;
}
GuiExecutor.instance().execute(new Runnable() {
@Override
public void run() {
firePropertyChange(new ObservableEvent(ObservableEvent.BasicAction.Select, DicomModel.this, null,
DicomModel.this));
// start build local dicom series list
if (opt.isSet("patient")) { //$NON-NLS-1$
for (String patientUID : args) {
MediaSeriesGroup patientGroup = null;
// In Weasis, Global Identity of the patient is composed of the patientID and the birth date by
// default
// TODO handle preferences choice for patientUID
patientGroup = getHierarchyNode(TreeModel.rootNode, patientUID);
if (patientGroup == null) {
System.out.println("Cannot find patient: " + patientUID); //$NON-NLS-1$
continue;
} else {
removePatient(patientGroup);
}
}
} else if (opt.isSet("study")) { //$NON-NLS-1$
for (String studyUID : args) {
for (MediaSeriesGroup ptGroup : model.getSuccessors(rootNode)) {
MediaSeriesGroup stGroup = getHierarchyNode(ptGroup, studyUID);
if (stGroup != null) {
removeStudy(stGroup);
break;
}
}
}
} else if (opt.isSet("series")) { //$NON-NLS-1$
for (String seriesUID : args) {
patientLevel: for (MediaSeriesGroup ptGroup : model.getSuccessors(rootNode)) {
for (MediaSeriesGroup stGroup : model.getSuccessors(ptGroup)) {
MediaSeriesGroup series = getHierarchyNode(stGroup, seriesUID);
if (series instanceof Series) {
removeSeries(series);
break patientLevel;
}
}
}
}
}
}
});
}
@Override
public TreeModelNode getTreeModelNodeForNewPlugin() {
return patient;
}
}
| false | true | public void get(String[] argv) throws IOException {
final String[] usage = { "Load DICOM files remotely or locally", "Usage: dicom:get [Options] SOURCE", //$NON-NLS-1$ //$NON-NLS-2$
" -l --local Open DICOMs from local disk", //$NON-NLS-1$
" -r --remote Open DICOMs from an URL", //$NON-NLS-1$
" -p --portable Open DICOMs from default directories at the same level of the executable", //$NON-NLS-1$
" -i --iwado Open DICOMs from an XML (GZIP, Base64) file containing UIDs", //$NON-NLS-1$
" -w --wado Open DICOMs from an XML (URL) file containing UIDs", " -? --help show help" }; //$NON-NLS-1$ //$NON-NLS-2$
final Option opt = Options.compile(usage).parse(argv);
final List<String> args = opt.args();
if (opt.isSet("help") || (args.isEmpty() && !opt.isSet("portable"))) { //$NON-NLS-1$ //$NON-NLS-2$
opt.usage();
return;
}
GuiExecutor.instance().execute(new Runnable() {
@Override
public void run() {
firePropertyChange(new ObservableEvent(ObservableEvent.BasicAction.Select, DicomModel.this, null,
DicomModel.this));
// start importing local dicom series list
if (opt.isSet("local")) { //$NON-NLS-1$
File[] files = new File[args.size()];
for (int i = 0; i < files.length; i++) {
files[i] = new File(args.get(i));
}
loadingExecutor.execute(new LoadLocalDicom(files, true, DicomModel.this, false));
} else if (opt.isSet("remote")) { //$NON-NLS-1$
loadingExecutor.execute(new LoadRemoteDicomURL(args.toArray(new String[args.size()]),
DicomModel.this));
}
// build WADO series list to download
else if (opt.isSet("wado")) { //$NON-NLS-1$
loadingExecutor.execute(new LoadRemoteDicomManifest(args.toArray(new String[args.size()]),
DicomModel.this));
} else if (opt.isSet("iwado")) { //$NON-NLS-1$
String[] xmlRef = args.toArray(new String[args.size()]);
File[] xmlFiles = new File[args.size()];
for (int i = 0; i < xmlFiles.length; i++) {
try {
File tempFile = File.createTempFile("wado_", ".xml", AbstractProperties.APP_TEMP_DIR); //$NON-NLS-1$ //$NON-NLS-2$
if (FileUtil.writeFile(new ByteArrayInputStream(Base64.decode(xmlRef[i])),
new FileOutputStream(tempFile)) == -1) {
xmlFiles[i] = tempFile;
}
} catch (Exception e) {
e.printStackTrace();
}
}
loadingExecutor.execute(new LoadRemoteDicomManifest(xmlFiles, DicomModel.this));
}
// Get DICOM folder (by default DICOM, dicom, IHE_PDI, ihe_pdi) at the same level at the Weasis
// executable file
else if (opt.isSet("portable")) { //$NON-NLS-1$
String prop = System.getProperty("weasis.portable.dicom.directory"); //$NON-NLS-1$
String baseDir = System.getProperty("weasis.portable.dir"); //$NON-NLS-1$
if (prop != null && baseDir != null) {
String[] dirs = prop.split(","); //$NON-NLS-1$
File[] files = new File[dirs.length];
boolean notCaseSensitive = AbstractProperties.OPERATING_SYSTEM.startsWith("win");//$NON-NLS-1$
if (notCaseSensitive) {
Arrays.sort(files);
}
String last = null;
for (int i = 0; i < files.length; i++) {
String dir = dirs[i].trim().replaceAll("/", File.separator);
if (notCaseSensitive && last != null && dir.equalsIgnoreCase(last)) {
last = null;
} else {
last = dir;
files[i] = new File(baseDir, dir); //$NON-NLS-1$
}
}
loadingExecutor.execute(new LoadLocalDicom(files, true, DicomModel.this, true));
}
}
}
});
}
| public void get(String[] argv) throws IOException {
final String[] usage = { "Load DICOM files remotely or locally", "Usage: dicom:get [Options] SOURCE", //$NON-NLS-1$ //$NON-NLS-2$
" -l --local Open DICOMs from local disk", //$NON-NLS-1$
" -r --remote Open DICOMs from an URL", //$NON-NLS-1$
" -p --portable Open DICOMs from default directories at the same level of the executable", //$NON-NLS-1$
" -i --iwado Open DICOMs from an XML (GZIP, Base64) file containing UIDs", //$NON-NLS-1$
" -w --wado Open DICOMs from an XML (URL) file containing UIDs", " -? --help show help" }; //$NON-NLS-1$ //$NON-NLS-2$
final Option opt = Options.compile(usage).parse(argv);
final List<String> args = opt.args();
if (opt.isSet("help") || (args.isEmpty() && !opt.isSet("portable"))) { //$NON-NLS-1$ //$NON-NLS-2$
opt.usage();
return;
}
GuiExecutor.instance().execute(new Runnable() {
@Override
public void run() {
firePropertyChange(new ObservableEvent(ObservableEvent.BasicAction.Select, DicomModel.this, null,
DicomModel.this));
// start importing local dicom series list
if (opt.isSet("local")) { //$NON-NLS-1$
File[] files = new File[args.size()];
for (int i = 0; i < files.length; i++) {
files[i] = new File(args.get(i));
}
loadingExecutor.execute(new LoadLocalDicom(files, true, DicomModel.this, false));
} else if (opt.isSet("remote")) { //$NON-NLS-1$
loadingExecutor.execute(new LoadRemoteDicomURL(args.toArray(new String[args.size()]),
DicomModel.this));
}
// build WADO series list to download
else if (opt.isSet("wado")) { //$NON-NLS-1$
loadingExecutor.execute(new LoadRemoteDicomManifest(args.toArray(new String[args.size()]),
DicomModel.this));
} else if (opt.isSet("iwado")) { //$NON-NLS-1$
String[] xmlRef = args.toArray(new String[args.size()]);
File[] xmlFiles = new File[args.size()];
for (int i = 0; i < xmlFiles.length; i++) {
try {
File tempFile = File.createTempFile("wado_", ".xml", AbstractProperties.APP_TEMP_DIR); //$NON-NLS-1$ //$NON-NLS-2$
if (FileUtil.writeFile(new ByteArrayInputStream(Base64.decode(xmlRef[i])),
new FileOutputStream(tempFile)) == -1) {
xmlFiles[i] = tempFile;
}
} catch (Exception e) {
e.printStackTrace();
}
}
loadingExecutor.execute(new LoadRemoteDicomManifest(xmlFiles, DicomModel.this));
}
// Get DICOM folder (by default DICOM, dicom, IHE_PDI, ihe_pdi) at the same level at the Weasis
// executable file
else if (opt.isSet("portable")) { //$NON-NLS-1$
String prop = System.getProperty("weasis.portable.dicom.directory"); //$NON-NLS-1$
String baseDir = System.getProperty("weasis.portable.dir"); //$NON-NLS-1$
if (prop != null && baseDir != null) {
String[] dirs = prop.split(","); //$NON-NLS-1$
for (int i = 0; i < dirs.length; i++) {
dirs[i] = dirs[i].trim().replaceAll("/", File.separator);
}
File[] files = new File[dirs.length];
boolean notCaseSensitive = AbstractProperties.OPERATING_SYSTEM.startsWith("win");//$NON-NLS-1$
if (notCaseSensitive) {
Arrays.sort(dirs, String.CASE_INSENSITIVE_ORDER);
}
String last = null;
for (int i = 0; i < files.length; i++) {
if (notCaseSensitive && last != null && dirs[i].equalsIgnoreCase(last)) {
last = null;
} else {
last = dirs[i];
files[i] = new File(baseDir, dirs[i]);
}
}
loadingExecutor.execute(new LoadLocalDicom(files, true, DicomModel.this, true));
}
}
}
});
}
|
diff --git a/clc/modules/www/test-gwt/src/com/eucalyptus/webui/server/EucaServiceWrapper.java b/clc/modules/www/test-gwt/src/com/eucalyptus/webui/server/EucaServiceWrapper.java
index c94d939..b76f64a 100644
--- a/clc/modules/www/test-gwt/src/com/eucalyptus/webui/server/EucaServiceWrapper.java
+++ b/clc/modules/www/test-gwt/src/com/eucalyptus/webui/server/EucaServiceWrapper.java
@@ -1,218 +1,219 @@
package com.eucalyptus.webui.server;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.amazonaws.services.ec2.model.Address;
import com.eucalyptus.webui.client.service.SearchResultRow;
import com.eucalyptus.webui.client.session.Session;
import com.eucalyptus.webui.client.service.EucalyptusServiceException;
import com.eucalyptus.webui.server.db.DBProcWrapper;
import com.eucalyptus.webui.server.stat.HistoryDBProcWrapper;
import com.eucalyptus.webui.shared.dictionary.DBTableColName;
import com.eucalyptus.webui.shared.dictionary.DBTableName;
import com.eucalyptus.webui.shared.resource.device.IPServiceInfo;
import com.eucalyptus.webui.shared.resource.device.TemplateInfo;
import com.eucalyptus.webui.shared.resource.device.status.IPState;
import com.eucalyptus.webui.shared.resource.device.status.IPType;
public class EucaServiceWrapper {
static private EucaServiceWrapper instance = null;
private static final Logger LOG = Logger.getLogger(EucaServiceWrapper.class);
private AwsServiceImpl aws = null;
private HistoryDBProcWrapper history = null;
private EucaServiceWrapper() {
aws = new AwsServiceImpl();
history = new HistoryDBProcWrapper();
}
static public EucaServiceWrapper getInstance() {
if (instance == null)
instance = new EucaServiceWrapper();
return instance;
}
/**
* run a new virtual machine with eucalyptus
* @param session
* @param template Template.class
* @param image DB vm_image_type euca_vit_id
* @param keypair string
* @param group string
* @return euca id of vm
*/
public String runVM(Session session, int userID, TemplateInfo template, String keypair, String group, String image) throws EucalyptusServiceException {
//real code about template won't be in old repo
return aws.runInstance(session, userID, image, keypair, "c1.xlarge", group);
}
public void terminateVM(Session session, int userID, String instanceID) throws EucalyptusServiceException {
List<String> ids = new ArrayList<String>();
ids.add(instanceID);
aws.terminateInstances(session, userID, ids);
}
/**
* get all keypairs' name owned by user
* @param session
* @return
*/
public List<String> getKeypairs(Session session, int userID) throws EucalyptusServiceException {
List<SearchResultRow> data = aws.lookupKeypair(session, userID);
List<String> ret = new ArrayList<String>();
for (SearchResultRow d: data) {
ret.add(d.getField(0));
}
return ret;
}
/**
* get all security groups' name can be used by user
* @param session
* @return
*/
public List<String> getSecurityGroups(Session session, int userID) throws EucalyptusServiceException {
List<SearchResultRow> data = aws.lookupSecurityGroup(session, userID);
List<String> ret = new ArrayList<String>();
for (SearchResultRow d: data) {
ret.add(d.getField(0));
}
return ret;
}
public List<String> getAvailabilityZones(Session session) throws EucalyptusServiceException {
//TODO: unused filter
return aws.lookupAvailablityZones(session);
}
public void bindServerWithZone(int serverID, String zone) {
StringBuilder sb = new StringBuilder();
sb.append("UPDATE ").append(DBTableName.SERVER)
.append(" SET ").append(DBTableColName.SERVER.EUCA_ZONE)
.append(" = '").append(zone).append("' WHERE ")
.append(DBTableColName.SERVER.ID)
.append(" = '").append(serverID).append("'");
try {
DBProcWrapper.Instance().update(sb.toString());
} catch (SQLException e) {
//TODO
}
}
public int getServerID(Session session, int userID, String instanceID) throws EucalyptusServiceException {
LOG.error("in getServerID: i-id = " + instanceID);
String zone = aws.lookupZoneWithInstanceId(session, userID, instanceID);
LOG.error("in getServerID: zone = " + zone);
StringBuilder sb = new StringBuilder();
sb.append("SELECT ").append(DBTableColName.SERVER.ID)
.append(" FROM ").append(DBTableName.SERVER)
.append(" WHERE ").append(DBTableColName.SERVER.EUCA_ZONE)
.append(" = '").append(zone).append("'");
try {
ResultSet r = DBProcWrapper.Instance().query(sb.toString()).getResultSet();
if (r.first()) {
return r.getInt(DBTableColName.SERVER.ID);
}
} catch (SQLException e) {
LOG.error("sql error in getServerID: " + e.toString());
}
return -1;
}
public String getServerIp(int userID, String instanceID) throws EucalyptusServiceException {
return aws.lookupInstanceForIp(userID, instanceID);
}
public List<IPServiceInfo> getIPServices(int accountID, int userID) throws EucalyptusServiceException {
List<Integer> ids = new ArrayList<Integer>();
if (userID > 0) {
ids.add(userID);
} else {
StringBuilder sb = new StringBuilder();
sb.append("SELECT ").append(DBTableColName.USER.ID).append(" FROM ")
.append(DBTableName.USER);
if (accountID > 0) {
sb.append(" WHERE ").append(DBTableColName.USER.ACCOUNT_ID).append(" = '")
.append(accountID).append("'");
}
try {
ResultSet r = DBProcWrapper.Instance().query(sb.toString()).getResultSet();
while (r.next()) {
ids.add(r.getInt(DBTableColName.USER.ID));
}
} catch (Exception e) {
throw new EucalyptusServiceException("db error");
}
}
LOG.debug("ip service: user ids = " + ids.toString());
List<IPServiceInfo> ret = new ArrayList<IPServiceInfo>();
List<Address> addrs = aws.lookupPublicAddress(ids.get(0));
for (Address a : addrs) {
String id = a.getInstanceId();
+ int _userID = aws.getUserID(id);
if (id.startsWith("nobody") ||
false) {
//!ids.contains(aws.getUserID(id))) {
continue;
}
IPServiceInfo e = new IPServiceInfo();
e.ip_addr = a.getPublicIp();
if (id.startsWith("available")) {
e.is_state = IPState.RESERVED;
} else {
e.is_state = IPState.INUSE;
IPServiceInfo _e = new IPServiceInfo();
String _id = id.substring(0, id.indexOf(' '));
e.ip_id = getIPID(_id, IPType.PUBLIC);
- String _ip = getServerIp(userID, _id);
+ String _ip = getServerIp(_userID, _id);
_e.is_state = IPState.INUSE;
_e.ip_type = IPType.PRIVATE;
_e.ip_addr = _ip;
_e.ip_id = getIPID(_id, IPType.PRIVATE);
ret.add(_e);
}
e.ip_type = IPType.PUBLIC;
ret.add(e);
}
return ret;
}
public int getIPID(String instanceID, IPType t) throws EucalyptusServiceException{
StringBuilder sb = new StringBuilder();
sb.append("SELECT ");
String col = null;
if (t == IPType.PRIVATE)
col = DBTableColName.USER_APP.PRI_IP_SRV_ID;
else
col = DBTableColName.USER_APP.PUB_IP_SRV_ID;
sb.append(col);
sb.append(" FROM ").append(DBTableName.USER_APP)
.append(" WHERE ").append(DBTableColName.USER_APP.EUCA_VI_KEY).append(" = '")
.append(instanceID).append("'");
try {
ResultSet r = DBProcWrapper.Instance().query(sb.toString()).getResultSet();
if (r.first())
return r.getInt(col);
} catch (Exception e) {
throw new EucalyptusServiceException("db error");
}
return 0;
}
public List<String> allocateAddress(int userID, IPType type, int count) throws EucalyptusServiceException {
return aws.allocateAddress(userID, type, count);
}
public void releaseAddress(int userID, IPType type, String addr) throws EucalyptusServiceException {
aws.releaseAddress(userID, type, addr);
}
}
| false | true | public List<IPServiceInfo> getIPServices(int accountID, int userID) throws EucalyptusServiceException {
List<Integer> ids = new ArrayList<Integer>();
if (userID > 0) {
ids.add(userID);
} else {
StringBuilder sb = new StringBuilder();
sb.append("SELECT ").append(DBTableColName.USER.ID).append(" FROM ")
.append(DBTableName.USER);
if (accountID > 0) {
sb.append(" WHERE ").append(DBTableColName.USER.ACCOUNT_ID).append(" = '")
.append(accountID).append("'");
}
try {
ResultSet r = DBProcWrapper.Instance().query(sb.toString()).getResultSet();
while (r.next()) {
ids.add(r.getInt(DBTableColName.USER.ID));
}
} catch (Exception e) {
throw new EucalyptusServiceException("db error");
}
}
LOG.debug("ip service: user ids = " + ids.toString());
List<IPServiceInfo> ret = new ArrayList<IPServiceInfo>();
List<Address> addrs = aws.lookupPublicAddress(ids.get(0));
for (Address a : addrs) {
String id = a.getInstanceId();
if (id.startsWith("nobody") ||
false) {
//!ids.contains(aws.getUserID(id))) {
continue;
}
IPServiceInfo e = new IPServiceInfo();
e.ip_addr = a.getPublicIp();
if (id.startsWith("available")) {
e.is_state = IPState.RESERVED;
} else {
e.is_state = IPState.INUSE;
IPServiceInfo _e = new IPServiceInfo();
String _id = id.substring(0, id.indexOf(' '));
e.ip_id = getIPID(_id, IPType.PUBLIC);
String _ip = getServerIp(userID, _id);
_e.is_state = IPState.INUSE;
_e.ip_type = IPType.PRIVATE;
_e.ip_addr = _ip;
_e.ip_id = getIPID(_id, IPType.PRIVATE);
ret.add(_e);
}
e.ip_type = IPType.PUBLIC;
ret.add(e);
}
return ret;
}
| public List<IPServiceInfo> getIPServices(int accountID, int userID) throws EucalyptusServiceException {
List<Integer> ids = new ArrayList<Integer>();
if (userID > 0) {
ids.add(userID);
} else {
StringBuilder sb = new StringBuilder();
sb.append("SELECT ").append(DBTableColName.USER.ID).append(" FROM ")
.append(DBTableName.USER);
if (accountID > 0) {
sb.append(" WHERE ").append(DBTableColName.USER.ACCOUNT_ID).append(" = '")
.append(accountID).append("'");
}
try {
ResultSet r = DBProcWrapper.Instance().query(sb.toString()).getResultSet();
while (r.next()) {
ids.add(r.getInt(DBTableColName.USER.ID));
}
} catch (Exception e) {
throw new EucalyptusServiceException("db error");
}
}
LOG.debug("ip service: user ids = " + ids.toString());
List<IPServiceInfo> ret = new ArrayList<IPServiceInfo>();
List<Address> addrs = aws.lookupPublicAddress(ids.get(0));
for (Address a : addrs) {
String id = a.getInstanceId();
int _userID = aws.getUserID(id);
if (id.startsWith("nobody") ||
false) {
//!ids.contains(aws.getUserID(id))) {
continue;
}
IPServiceInfo e = new IPServiceInfo();
e.ip_addr = a.getPublicIp();
if (id.startsWith("available")) {
e.is_state = IPState.RESERVED;
} else {
e.is_state = IPState.INUSE;
IPServiceInfo _e = new IPServiceInfo();
String _id = id.substring(0, id.indexOf(' '));
e.ip_id = getIPID(_id, IPType.PUBLIC);
String _ip = getServerIp(_userID, _id);
_e.is_state = IPState.INUSE;
_e.ip_type = IPType.PRIVATE;
_e.ip_addr = _ip;
_e.ip_id = getIPID(_id, IPType.PRIVATE);
ret.add(_e);
}
e.ip_type = IPType.PUBLIC;
ret.add(e);
}
return ret;
}
|
diff --git a/src/com/android/gallery3d/filtershow/imageshow/ImageDraw.java b/src/com/android/gallery3d/filtershow/imageshow/ImageDraw.java
index 6c3417ad3..8fcc028af 100644
--- a/src/com/android/gallery3d/filtershow/imageshow/ImageDraw.java
+++ b/src/com/android/gallery3d/filtershow/imageshow/ImageDraw.java
@@ -1,150 +1,150 @@
package com.android.gallery3d.filtershow.imageshow;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import com.android.gallery3d.filtershow.editors.EditorDraw;
import com.android.gallery3d.filtershow.filters.FilterDrawRepresentation;
import com.android.gallery3d.filtershow.filters.ImageFilterDraw;
public class ImageDraw extends ImageShow {
private static final String LOGTAG = "ImageDraw";
private int mCurrentColor = Color.RED;
final static float INITAL_STROKE_RADIUS = 40;
private float mCurrentSize = INITAL_STROKE_RADIUS;
private byte mType = 0;
private FilterDrawRepresentation mFRep;
private EditorDraw mEditorDraw;
public ImageDraw(Context context, AttributeSet attrs) {
super(context, attrs);
resetParameter();
super.setOriginalDisabled(true);
}
public ImageDraw(Context context) {
super(context);
resetParameter();
super.setOriginalDisabled(true);
}
public void setEditor(EditorDraw editorDraw) {
mEditorDraw = editorDraw;
}
public void setFilterDrawRepresentation(FilterDrawRepresentation fr) {
mFRep = fr;
}
public Drawable getIcon(Context context) {
return null;
}
@Override
public void resetParameter() {
if (mFRep != null) {
mFRep.clear();
}
}
public void setColor(int color) {
mCurrentColor = color;
}
public void setSize(int size) {
mCurrentSize = size;
}
public void setStyle(byte style) {
mType = (byte) (style % ImageFilterDraw.NUMBER_OF_STYLES);
}
public int getStyle() {
return mType;
}
public int getSize() {
return (int) mCurrentSize;
}
@Override
public void updateImage() {
super.updateImage();
invalidate();
}
float[] mTmpPoint = new float[2]; // so we do not malloc
@Override
public boolean onTouchEvent(MotionEvent event) {
- boolean ret = super.onTouchEvent(event);
if (event.getPointerCount() > 1) {
+ boolean ret = super.onTouchEvent(event);
if (mFRep.getCurrentDrawing() != null) {
mFRep.clearCurrentSection();
mEditorDraw.commitLocalRepresentation();
}
return ret;
}
if (event.getAction() != MotionEvent.ACTION_DOWN) {
if (mFRep.getCurrentDrawing() == null) {
- return ret;
+ return super.onTouchEvent(event);
}
}
ImageFilterDraw filter = (ImageFilterDraw) getCurrentFilter();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
calcScreenMapping();
mTmpPoint[0] = event.getX();
mTmpPoint[1] = event.getY();
mToOrig.mapPoints(mTmpPoint);
mFRep.startNewSection(mType, mCurrentColor, mCurrentSize, mTmpPoint[0], mTmpPoint[1]);
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
int historySize = event.getHistorySize();
final int pointerCount = event.getPointerCount();
for (int h = 0; h < historySize; h++) {
int p = 0;
{
mTmpPoint[0] = event.getHistoricalX(p, h);
mTmpPoint[1] = event.getHistoricalY(p, h);
mToOrig.mapPoints(mTmpPoint);
mFRep.addPoint(mTmpPoint[0], mTmpPoint[1]);
}
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
mTmpPoint[0] = event.getX();
mTmpPoint[1] = event.getY();
mToOrig.mapPoints(mTmpPoint);
mFRep.endSection(mTmpPoint[0], mTmpPoint[1]);
}
mEditorDraw.commitLocalRepresentation();
invalidate();
return true;
}
Matrix mRotateToScreen = new Matrix();
Matrix mToOrig;
private void calcScreenMapping() {
mToOrig = getScreenToImageMatrix(true);
mToOrig.invert(mRotateToScreen);
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
calcScreenMapping();
}
}
| false | true | public boolean onTouchEvent(MotionEvent event) {
boolean ret = super.onTouchEvent(event);
if (event.getPointerCount() > 1) {
if (mFRep.getCurrentDrawing() != null) {
mFRep.clearCurrentSection();
mEditorDraw.commitLocalRepresentation();
}
return ret;
}
if (event.getAction() != MotionEvent.ACTION_DOWN) {
if (mFRep.getCurrentDrawing() == null) {
return ret;
}
}
ImageFilterDraw filter = (ImageFilterDraw) getCurrentFilter();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
calcScreenMapping();
mTmpPoint[0] = event.getX();
mTmpPoint[1] = event.getY();
mToOrig.mapPoints(mTmpPoint);
mFRep.startNewSection(mType, mCurrentColor, mCurrentSize, mTmpPoint[0], mTmpPoint[1]);
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
int historySize = event.getHistorySize();
final int pointerCount = event.getPointerCount();
for (int h = 0; h < historySize; h++) {
int p = 0;
{
mTmpPoint[0] = event.getHistoricalX(p, h);
mTmpPoint[1] = event.getHistoricalY(p, h);
mToOrig.mapPoints(mTmpPoint);
mFRep.addPoint(mTmpPoint[0], mTmpPoint[1]);
}
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
mTmpPoint[0] = event.getX();
mTmpPoint[1] = event.getY();
mToOrig.mapPoints(mTmpPoint);
mFRep.endSection(mTmpPoint[0], mTmpPoint[1]);
}
mEditorDraw.commitLocalRepresentation();
invalidate();
return true;
}
| public boolean onTouchEvent(MotionEvent event) {
if (event.getPointerCount() > 1) {
boolean ret = super.onTouchEvent(event);
if (mFRep.getCurrentDrawing() != null) {
mFRep.clearCurrentSection();
mEditorDraw.commitLocalRepresentation();
}
return ret;
}
if (event.getAction() != MotionEvent.ACTION_DOWN) {
if (mFRep.getCurrentDrawing() == null) {
return super.onTouchEvent(event);
}
}
ImageFilterDraw filter = (ImageFilterDraw) getCurrentFilter();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
calcScreenMapping();
mTmpPoint[0] = event.getX();
mTmpPoint[1] = event.getY();
mToOrig.mapPoints(mTmpPoint);
mFRep.startNewSection(mType, mCurrentColor, mCurrentSize, mTmpPoint[0], mTmpPoint[1]);
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
int historySize = event.getHistorySize();
final int pointerCount = event.getPointerCount();
for (int h = 0; h < historySize; h++) {
int p = 0;
{
mTmpPoint[0] = event.getHistoricalX(p, h);
mTmpPoint[1] = event.getHistoricalY(p, h);
mToOrig.mapPoints(mTmpPoint);
mFRep.addPoint(mTmpPoint[0], mTmpPoint[1]);
}
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
mTmpPoint[0] = event.getX();
mTmpPoint[1] = event.getY();
mToOrig.mapPoints(mTmpPoint);
mFRep.endSection(mTmpPoint[0], mTmpPoint[1]);
}
mEditorDraw.commitLocalRepresentation();
invalidate();
return true;
}
|
diff --git a/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/DefaultCommandModule.java b/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/DefaultCommandModule.java
index e0ef9881f..a04ba159c 100644
--- a/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/DefaultCommandModule.java
+++ b/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/DefaultCommandModule.java
@@ -1,60 +1,60 @@
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.sshd.commands;
import com.google.gerrit.sshd.CommandModule;
import com.google.gerrit.sshd.CommandName;
import com.google.gerrit.sshd.Commands;
import com.google.gerrit.sshd.DispatchCommandProvider;
import com.google.gerrit.sshd.SuExec;
/** Register the basic commands any Gerrit server should support. */
public class DefaultCommandModule extends CommandModule {
@Override
protected void configure() {
final CommandName git = Commands.named("git");
final CommandName gerrit = Commands.named("gerrit");
// The following commands can be ran on a server in either Master or Slave
// mode. If a command should only be used on a server in one mode, but not
// both, it should be bound in both MasterCommandModule and
// SlaveCommandModule.
command(gerrit).toProvider(new DispatchCommandProvider(gerrit));
command(gerrit, "flush-caches").to(AdminFlushCaches.class);
command(gerrit, "ls-projects").to(ListProjects.class);
command(gerrit, "show-caches").to(AdminShowCaches.class);
command(gerrit, "show-connections").to(AdminShowConnections.class);
command(gerrit, "show-queue").to(ShowQueue.class);
command(gerrit, "stream-events").to(StreamEvents.class);
command(git).toProvider(new DispatchCommandProvider(git));
command(git, "receive-pack").to(Commands.key(gerrit, "receive-pack"));
command(git, "upload-pack").to(Upload.class);
- command("ps").to(AdminShowCaches.class);
+ command("ps").to(ShowQueue.class);
command("kill").to(AdminKill.class);
command("scp").to(ScpCommand.class);
// Honor the legacy hyphenated forms as aliases for the non-hyphenated forms
//
command("git-upload-pack").to(Commands.key(git, "upload-pack"));
command("git-receive-pack").to(Commands.key(git, "receive-pack"));
command("gerrit-receive-pack").to(Commands.key(git, "receive-pack"));
command("suexec").to(SuExec.class);
}
}
| true | true | protected void configure() {
final CommandName git = Commands.named("git");
final CommandName gerrit = Commands.named("gerrit");
// The following commands can be ran on a server in either Master or Slave
// mode. If a command should only be used on a server in one mode, but not
// both, it should be bound in both MasterCommandModule and
// SlaveCommandModule.
command(gerrit).toProvider(new DispatchCommandProvider(gerrit));
command(gerrit, "flush-caches").to(AdminFlushCaches.class);
command(gerrit, "ls-projects").to(ListProjects.class);
command(gerrit, "show-caches").to(AdminShowCaches.class);
command(gerrit, "show-connections").to(AdminShowConnections.class);
command(gerrit, "show-queue").to(ShowQueue.class);
command(gerrit, "stream-events").to(StreamEvents.class);
command(git).toProvider(new DispatchCommandProvider(git));
command(git, "receive-pack").to(Commands.key(gerrit, "receive-pack"));
command(git, "upload-pack").to(Upload.class);
command("ps").to(AdminShowCaches.class);
command("kill").to(AdminKill.class);
command("scp").to(ScpCommand.class);
// Honor the legacy hyphenated forms as aliases for the non-hyphenated forms
//
command("git-upload-pack").to(Commands.key(git, "upload-pack"));
command("git-receive-pack").to(Commands.key(git, "receive-pack"));
command("gerrit-receive-pack").to(Commands.key(git, "receive-pack"));
command("suexec").to(SuExec.class);
}
| protected void configure() {
final CommandName git = Commands.named("git");
final CommandName gerrit = Commands.named("gerrit");
// The following commands can be ran on a server in either Master or Slave
// mode. If a command should only be used on a server in one mode, but not
// both, it should be bound in both MasterCommandModule and
// SlaveCommandModule.
command(gerrit).toProvider(new DispatchCommandProvider(gerrit));
command(gerrit, "flush-caches").to(AdminFlushCaches.class);
command(gerrit, "ls-projects").to(ListProjects.class);
command(gerrit, "show-caches").to(AdminShowCaches.class);
command(gerrit, "show-connections").to(AdminShowConnections.class);
command(gerrit, "show-queue").to(ShowQueue.class);
command(gerrit, "stream-events").to(StreamEvents.class);
command(git).toProvider(new DispatchCommandProvider(git));
command(git, "receive-pack").to(Commands.key(gerrit, "receive-pack"));
command(git, "upload-pack").to(Upload.class);
command("ps").to(ShowQueue.class);
command("kill").to(AdminKill.class);
command("scp").to(ScpCommand.class);
// Honor the legacy hyphenated forms as aliases for the non-hyphenated forms
//
command("git-upload-pack").to(Commands.key(git, "upload-pack"));
command("git-receive-pack").to(Commands.key(git, "receive-pack"));
command("gerrit-receive-pack").to(Commands.key(git, "receive-pack"));
command("suexec").to(SuExec.class);
}
|
diff --git a/src/freemail/utils/PropsFile.java b/src/freemail/utils/PropsFile.java
index 0e756ad..240875e 100644
--- a/src/freemail/utils/PropsFile.java
+++ b/src/freemail/utils/PropsFile.java
@@ -1,227 +1,228 @@
/*
* PropsFile.java
* This file is part of Freemail
* Copyright (C) 2006,2008 Dave Baker
* Copyright (C) 2008 Alexander Lehmann
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package freemail.utils;
import java.io.File;
import java.io.FileReader;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Hashtable;
public class PropsFile {
// substitute static methods for constructor
private static final Hashtable<String, PropsFile> propsList=new Hashtable<String, PropsFile>();
private static int reapCounter = 0;
/// We go through the list and remove stale entries once in this many times a PropsFile is created
private static final int reapEvery = 20;
public static synchronized PropsFile createPropsFile(File f, boolean stopAtBlank) {
if (reapCounter == reapEvery) {
reapOld();
reapCounter = 0;
} else {
++reapCounter;
}
String fn=f.getPath();
PropsFile pf=propsList.get(fn);
if(pf!=null) {
return pf;
} else {
pf=new PropsFile(f, stopAtBlank);
propsList.put(fn, pf);
return pf;
}
}
public static PropsFile createPropsFile(File f) {
return createPropsFile(f, false);
}
public static void reapOld() {
Logger.debug(PropsFile.class, "Cleaning up stale PropsFiles");
Iterator<Map.Entry<String, PropsFile>> i = propsList.entrySet().iterator();
while (i.hasNext()) {
Map.Entry<String, PropsFile> entry = i.next();
File f = new File(entry.getKey());
if (!f.exists()) {
Logger.debug(PropsFile.class, "Removing "+f.getPath());
i.remove();
}
}
}
private final File file;
private HashMap<String, String> data;
private BufferedReader bufrdr;
private String commentPrefix;
private String header;
/** Pass true into stopAtBlank to cause the reader to stop upon encountering
* a blank line. It's the the caller's responsibility to get
* (using the getReader() method) the stream and close it properly.
*/
private PropsFile(File f, boolean stopAtBlank) {
this.file = f;
this.data = null;
if (f.exists()) {
try {
this.bufrdr = this.read(stopAtBlank);
} catch (IOException ioe) {
}
}
this.commentPrefix = null;
this.header = null;
}
public void setCommentPrefix(String cp) {
this.commentPrefix = cp;
}
public void setHeader(String hdr) {
this.header = hdr;
}
private synchronized BufferedReader read(boolean stopAtBlank) throws IOException {
this.data = new HashMap<String, String>();
BufferedReader br = new BufferedReader(new FileReader(this.file));
String line = null;
while ( (line = br.readLine()) != null) {
if (this.commentPrefix != null && line.startsWith(this.commentPrefix)) {
continue;
}
if (stopAtBlank && line.length() == 0) {
return br;
}
String[] parts = line.split("=", 2);
if (parts.length < 2) continue;
this.data.put(parts[0], parts[1]);
}
br.close();
return null;
}
public BufferedReader getReader() {
return this.bufrdr;
}
public void closeReader() {
if (this.bufrdr == null) return;
try {
this.bufrdr.close();
} catch (IOException ioe) {
}
}
private synchronized void write() throws IOException {
- if(!file.getParentFile().exists()) {
- if(!file.getParentFile().mkdirs()) {
+ File parentDir = file.getParentFile();
+ if(parentDir != null && !parentDir.exists()) {
+ if(!parentDir.mkdirs()) {
Logger.error(this, "Couldn't create parent directory of " + file);
throw new IOException("Couldn't create parent directory of " + file);
}
}
PrintWriter pw = new PrintWriter(new FileOutputStream(this.file));
if (this.header != null) pw.println(this.header);
Iterator<Map.Entry<String, String>> i = this.data.entrySet().iterator();
while (i.hasNext()) {
Map.Entry<String, String> e = i.next();
String key = e.getKey();
String val = e.getValue();
pw.println(key+"="+val);
}
pw.close();
}
public String get(String key) {
if (this.data == null) return null;
return this.data.get(key);
}
public boolean put(String key, String val) {
if (this.data == null) {
this.data = new HashMap<String, String>();
}
Object o = this.data.put(key, val);
if (o == null || !o.equals(val)) {
try {
this.write();
} catch (IOException ioe) {
ioe.printStackTrace();
return false;
}
}
return true;
}
public boolean put(String key, long val) {
return this.put(key, Long.toString(val));
}
public boolean exists() {
return this.file.exists();
}
public Set<String> listProps() {
return this.data.keySet();
}
public boolean remove(String key) {
if (this.data.containsKey(key)) {
this.data.remove(key);
try {
this.write();
} catch (IOException ioe) {
ioe.printStackTrace();
return false;
}
}
return true;
}
@Override
public String toString() {
return file.getPath();
}
}
| true | true | private synchronized void write() throws IOException {
if(!file.getParentFile().exists()) {
if(!file.getParentFile().mkdirs()) {
Logger.error(this, "Couldn't create parent directory of " + file);
throw new IOException("Couldn't create parent directory of " + file);
}
}
PrintWriter pw = new PrintWriter(new FileOutputStream(this.file));
if (this.header != null) pw.println(this.header);
Iterator<Map.Entry<String, String>> i = this.data.entrySet().iterator();
while (i.hasNext()) {
Map.Entry<String, String> e = i.next();
String key = e.getKey();
String val = e.getValue();
pw.println(key+"="+val);
}
pw.close();
}
| private synchronized void write() throws IOException {
File parentDir = file.getParentFile();
if(parentDir != null && !parentDir.exists()) {
if(!parentDir.mkdirs()) {
Logger.error(this, "Couldn't create parent directory of " + file);
throw new IOException("Couldn't create parent directory of " + file);
}
}
PrintWriter pw = new PrintWriter(new FileOutputStream(this.file));
if (this.header != null) pw.println(this.header);
Iterator<Map.Entry<String, String>> i = this.data.entrySet().iterator();
while (i.hasNext()) {
Map.Entry<String, String> e = i.next();
String key = e.getKey();
String val = e.getValue();
pw.println(key+"="+val);
}
pw.close();
}
|
diff --git a/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java b/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java
index bb7960b19..9446882c2 100644
--- a/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java
+++ b/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java
@@ -1,237 +1,238 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.optimization.linear;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.math3.exception.MaxCountExceededException;
import org.apache.commons.math3.optimization.PointValuePair;
import org.apache.commons.math3.util.Precision;
/**
* Solves a linear problem using the Two-Phase Simplex Method.
* @version $Id$
* @since 2.0
*/
public class SimplexSolver extends AbstractLinearOptimizer {
/** Default amount of error to accept for algorithm convergence. */
private static final double DEFAULT_EPSILON = 1.0e-6;
/** Default amount of error to accept in floating point comparisons (as ulps). */
private static final int DEFAULT_ULPS = 10;
/** Amount of error to accept for algorithm convergence. */
private final double epsilon;
/** Amount of error to accept in floating point comparisons (as ulps). */
private final int maxUlps;
/**
* Build a simplex solver with default settings.
*/
public SimplexSolver() {
this(DEFAULT_EPSILON, DEFAULT_ULPS);
}
/**
* Build a simplex solver with a specified accepted amount of error
* @param epsilon the amount of error to accept for algorithm convergence
* @param maxUlps amount of error to accept in floating point comparisons
*/
public SimplexSolver(final double epsilon, final int maxUlps) {
this.epsilon = epsilon;
this.maxUlps = maxUlps;
}
/**
* Returns the column with the most negative coefficient in the objective function row.
* @param tableau simple tableau for the problem
* @return column with the most negative coefficient
*/
private Integer getPivotColumn(SimplexTableau tableau) {
double minValue = 0;
Integer minPos = null;
for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1; i++) {
final double entry = tableau.getEntry(0, i);
// check if the entry is strictly smaller than the current minimum
// do not use a ulp/epsilon check
if (entry < minValue) {
minValue = entry;
minPos = i;
}
}
return minPos;
}
/**
* Returns the row with the minimum ratio as given by the minimum ratio test (MRT).
* @param tableau simple tableau for the problem
* @param col the column to test the ratio of. See {@link #getPivotColumn(SimplexTableau)}
* @return row with the minimum ratio
*/
private Integer getPivotRow(SimplexTableau tableau, final int col) {
// create a list of all the rows that tie for the lowest score in the minimum ratio test
List<Integer> minRatioPositions = new ArrayList<Integer>();
double minRatio = Double.MAX_VALUE;
for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
final double entry = tableau.getEntry(i, col);
if (Precision.compareTo(entry, 0d, maxUlps) > 0) {
final double ratio = rhs / entry;
// check if the entry is strictly equal to the current min ratio
// do not use a ulp/epsilon check
final int cmp = Double.compare(ratio, minRatio);
if (cmp == 0) {
minRatioPositions.add(i);
} else if (cmp < 0) {
minRatio = ratio;
minRatioPositions = new ArrayList<Integer>();
minRatioPositions.add(i);
}
}
}
if (minRatioPositions.size() == 0) {
return null;
} else if (minRatioPositions.size() > 1) {
// there's a degeneracy as indicated by a tie in the minimum ratio test
// 1. check if there's an artificial variable that can be forced out of the basis
if (tableau.getNumArtificialVariables() > 0) {
for (Integer row : minRatioPositions) {
for (int i = 0; i < tableau.getNumArtificialVariables(); i++) {
int column = i + tableau.getArtificialVariableOffset();
final double entry = tableau.getEntry(row, column);
if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) {
return row;
}
}
}
}
// 2. apply Bland's rule to prevent cycling:
// take the row for which the corresponding basic variable has the smallest index
//
// see http://www.stanford.edu/class/msande310/blandrule.pdf
// see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper)
//
// Additional heuristic: if we did not get a solution after half of maxIterations
// revert to the simple case of just returning the top-most row
// This heuristic is based on empirical data gathered while investigating MATH-828.
if (getIterations() < getMaxIterations() / 2) {
Integer minRow = null;
int minIndex = tableau.getWidth();
+ final int varStart = tableau.getNumObjectiveFunctions();
+ final int varEnd = tableau.getWidth() - 1;
for (Integer row : minRatioPositions) {
- int i = tableau.getNumObjectiveFunctions();
- for (; i < tableau.getWidth() - 1 && !row.equals(minRow); i++) {
- Integer basicRow = tableau.getBasicRow(i);
+ for (int i = varStart; i < varEnd && !row.equals(minRow); i++) {
+ final Integer basicRow = tableau.getBasicRow(i);
if (basicRow != null && basicRow.equals(row)) {
if (i < minIndex) {
minIndex = i;
minRow = row;
}
}
}
}
return minRow;
}
}
return minRatioPositions.get(0);
}
/**
* Runs one iteration of the Simplex method on the given model.
* @param tableau simple tableau for the problem
* @throws MaxCountExceededException if the maximal iteration count has been exceeded
* @throws UnboundedSolutionException if the model is found not to have a bounded solution
*/
protected void doIteration(final SimplexTableau tableau)
throws MaxCountExceededException, UnboundedSolutionException {
incrementIterationsCounter();
Integer pivotCol = getPivotColumn(tableau);
Integer pivotRow = getPivotRow(tableau, pivotCol);
if (pivotRow == null) {
throw new UnboundedSolutionException();
}
// set the pivot element to 1
double pivotVal = tableau.getEntry(pivotRow, pivotCol);
tableau.divideRow(pivotRow, pivotVal);
// set the rest of the pivot column to 0
for (int i = 0; i < tableau.getHeight(); i++) {
if (i != pivotRow) {
final double multiplier = tableau.getEntry(i, pivotCol);
tableau.subtractRow(i, pivotRow, multiplier);
}
}
}
/**
* Solves Phase 1 of the Simplex method.
* @param tableau simple tableau for the problem
* @throws MaxCountExceededException if the maximal iteration count has been exceeded
* @throws UnboundedSolutionException if the model is found not to have a bounded solution
* @throws NoFeasibleSolutionException if there is no feasible solution
*/
protected void solvePhase1(final SimplexTableau tableau)
throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException {
// make sure we're in Phase 1
if (tableau.getNumArtificialVariables() == 0) {
return;
}
while (!tableau.isOptimal()) {
doIteration(tableau);
}
// if W is not zero then we have no feasible solution
if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
throw new NoFeasibleSolutionException();
}
}
/** {@inheritDoc} */
@Override
public PointValuePair doOptimize()
throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException {
final SimplexTableau tableau =
new SimplexTableau(getFunction(),
getConstraints(),
getGoalType(),
restrictToNonNegative(),
epsilon,
maxUlps);
solvePhase1(tableau);
tableau.dropPhase1Objective();
while (!tableau.isOptimal()) {
doIteration(tableau);
}
return tableau.getSolution();
}
}
| false | true | private Integer getPivotRow(SimplexTableau tableau, final int col) {
// create a list of all the rows that tie for the lowest score in the minimum ratio test
List<Integer> minRatioPositions = new ArrayList<Integer>();
double minRatio = Double.MAX_VALUE;
for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
final double entry = tableau.getEntry(i, col);
if (Precision.compareTo(entry, 0d, maxUlps) > 0) {
final double ratio = rhs / entry;
// check if the entry is strictly equal to the current min ratio
// do not use a ulp/epsilon check
final int cmp = Double.compare(ratio, minRatio);
if (cmp == 0) {
minRatioPositions.add(i);
} else if (cmp < 0) {
minRatio = ratio;
minRatioPositions = new ArrayList<Integer>();
minRatioPositions.add(i);
}
}
}
if (minRatioPositions.size() == 0) {
return null;
} else if (minRatioPositions.size() > 1) {
// there's a degeneracy as indicated by a tie in the minimum ratio test
// 1. check if there's an artificial variable that can be forced out of the basis
if (tableau.getNumArtificialVariables() > 0) {
for (Integer row : minRatioPositions) {
for (int i = 0; i < tableau.getNumArtificialVariables(); i++) {
int column = i + tableau.getArtificialVariableOffset();
final double entry = tableau.getEntry(row, column);
if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) {
return row;
}
}
}
}
// 2. apply Bland's rule to prevent cycling:
// take the row for which the corresponding basic variable has the smallest index
//
// see http://www.stanford.edu/class/msande310/blandrule.pdf
// see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper)
//
// Additional heuristic: if we did not get a solution after half of maxIterations
// revert to the simple case of just returning the top-most row
// This heuristic is based on empirical data gathered while investigating MATH-828.
if (getIterations() < getMaxIterations() / 2) {
Integer minRow = null;
int minIndex = tableau.getWidth();
for (Integer row : minRatioPositions) {
int i = tableau.getNumObjectiveFunctions();
for (; i < tableau.getWidth() - 1 && !row.equals(minRow); i++) {
Integer basicRow = tableau.getBasicRow(i);
if (basicRow != null && basicRow.equals(row)) {
if (i < minIndex) {
minIndex = i;
minRow = row;
}
}
}
}
return minRow;
}
}
return minRatioPositions.get(0);
}
| private Integer getPivotRow(SimplexTableau tableau, final int col) {
// create a list of all the rows that tie for the lowest score in the minimum ratio test
List<Integer> minRatioPositions = new ArrayList<Integer>();
double minRatio = Double.MAX_VALUE;
for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
final double entry = tableau.getEntry(i, col);
if (Precision.compareTo(entry, 0d, maxUlps) > 0) {
final double ratio = rhs / entry;
// check if the entry is strictly equal to the current min ratio
// do not use a ulp/epsilon check
final int cmp = Double.compare(ratio, minRatio);
if (cmp == 0) {
minRatioPositions.add(i);
} else if (cmp < 0) {
minRatio = ratio;
minRatioPositions = new ArrayList<Integer>();
minRatioPositions.add(i);
}
}
}
if (minRatioPositions.size() == 0) {
return null;
} else if (minRatioPositions.size() > 1) {
// there's a degeneracy as indicated by a tie in the minimum ratio test
// 1. check if there's an artificial variable that can be forced out of the basis
if (tableau.getNumArtificialVariables() > 0) {
for (Integer row : minRatioPositions) {
for (int i = 0; i < tableau.getNumArtificialVariables(); i++) {
int column = i + tableau.getArtificialVariableOffset();
final double entry = tableau.getEntry(row, column);
if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) {
return row;
}
}
}
}
// 2. apply Bland's rule to prevent cycling:
// take the row for which the corresponding basic variable has the smallest index
//
// see http://www.stanford.edu/class/msande310/blandrule.pdf
// see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper)
//
// Additional heuristic: if we did not get a solution after half of maxIterations
// revert to the simple case of just returning the top-most row
// This heuristic is based on empirical data gathered while investigating MATH-828.
if (getIterations() < getMaxIterations() / 2) {
Integer minRow = null;
int minIndex = tableau.getWidth();
final int varStart = tableau.getNumObjectiveFunctions();
final int varEnd = tableau.getWidth() - 1;
for (Integer row : minRatioPositions) {
for (int i = varStart; i < varEnd && !row.equals(minRow); i++) {
final Integer basicRow = tableau.getBasicRow(i);
if (basicRow != null && basicRow.equals(row)) {
if (i < minIndex) {
minIndex = i;
minRow = row;
}
}
}
}
return minRow;
}
}
return minRatioPositions.get(0);
}
|
diff --git a/src/model/ConcreteProductContainerManager.java b/src/model/ConcreteProductContainerManager.java
index d165e6a..5cc6c35 100644
--- a/src/model/ConcreteProductContainerManager.java
+++ b/src/model/ConcreteProductContainerManager.java
@@ -1,171 +1,171 @@
package model;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;
import java.util.Observable;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import model.Action.ActionType;
@SuppressWarnings("serial")
public class ConcreteProductContainerManager extends Observable implements Serializable,
ProductContainerManager {
private final Set<StorageUnit> rootStorageUnits;
private final Map<String, StorageUnit> nameToStorageUnit;
/**
* Constructor
*
*/
public ConcreteProductContainerManager() {
rootStorageUnits = new TreeSet<StorageUnit>();
nameToStorageUnit = new TreeMap<String, StorageUnit>();
}
@Override
public void editProductGroup(ProductContainer parent, String oldName, String newName,
ProductQuantity newTMS) {
ProductGroup pg = parent.editProductGroup(oldName, newName, newTMS);
setChanged();
Action a = new Action(pg, ActionType.EDIT);
this.notifyObservers(a);
}
@Override
public StorageUnit getRootStorageUnitByName(String productGroupName) {
for (StorageUnit su : rootStorageUnits) {
if (su.getName().equals(productGroupName)
|| su.containsProductGroup(productGroupName))
return su;
}
return null;
}
@Override
public StorageUnit getRootStorageUnitForChild(ProductContainer child) {
for (StorageUnit su : rootStorageUnits) {
if (su.equals(child) || su.hasDescendantProductContainer(child))
return su;
}
return null;
}
/**
* Gets the StorageUnit with the given name.
*
* @return The StorageUnit with the given name, or null, if not found
*
* @pre true
* @post true
*/
@Override
public StorageUnit getStorageUnitByName(String name) {
return nameToStorageUnit.get(name);
}
@Override
public Iterator<StorageUnit> getStorageUnitIterator() {
return rootStorageUnits.iterator();
}
/**
* Determines whether the specified Storage Unit name is valid for adding a new Storage
* Unit.
*
* @param name
* The name to be tested
* @return true if name is valid, false otherwise
*
* @pre true
* @post true
*/
@Override
public boolean isValidStorageUnitName(String name) {
if (name == null || name.equals(""))
return false;
// From the Data Dictionary: Must be non-empty. Must be unique among all
// Storage Units.
for (StorageUnit su : rootStorageUnits) {
if (name.equals(su.getName().toString()))
return false;
}
return true;
}
/**
* If pc is a StorageUnit, it is added to the list of StorageUnits managed. Notifies
* observers of a change.
*
* @param pc
* ProductContainer to be managed
*
* @pre pc != null
* @post if(pc instanceof StorageUnit) getByName(pc.getName()) == pc
*/
@Override
public void manage(ProductContainer pc) {
if (pc instanceof StorageUnit) {
StorageUnit storageUnit = (StorageUnit) pc;
rootStorageUnits.add(storageUnit);
nameToStorageUnit.put(storageUnit.getName(), storageUnit);
}
setChanged();
Action a = new Action(pc, ActionType.CREATE);
this.notifyObservers(a);
}
/**
*
* @param name
* @param su
*/
@Override
public void setStorageUnitName(String name, StorageUnit su) {
if (name.equals(su.getName()))
return;
if (!isValidStorageUnitName(name))
throw new IllegalArgumentException("Illegal storage unit name");
rootStorageUnits.remove(su);
nameToStorageUnit.remove(su.getName());
su.setName(name);
rootStorageUnits.add(su);
nameToStorageUnit.put(name, su);
setChanged();
Action a = new Action(su, ActionType.EDIT);
this.notifyObservers(a);
}
/**
* Remove pc from set of managed objects and notify observers of a change.
*
* @param pc
* ProductContainer to be unmanaged
*
* @pre true
* @post getByName(pc.getName()) == null
*/
@Override
public void unmanage(ProductContainer pc) {
if (pc instanceof StorageUnit) {
StorageUnit storageUnit = (StorageUnit) pc;
rootStorageUnits.remove(storageUnit);
nameToStorageUnit.remove(storageUnit.getName());
} else {
ProductGroup pg = (ProductGroup) pc;
for (StorageUnit su : rootStorageUnits) {
- if (su.containsProductGroup(pg.getName())) {
+ if (su.containsProductGroup(pg) || su.hasDescendantProductContainer(pg)) {
su.remove(pg);
}
}
}
setChanged();
Action a = new Action(pc, ActionType.DELETE);
this.notifyObservers(a);
}
}
| true | true | public void unmanage(ProductContainer pc) {
if (pc instanceof StorageUnit) {
StorageUnit storageUnit = (StorageUnit) pc;
rootStorageUnits.remove(storageUnit);
nameToStorageUnit.remove(storageUnit.getName());
} else {
ProductGroup pg = (ProductGroup) pc;
for (StorageUnit su : rootStorageUnits) {
if (su.containsProductGroup(pg.getName())) {
su.remove(pg);
}
}
}
setChanged();
Action a = new Action(pc, ActionType.DELETE);
this.notifyObservers(a);
}
| public void unmanage(ProductContainer pc) {
if (pc instanceof StorageUnit) {
StorageUnit storageUnit = (StorageUnit) pc;
rootStorageUnits.remove(storageUnit);
nameToStorageUnit.remove(storageUnit.getName());
} else {
ProductGroup pg = (ProductGroup) pc;
for (StorageUnit su : rootStorageUnits) {
if (su.containsProductGroup(pg) || su.hasDescendantProductContainer(pg)) {
su.remove(pg);
}
}
}
setChanged();
Action a = new Action(pc, ActionType.DELETE);
this.notifyObservers(a);
}
|
diff --git a/src/main/java/com/authdb/util/Config.java b/src/main/java/com/authdb/util/Config.java
index 695ce39..ccfd62e 100644
--- a/src/main/java/com/authdb/util/Config.java
+++ b/src/main/java/com/authdb/util/Config.java
@@ -1,352 +1,352 @@
/**
(C) Copyright 2011 CraftFire <[email protected]>
Contex <[email protected]>, Wulfspider <[email protected]>
This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.
To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/
or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
**/
package com.authdb.util;
import java.io.File;
import org.bukkit.util.config.Configuration;
//import com.ensifera.animosity.craftirc.CraftIRC;
public class Config {
public static boolean database_ison, authdb_enabled = true;
public static boolean has_badcharacters;
public static boolean hasForumBoard,capitalization;
public static boolean hasBackpack = false, hasBukkitContrib = false, hasSpout = false, hasBuildr = false;
public static boolean onlineMode = true;
public static boolean database_keepalive;
public static String database_type, database_username,database_password,database_port,database_host,database_database,dbDb;
public static boolean autoupdate_enable,debug_enable,usagestats_enabled,logging_enabled;
public static String language, logformat;
public static String script_name,script_version,script_salt,script_tableprefix;
public static boolean script_updatestatus;
public static String custom_table,custom_userfield,custom_passfield,custom_encryption,custom_emailfield;
public static boolean custom_enabled,custom_autocreate,custom_salt, custom_emailrequired;
public static boolean register_enabled,register_force;
public static String register_delay_length,register_delay_time,register_timeout_length,register_timeout_time,register_show_length,register_show_time;
public static int register_delay,register_timeout,register_show;
public static boolean login_enabled;
public static String login_method,login_tries,login_action,login_delay_length,login_delay_time,login_timeout_length,login_timeout_time,login_show_length,login_show_time;
public static int login_delay,login_timeout,login_show;
public static boolean link_enabled,link_rename;
public static boolean unlink_enabled,unlink_rename;
public static String username_minimum,username_maximum;
public static String password_minimum,password_maximum;
public static boolean session_protect, session_enabled;
public static String session_time,session_thelength,session_start;
public static int session_length;
public static boolean guests_commands,guests_movement,guests_inventory,guests_drop,guests_pickup,guests_health,guests_mobdamage,guests_interact,guests_build,guests_destroy,guests_chat,guests_mobtargeting,guests_pvp;
public static boolean protection_notify, protection_freeze;
public static int protection_notify_delay, protection_freeze_delay;
public static String protection_notify_delay_time, protection_notify_delay_length, protection_freeze_delay_time, protection_freeze_delay_length;
public static String filter_action,filter_username,filter_password,filter_whitelist="";
public static boolean geoip_enabled;
public static boolean CraftIRC_enabled;
public static String CraftIRC_tag,CraftIRC_prefix;
public static boolean CraftIRC_messages_enabled,CraftIRC_messages_welcome_enabled,CraftIRC_messages_register_enabled,CraftIRC_messages_unregister_enabled,CraftIRC_messages_login_enabled,CraftIRC_messages_email_enabled,CraftIRC_messages_username_enabled,CraftIRC_messages_password_enabled,CraftIRC_messages_idle_enabled;
public static String commands_register,commands_link,commands_unlink,commands_login,commands_logout,commands_setspawn,commands_reload;
public static String aliases_register,aliases_link,aliases_unlink,aliases_login,aliases_logout,aliases_setspawn,aliases_reload;
public static Configuration template = null;
public Config(String config, String directory, String filename) {
template = new Configuration(new File(directory, filename));
template.load();
if (config.equalsIgnoreCase("basic")) {
language = getConfigString("plugin.language", "English");
autoupdate_enable = getConfigBoolean("plugin.autoupdate", true);
debug_enable = getConfigBoolean("plugin.debugmode", false);
usagestats_enabled = getConfigBoolean("plugin.usagestats", true);
logformat = getConfigString("plugin.logformat", "yyyy-MM-dd");
logging_enabled = getConfigBoolean("plugin.logging", true);
database_type = getConfigString("database.type", "mysql");
database_username = getConfigString("database.username", "root");
database_password = getConfigString("database.password", "");
database_port = getConfigString("database.port", "3306");
database_host = getConfigString("database.host", "localhost");
database_database = getConfigString("database.name", "forum");
database_keepalive = getConfigBoolean("database.keepalive", false);
dbDb = "jdbc:mysql://" + database_host + ":" + database_port + "/" + database_database;
script_name = getConfigString("script.name", "phpbb").toLowerCase();
script_version = getConfigString("script.version", "3.0.8");
script_tableprefix = getConfigString("script.tableprefix", "");
script_updatestatus = getConfigBoolean("script.updatestatus", true);
script_salt = getConfigString("script.salt", "");
} else if (config.equalsIgnoreCase("advanced")) {
custom_enabled = getConfigBoolean("customdb.enabled", false);
custom_autocreate = getConfigBoolean("customdb.autocreate", true);
custom_emailrequired = getConfigBoolean("customdb.emailrequired", false);
custom_table = getConfigString("customdb.table", "authdb_users");
custom_userfield = getConfigString("customdb.userfield", "username");
custom_passfield = getConfigString("customdb.passfield", "password");
custom_emailfield = getConfigString("customdb.emailfield", "email");
custom_encryption = getConfigString("customdb.encryption", "md5").toLowerCase();
register_enabled = getConfigBoolean("register.enabled", true);
register_force = getConfigBoolean("register.force", true);
register_delay_length = Util.split(getConfigString("register.delay", "4 seconds"), " ")[0];
register_delay_time = Util.split(getConfigString("register.delay", "4 seconds"), " ")[1];
register_delay = Util.toTicks(register_delay_time,register_delay_length);
register_show_length = Util.split(getConfigString("register.show", "10 seconds"), " ")[0];
register_show_time = Util.split(getConfigString("register.show", "10 seconds"), " ")[1];
register_show = Util.toSeconds(register_show_time,register_show_length);
register_timeout_length = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[0];
register_timeout_time = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[1];
register_timeout = Util.toTicks(register_timeout_time,register_timeout_length);
login_method = getConfigString("login.method", "prompt");
login_tries = getConfigString("login.tries", "3");
login_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase());
login_delay_length = Util.split(getConfigString("login.delay", "4 seconds"), " ")[0];
login_delay_time = Util.split(getConfigString("login.delay", "4 seconds"), " ")[1];
login_delay = Util.toTicks(login_delay_time,login_delay_length);
login_show_length = Util.split(getConfigString("login.show", "10 seconds"), " ")[0];
login_show_time = Util.split(getConfigString("login.show", "10 seconds"), " ")[1];
login_show = Util.toSeconds(login_show_time,login_show_length);
login_timeout_length = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[0];
login_timeout_time = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[1];
login_timeout = Util.toTicks(login_timeout_time,login_timeout_length);
link_enabled = getConfigBoolean("link.enabled", true);
link_rename = getConfigBoolean("link.rename", true);
unlink_enabled = getConfigBoolean("unlink.enabled", true);
unlink_rename = getConfigBoolean("unlink.rename", true);
username_minimum = getConfigString("username.minimum", "3");
username_maximum = getConfigString("username.maximum", "16");
password_minimum = getConfigString("password.minimum", "6");
password_maximum = getConfigString("password.maximum", "16");
session_enabled = getConfigBoolean("session.enabled", false);
session_protect = getConfigBoolean("session.protect", true);
session_thelength = Util.split(getConfigString("session.length", "1 hour"), " ")[0];
session_time = Util.split(getConfigString("session.length", "1 hour"), " ")[1];
session_length = Util.toSeconds(session_time,session_thelength);
session_start = Util.checkSessionStart(getConfigString("session.start", "login"));
guests_commands = getConfigBoolean("guest.commands", false);
guests_movement = getConfigBoolean("guest.movement", false);
guests_inventory = getConfigBoolean("guest.inventory", false);
guests_drop = getConfigBoolean("guest.drop", false);
guests_pickup = getConfigBoolean("guest.pickup", false);
guests_health = getConfigBoolean("guest.health", false);
guests_mobdamage = getConfigBoolean("guest.mobdamage", false);
guests_interact = getConfigBoolean("guest.interactions", false);
guests_build = getConfigBoolean("guest.building", false);
guests_destroy = getConfigBoolean("guest.destruction", false);
guests_chat = getConfigBoolean("guest.chat", false);
guests_mobtargeting = getConfigBoolean("guest.mobtargeting", false);
guests_pvp = getConfigBoolean("guest.pvp", false);
- protection_freeze = getConfigBoolean("protection.freeze", true);
+ protection_freeze = getConfigBoolean("protection.freeze.enabled", true);
protection_freeze_delay_length = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[0];
protection_freeze_delay_time = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[1];
protection_freeze_delay = Util.toSeconds(protection_freeze_delay_time, protection_freeze_delay_length);
- protection_notify = getConfigBoolean("protection.notify", true);
+ protection_notify = getConfigBoolean("protection.notify.enabled", true);
protection_notify_delay_length = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[0];
protection_notify_delay_time = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[1];
protection_notify_delay = Util.toSeconds(protection_notify_delay_time, protection_notify_delay_length);
filter_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase());
filter_username = getConfigString("filter.username", "`~!@#$%^&*()-= + {[]}|\\:;\"<,>.?/");
filter_password = getConfigString("filter.password", "&");
filter_whitelist= getConfigString("filter.whitelist", "");
} else if (config.equalsIgnoreCase("plugins")) {
CraftIRC_enabled = getConfigBoolean("CraftIRC.enabled", true);
CraftIRC_tag = getConfigString("CraftIRC.tag", "admin");
CraftIRC_prefix = getConfigString("CraftIRC.prefix", "%b%%green%[{PLUGIN}]%k%%b%");
/*
CraftIRC_messages_enabled = getConfigBoolean("CraftIRC.messages.enabled", true);
CraftIRC_messages_welcome_enabled = getConfigBoolean("CraftIRC.messages.welcome", true);
CraftIRC_messages_register_enabled = getConfigBoolean("CraftIRC.messages.register", true);
CraftIRC_messages_unregister_enabled = getConfigBoolean("CraftIRC.messages.unregister", true);
CraftIRC_messages_login_enabled = getConfigBoolean("CraftIRC.messages.login", true);
CraftIRC_messages_email_enabled = getConfigBoolean("CraftIRC.messages.email", true);
CraftIRC_messages_username_enabled = getConfigBoolean("CraftIRC.messages.username", true);
CraftIRC_messages_password_enabled = getConfigBoolean("CraftIRC.messages.password", true);
CraftIRC_messages_idle_enabled = getConfigBoolean("CraftIRC.messages.idle", true);
*/
} else if (config.equalsIgnoreCase("messages")) {
Messages.time_millisecond = Config.getConfigString("Core.time.millisecond.", "millisecond");
Messages.time_milliseconds = Config.getConfigString("Core.time.milliseconds", "milliseconds");
Messages.time_second = Config.getConfigString("Core.time.second.", "second");
Messages.time_seconds = Config.getConfigString("Core.time.seconds", "seconds");
Messages.time_minute = Config.getConfigString("Core.time.minute.", "minute");
Messages.time_minutes = Config.getConfigString("Core.time.minutes", "minutes");
Messages.time_hour = Config.getConfigString("Core.time.hour.", "hour");
Messages.time_hours = Config.getConfigString("Core.time.hours", "hours");
Messages.time_day = Config.getConfigString("Core.time.day", "day");
Messages.time_days = Config.getConfigString("Core.time.days", "days");
Messages.AuthDB_message_reload_success = Config.getConfigString("Core.reload.success", "AuthDB has successfully reloaded!");
Messages.AuthDB_message_database_failure = Config.getConfigString("Core.database.failure", "{RED}database connection failed! Access is denied! Contact admin.");
Messages.AuthDB_message_register_welcome = (String)Config.getConfigString("Core.register.welcome", "{YELLOW}Welcome {WHITE}guest{YELLOW}! Please use {REGISTERCMD} password email");
Messages.AuthDB_message_register_success = Config.getConfigString("Core.register.success", "{RED}You have been registered!");
Messages.AuthDB_message_register_failure = Config.getConfigString("Core.register.failure", "{RED}Registration failed!");
Messages.AuthDB_message_register_offline = Config.getConfigString("Core.register.offline", "{RED}Database is unavailable. Unable to verify password!");
Messages.AuthDB_message_register_exists = Config.getConfigString("Core.register.exists", "{RED}You are already registered!");
Messages.AuthDB_message_register_disabled = Config.getConfigString("Core.register.disabled", "{RED}Registration not allowed!");
Messages.AuthDB_message_register_usage = Config.getConfigString("Core.register.usage", "{RED}Correct usage is: /register password email");
Messages.AuthDB_message_register_timeout = Config.getConfigString("Core.register.timeout", "Kicked because you failed to register within {REGISTERTIMEOUT}.");
Messages.AuthDB_message_unregister_success = Config.getConfigString("Core.unregister.success", "{BRIGHTGREEN}Unregistered successfully!");
Messages.AuthDB_message_unregister_failure = Config.getConfigString("Core.unregister.failure", "{RED}An error occurred while unregistering!");
Messages.AuthDB_message_unregister_usage = Config.getConfigString("Core.unregister.usage", "{RED}Correct usage is: /unregister password");
Messages.AuthDB_message_logout_success = Config.getConfigString("Core.logout.success", "Successfully logged out!");
Messages.AuthDB_message_logout_failure = Config.getConfigString("Core.logout.failure", "You are not logged in!");
Messages.AuthDB_message_logout_admin = Config.getConfigString("Core.logout.admin", "You have been logged out by an admin.");
Messages.AuthDB_message_logout_admin_success = Config.getConfigString("Core.logout.adminsuccess", "Successfully logged out player, {PLAYER}.");
Messages.AuthDB_message_logout_admin_failure = Config.getConfigString("Core.logout.adminfailure", "You cannot logout player, {PLAYER}! That player is not logged in");
Messages.AuthDB_message_logout_admin_notfound = Config.getConfigString("Core.logout.adminnotfound", "Could not find player, {PLAYER}! Please try again.");
Messages.AuthDB_message_logout_usage = Config.getConfigString("Core.logout.usage", "{YELLOW}Correct usage is: {WHITE}{LOGOUTCMD}");
Messages.AuthDB_message_login_normal = Config.getConfigString("Core.login.normal", "{YELLOW}Welcome back {WHITE}{PLAYER}{YELLOW}! Please use /login password");
Messages.AuthDB_message_login_prompt = Config.getConfigString("Core.login.prompt", "{WHITE}Welcome {TEAL}{PLAYER}{WHITE}! Please enter your password:");
Messages.AuthDB_message_login_success = Config.getConfigString("Core.login.success", "{BRIGHTGREEN}Password accepted. Welcome!");
Messages.AuthDB_message_login_failure = Config.getConfigString("Core.login.failure", "{RED}Password incorrect, please try again.");
Messages.AuthDB_message_login_offline = Config.getConfigString("Core.login.offline", "{RED}Database is unavailable. Unable to verify password!");
Messages.AuthDB_message_login_authorized = Config.getConfigString("Core.login.authorized", "{BRIGHTGREEN}You are already logged in!");
Messages.AuthDB_message_login_notregistered = Config.getConfigString("Core.login.notregistered", "{RED}You are not registred yet!");
Messages.AuthDB_message_login_timeout = Config.getConfigString("Core.login.timeout", "Kicked because you failed to login within {LOGINTIMEOUT}.");
Messages.AuthDB_message_login_admin = Config.getConfigString("Core.login.admin", "You have been logged in by an admin.");
Messages.AuthDB_message_login_admin_success = Config.getConfigString("Core.login.admin.success", "Successfully logged in player, {PLAYER}.");
Messages.AuthDB_message_login_admin_failure = Config.getConfigString("Core.login.adminfailure", "You cannot login player {PLAYER}! That player is already logged in.");
Messages.AuthDB_message_login_admin_notfound = Config.getConfigString("Core.login.adminnotfound", "Could not find player, {PLAYER}! Please try again.");
Messages.AuthDB_message_login_usage = Config.getConfigString("Core.login.usage", "{RED}Correct usage is: /login password");
Messages.AuthDB_message_link_welcome = (String)Config.getConfigString("Core.link.welcome", "or {LINKCMD} otherusername password");
Messages.AuthDB_message_link_success = Config.getConfigString("Core.link.success", "{BRIGHTGREEN}You have successfully linked!. You are now logged in");
Messages.AuthDB_message_link_failure = Config.getConfigString("Core.link.failure", "{RED}Error while linking!");
Messages.AuthDB_message_link_exists = Config.getConfigString("Core.link.exists", "{RED}You are already linked to a username!");
Messages.AuthDB_message_link_duplicate = Config.getConfigString("Core.link.duplicate", "{RED}Username is already linked to another player!");
Messages.AuthDB_message_link_registred = Config.getConfigString("Core.link.registred", "{RED}You cannot link as this username is already registered!");
Messages.AuthDB_message_link_invaliduser = Config.getConfigString("Core.link.invaliduser", "{RED}You cannot link with yourself!");
Messages.AuthDB_message_link_usage = Config.getConfigString("Core.link.usage", "{RED}Correct usage is: /link otherusername password");
Messages.AuthDB_message_unlink_success = Config.getConfigString("Core.unlink.success", "{BRIGHTGREEN}You have successfully unlinked!");
Messages.AuthDB_message_unlink_failure = Config.getConfigString("Core.unlink.failure", "{RED}Error while unlinking!");
Messages.AuthDB_message_unlink_nonexist = Config.getConfigString("Core.unlink.nonexist", "{RED}You do not have a linked username!");
Messages.AuthDB_message_unlink_invaliduser = Config.getConfigString("Core.unlink.invaliduser", "{RED}Invalid linked username!");
Messages.AuthDB_message_unlink_invalidpass = Config.getConfigString("Core.unlink.invalidpass", "{RED}Invalid linked password!");
Messages.AuthDB_message_unlink_usage = Config.getConfigString("Core.unlink.usage", "{RED}Correct usage is: /unlink otherusername password");
Messages.AuthDB_message_email_required = Config.getConfigString("Core.email.required", "{RED}Email required for registration!");
Messages.AuthDB_message_email_invalid = Config.getConfigString("Core.email.invalid", "{RED}Invalid email! Please try again!");
Messages.AuthDB_message_email_badcharacters = Config.getConfigString("Core.email.badcharacters", "{RED}Email contains bad characters! {BADCHARACTERS}!");
Messages.AuthDB_message_filter_renamed = Config.getConfigString("Core.filter.renamed", "{RED}{PLAYER} renamed to {PLAYERNEW} due to bad characters: {USERBADCHARACTERS}.");
Messages.AuthDB_message_filter_username = Config.getConfigString("Core.filter.username", "{RED}Username contains bad characters: {USERBADCHARACTERS}!");
Messages.AuthDB_message_filter_password = Config.getConfigString("Core.filter.password", "{RED}Password contains bad characters: {PASSBADCHARACTERS}!");
Messages.AuthDB_message_filter_whitelist = Config.getConfigString("Core.filter.whitelist", "{BRIGHTGREEN}{PLAYER} is on the filter {WHITE}whitelist{BRIGHTGREEN}, bypassing restrictions!");
Messages.AuthDB_message_username_minimum = Config.getConfigString("Core.username.minimum", "{RED}Your username does not meet the minimum requirement of {USERMIN} characters!");
Messages.AuthDB_message_username_maximum = Config.getConfigString("Core.username.maximum", "{RED}Your username does not meet the maximum requirement of {USERMAX} characters!");
Messages.AuthDB_message_password_minimum = Config.getConfigString("Core.password.minimum", "{RED}Your password does not meet the minimum requirement of {PASSMIN} characters!");
Messages.AuthDB_message_password_maximum = Config.getConfigString("Core.password.maximum", "{RED}Your password does not meet the maximum requirement of {PASSMAX} characters!");
Messages.AuthDB_message_password_success = Config.getConfigString("Core.password.success", "{BRIGHTGREEN}Password changed successfully!");
Messages.AuthDB_message_password_failure = Config.getConfigString("Core.password.failure", "{RED}Error! Password change failed!");
Messages.AuthDB_message_password_notregistered = Config.getConfigString("Core.password.notregistered", "{RED}Register first!");
Messages.AuthDB_message_password_usage = Config.getConfigString("Core.password.usage", "{RED}Correct usage is: /password oldpassword password");
Messages.AuthDB_message_session_valid = Config.getConfigString("Core.session.valid", "{BRIGHTGREEN}Hey, I remember you! You are logged in!");
Messages.AuthDB_message_session_protected = Config.getConfigString("Core.session.protected", "{RED}Sorry, a player with that name is already logged in on this server.");
Messages.AuthDB_message_protection_denied = Config.getConfigString("Core.protection.denied", "You do not have permission to use that command.");
Messages.AuthDB_message_protection_notauthorized = Config.getConfigString("Core.protection.notauthorized", "{RED}You are not authorized to do that!");
Messages.CraftIRC_message_status_join = Config.getConfigString("Plugins.CraftIRC.status.join", "{PLAYER} has joined the server.");
Messages.CraftIRC_message_status_quit = Config.getConfigString("Plugins.CraftIRC.status.quit", "{PLAYER} has quit the server.");
Messages.CraftIRC_message_register_success = Config.getConfigString("Plugins.CraftIRC.register.success", "{PLAYER} just registered successfully!");
Messages.CraftIRC_message_register_failure = Config.getConfigString("Plugins.CraftIRC.register.failure", "{PLAYER} had some errors while registering!");
Messages.CraftIRC_message_register_registered = Config.getConfigString("Plugins.CraftIRC.register.registered", "{PLAYER} had a lapse in memory and tried to register again.");
Messages.CraftIRC_message_password_success = Config.getConfigString("Plugins.CraftIRC.password.success", "{PLAYER} logged in successfully!");
Messages.CraftIRC_message_password_failure = Config.getConfigString("Plugins.CraftIRC.password.failure", "{PLAYER} tried to login with the wrong password!");
Messages.CraftIRC_message_idle_kicked = Config.getConfigString("Plugins.CraftIRC.idle.kicked", "{PLAYER} was kicked due to bad characters in username!");
Messages.CraftIRC_message_idle_whitelist = Config.getConfigString("Plugins.CraftIRC.idle.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!");
Messages.CraftIRC_message_filter_renamed = Config.getConfigString("Plugins.CraftIRC.filter.renamed", "{PLAYER} renamed to {PLAYERNEW} due to bad characters.");
Messages.CraftIRC_message_filter_kicked = Config.getConfigString("Plugins.CraftIRC.filter.kicked", "{PLAYER} was kicked due to bad characters in username!");
Messages.CraftIRC_message_filter_whitelist = Config.getConfigString("Plugins.CraftIRC.filter.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!");
} else if (config.equalsIgnoreCase("commands")) {
commands_register = Config.getConfigString("Core.commands.register", "/register");
commands_link = Config.getConfigString("Core.commands.link", "/link");
commands_unlink = Config.getConfigString("Core.commands.unlink", "/unlink");
commands_login = Config.getConfigString("Core.commands.login", "/login");
commands_logout = Config.getConfigString("Core.commands.logout", "/logout");
commands_setspawn = Config.getConfigString("Core.commands.setspawn", "/authdb setspawn");
commands_reload = Config.getConfigString("Core.commands.reload", "/authdb reload");
aliases_register = Config.getConfigString("Core.aliases.register", "/r");
aliases_link = Config.getConfigString("Core.aliases.link", "/li");
aliases_unlink = Config.getConfigString("Core.aliases.unlink", "/ul");
aliases_login = Config.getConfigString("Core.aliases.login", "/l");
aliases_logout = Config.getConfigString("Core.aliases.logout", "/lo");
aliases_setspawn = Config.getConfigString("Core.aliases.setspawn", "/s");
aliases_reload = Config.getConfigString("Core.aliases.reload", "/ar");
}
}
public static String getConfigString(String key, String defaultvalue) {
return template.getString(key, defaultvalue);
}
public static boolean getConfigBoolean(String key, boolean defaultvalue) {
return template.getBoolean(key, defaultvalue);
}
public void deleteConfigValue(String key) {
template.removeProperty(key);
}
public String raw(String key, String line) {
return template.getString(key, line);
}
public void save(String key, String line) {
template.setProperty(key, line);
}
}
| false | true | public Config(String config, String directory, String filename) {
template = new Configuration(new File(directory, filename));
template.load();
if (config.equalsIgnoreCase("basic")) {
language = getConfigString("plugin.language", "English");
autoupdate_enable = getConfigBoolean("plugin.autoupdate", true);
debug_enable = getConfigBoolean("plugin.debugmode", false);
usagestats_enabled = getConfigBoolean("plugin.usagestats", true);
logformat = getConfigString("plugin.logformat", "yyyy-MM-dd");
logging_enabled = getConfigBoolean("plugin.logging", true);
database_type = getConfigString("database.type", "mysql");
database_username = getConfigString("database.username", "root");
database_password = getConfigString("database.password", "");
database_port = getConfigString("database.port", "3306");
database_host = getConfigString("database.host", "localhost");
database_database = getConfigString("database.name", "forum");
database_keepalive = getConfigBoolean("database.keepalive", false);
dbDb = "jdbc:mysql://" + database_host + ":" + database_port + "/" + database_database;
script_name = getConfigString("script.name", "phpbb").toLowerCase();
script_version = getConfigString("script.version", "3.0.8");
script_tableprefix = getConfigString("script.tableprefix", "");
script_updatestatus = getConfigBoolean("script.updatestatus", true);
script_salt = getConfigString("script.salt", "");
} else if (config.equalsIgnoreCase("advanced")) {
custom_enabled = getConfigBoolean("customdb.enabled", false);
custom_autocreate = getConfigBoolean("customdb.autocreate", true);
custom_emailrequired = getConfigBoolean("customdb.emailrequired", false);
custom_table = getConfigString("customdb.table", "authdb_users");
custom_userfield = getConfigString("customdb.userfield", "username");
custom_passfield = getConfigString("customdb.passfield", "password");
custom_emailfield = getConfigString("customdb.emailfield", "email");
custom_encryption = getConfigString("customdb.encryption", "md5").toLowerCase();
register_enabled = getConfigBoolean("register.enabled", true);
register_force = getConfigBoolean("register.force", true);
register_delay_length = Util.split(getConfigString("register.delay", "4 seconds"), " ")[0];
register_delay_time = Util.split(getConfigString("register.delay", "4 seconds"), " ")[1];
register_delay = Util.toTicks(register_delay_time,register_delay_length);
register_show_length = Util.split(getConfigString("register.show", "10 seconds"), " ")[0];
register_show_time = Util.split(getConfigString("register.show", "10 seconds"), " ")[1];
register_show = Util.toSeconds(register_show_time,register_show_length);
register_timeout_length = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[0];
register_timeout_time = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[1];
register_timeout = Util.toTicks(register_timeout_time,register_timeout_length);
login_method = getConfigString("login.method", "prompt");
login_tries = getConfigString("login.tries", "3");
login_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase());
login_delay_length = Util.split(getConfigString("login.delay", "4 seconds"), " ")[0];
login_delay_time = Util.split(getConfigString("login.delay", "4 seconds"), " ")[1];
login_delay = Util.toTicks(login_delay_time,login_delay_length);
login_show_length = Util.split(getConfigString("login.show", "10 seconds"), " ")[0];
login_show_time = Util.split(getConfigString("login.show", "10 seconds"), " ")[1];
login_show = Util.toSeconds(login_show_time,login_show_length);
login_timeout_length = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[0];
login_timeout_time = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[1];
login_timeout = Util.toTicks(login_timeout_time,login_timeout_length);
link_enabled = getConfigBoolean("link.enabled", true);
link_rename = getConfigBoolean("link.rename", true);
unlink_enabled = getConfigBoolean("unlink.enabled", true);
unlink_rename = getConfigBoolean("unlink.rename", true);
username_minimum = getConfigString("username.minimum", "3");
username_maximum = getConfigString("username.maximum", "16");
password_minimum = getConfigString("password.minimum", "6");
password_maximum = getConfigString("password.maximum", "16");
session_enabled = getConfigBoolean("session.enabled", false);
session_protect = getConfigBoolean("session.protect", true);
session_thelength = Util.split(getConfigString("session.length", "1 hour"), " ")[0];
session_time = Util.split(getConfigString("session.length", "1 hour"), " ")[1];
session_length = Util.toSeconds(session_time,session_thelength);
session_start = Util.checkSessionStart(getConfigString("session.start", "login"));
guests_commands = getConfigBoolean("guest.commands", false);
guests_movement = getConfigBoolean("guest.movement", false);
guests_inventory = getConfigBoolean("guest.inventory", false);
guests_drop = getConfigBoolean("guest.drop", false);
guests_pickup = getConfigBoolean("guest.pickup", false);
guests_health = getConfigBoolean("guest.health", false);
guests_mobdamage = getConfigBoolean("guest.mobdamage", false);
guests_interact = getConfigBoolean("guest.interactions", false);
guests_build = getConfigBoolean("guest.building", false);
guests_destroy = getConfigBoolean("guest.destruction", false);
guests_chat = getConfigBoolean("guest.chat", false);
guests_mobtargeting = getConfigBoolean("guest.mobtargeting", false);
guests_pvp = getConfigBoolean("guest.pvp", false);
protection_freeze = getConfigBoolean("protection.freeze", true);
protection_freeze_delay_length = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[0];
protection_freeze_delay_time = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[1];
protection_freeze_delay = Util.toSeconds(protection_freeze_delay_time, protection_freeze_delay_length);
protection_notify = getConfigBoolean("protection.notify", true);
protection_notify_delay_length = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[0];
protection_notify_delay_time = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[1];
protection_notify_delay = Util.toSeconds(protection_notify_delay_time, protection_notify_delay_length);
filter_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase());
filter_username = getConfigString("filter.username", "`~!@#$%^&*()-= + {[]}|\\:;\"<,>.?/");
filter_password = getConfigString("filter.password", "&");
filter_whitelist= getConfigString("filter.whitelist", "");
} else if (config.equalsIgnoreCase("plugins")) {
CraftIRC_enabled = getConfigBoolean("CraftIRC.enabled", true);
CraftIRC_tag = getConfigString("CraftIRC.tag", "admin");
CraftIRC_prefix = getConfigString("CraftIRC.prefix", "%b%%green%[{PLUGIN}]%k%%b%");
/*
CraftIRC_messages_enabled = getConfigBoolean("CraftIRC.messages.enabled", true);
CraftIRC_messages_welcome_enabled = getConfigBoolean("CraftIRC.messages.welcome", true);
CraftIRC_messages_register_enabled = getConfigBoolean("CraftIRC.messages.register", true);
CraftIRC_messages_unregister_enabled = getConfigBoolean("CraftIRC.messages.unregister", true);
CraftIRC_messages_login_enabled = getConfigBoolean("CraftIRC.messages.login", true);
CraftIRC_messages_email_enabled = getConfigBoolean("CraftIRC.messages.email", true);
CraftIRC_messages_username_enabled = getConfigBoolean("CraftIRC.messages.username", true);
CraftIRC_messages_password_enabled = getConfigBoolean("CraftIRC.messages.password", true);
CraftIRC_messages_idle_enabled = getConfigBoolean("CraftIRC.messages.idle", true);
*/
} else if (config.equalsIgnoreCase("messages")) {
Messages.time_millisecond = Config.getConfigString("Core.time.millisecond.", "millisecond");
Messages.time_milliseconds = Config.getConfigString("Core.time.milliseconds", "milliseconds");
Messages.time_second = Config.getConfigString("Core.time.second.", "second");
Messages.time_seconds = Config.getConfigString("Core.time.seconds", "seconds");
Messages.time_minute = Config.getConfigString("Core.time.minute.", "minute");
Messages.time_minutes = Config.getConfigString("Core.time.minutes", "minutes");
Messages.time_hour = Config.getConfigString("Core.time.hour.", "hour");
Messages.time_hours = Config.getConfigString("Core.time.hours", "hours");
Messages.time_day = Config.getConfigString("Core.time.day", "day");
Messages.time_days = Config.getConfigString("Core.time.days", "days");
Messages.AuthDB_message_reload_success = Config.getConfigString("Core.reload.success", "AuthDB has successfully reloaded!");
Messages.AuthDB_message_database_failure = Config.getConfigString("Core.database.failure", "{RED}database connection failed! Access is denied! Contact admin.");
Messages.AuthDB_message_register_welcome = (String)Config.getConfigString("Core.register.welcome", "{YELLOW}Welcome {WHITE}guest{YELLOW}! Please use {REGISTERCMD} password email");
Messages.AuthDB_message_register_success = Config.getConfigString("Core.register.success", "{RED}You have been registered!");
Messages.AuthDB_message_register_failure = Config.getConfigString("Core.register.failure", "{RED}Registration failed!");
Messages.AuthDB_message_register_offline = Config.getConfigString("Core.register.offline", "{RED}Database is unavailable. Unable to verify password!");
Messages.AuthDB_message_register_exists = Config.getConfigString("Core.register.exists", "{RED}You are already registered!");
Messages.AuthDB_message_register_disabled = Config.getConfigString("Core.register.disabled", "{RED}Registration not allowed!");
Messages.AuthDB_message_register_usage = Config.getConfigString("Core.register.usage", "{RED}Correct usage is: /register password email");
Messages.AuthDB_message_register_timeout = Config.getConfigString("Core.register.timeout", "Kicked because you failed to register within {REGISTERTIMEOUT}.");
Messages.AuthDB_message_unregister_success = Config.getConfigString("Core.unregister.success", "{BRIGHTGREEN}Unregistered successfully!");
Messages.AuthDB_message_unregister_failure = Config.getConfigString("Core.unregister.failure", "{RED}An error occurred while unregistering!");
Messages.AuthDB_message_unregister_usage = Config.getConfigString("Core.unregister.usage", "{RED}Correct usage is: /unregister password");
Messages.AuthDB_message_logout_success = Config.getConfigString("Core.logout.success", "Successfully logged out!");
Messages.AuthDB_message_logout_failure = Config.getConfigString("Core.logout.failure", "You are not logged in!");
Messages.AuthDB_message_logout_admin = Config.getConfigString("Core.logout.admin", "You have been logged out by an admin.");
Messages.AuthDB_message_logout_admin_success = Config.getConfigString("Core.logout.adminsuccess", "Successfully logged out player, {PLAYER}.");
Messages.AuthDB_message_logout_admin_failure = Config.getConfigString("Core.logout.adminfailure", "You cannot logout player, {PLAYER}! That player is not logged in");
Messages.AuthDB_message_logout_admin_notfound = Config.getConfigString("Core.logout.adminnotfound", "Could not find player, {PLAYER}! Please try again.");
Messages.AuthDB_message_logout_usage = Config.getConfigString("Core.logout.usage", "{YELLOW}Correct usage is: {WHITE}{LOGOUTCMD}");
Messages.AuthDB_message_login_normal = Config.getConfigString("Core.login.normal", "{YELLOW}Welcome back {WHITE}{PLAYER}{YELLOW}! Please use /login password");
Messages.AuthDB_message_login_prompt = Config.getConfigString("Core.login.prompt", "{WHITE}Welcome {TEAL}{PLAYER}{WHITE}! Please enter your password:");
Messages.AuthDB_message_login_success = Config.getConfigString("Core.login.success", "{BRIGHTGREEN}Password accepted. Welcome!");
Messages.AuthDB_message_login_failure = Config.getConfigString("Core.login.failure", "{RED}Password incorrect, please try again.");
Messages.AuthDB_message_login_offline = Config.getConfigString("Core.login.offline", "{RED}Database is unavailable. Unable to verify password!");
Messages.AuthDB_message_login_authorized = Config.getConfigString("Core.login.authorized", "{BRIGHTGREEN}You are already logged in!");
Messages.AuthDB_message_login_notregistered = Config.getConfigString("Core.login.notregistered", "{RED}You are not registred yet!");
Messages.AuthDB_message_login_timeout = Config.getConfigString("Core.login.timeout", "Kicked because you failed to login within {LOGINTIMEOUT}.");
Messages.AuthDB_message_login_admin = Config.getConfigString("Core.login.admin", "You have been logged in by an admin.");
Messages.AuthDB_message_login_admin_success = Config.getConfigString("Core.login.admin.success", "Successfully logged in player, {PLAYER}.");
Messages.AuthDB_message_login_admin_failure = Config.getConfigString("Core.login.adminfailure", "You cannot login player {PLAYER}! That player is already logged in.");
Messages.AuthDB_message_login_admin_notfound = Config.getConfigString("Core.login.adminnotfound", "Could not find player, {PLAYER}! Please try again.");
Messages.AuthDB_message_login_usage = Config.getConfigString("Core.login.usage", "{RED}Correct usage is: /login password");
Messages.AuthDB_message_link_welcome = (String)Config.getConfigString("Core.link.welcome", "or {LINKCMD} otherusername password");
Messages.AuthDB_message_link_success = Config.getConfigString("Core.link.success", "{BRIGHTGREEN}You have successfully linked!. You are now logged in");
Messages.AuthDB_message_link_failure = Config.getConfigString("Core.link.failure", "{RED}Error while linking!");
Messages.AuthDB_message_link_exists = Config.getConfigString("Core.link.exists", "{RED}You are already linked to a username!");
Messages.AuthDB_message_link_duplicate = Config.getConfigString("Core.link.duplicate", "{RED}Username is already linked to another player!");
Messages.AuthDB_message_link_registred = Config.getConfigString("Core.link.registred", "{RED}You cannot link as this username is already registered!");
Messages.AuthDB_message_link_invaliduser = Config.getConfigString("Core.link.invaliduser", "{RED}You cannot link with yourself!");
Messages.AuthDB_message_link_usage = Config.getConfigString("Core.link.usage", "{RED}Correct usage is: /link otherusername password");
Messages.AuthDB_message_unlink_success = Config.getConfigString("Core.unlink.success", "{BRIGHTGREEN}You have successfully unlinked!");
Messages.AuthDB_message_unlink_failure = Config.getConfigString("Core.unlink.failure", "{RED}Error while unlinking!");
Messages.AuthDB_message_unlink_nonexist = Config.getConfigString("Core.unlink.nonexist", "{RED}You do not have a linked username!");
Messages.AuthDB_message_unlink_invaliduser = Config.getConfigString("Core.unlink.invaliduser", "{RED}Invalid linked username!");
Messages.AuthDB_message_unlink_invalidpass = Config.getConfigString("Core.unlink.invalidpass", "{RED}Invalid linked password!");
Messages.AuthDB_message_unlink_usage = Config.getConfigString("Core.unlink.usage", "{RED}Correct usage is: /unlink otherusername password");
Messages.AuthDB_message_email_required = Config.getConfigString("Core.email.required", "{RED}Email required for registration!");
Messages.AuthDB_message_email_invalid = Config.getConfigString("Core.email.invalid", "{RED}Invalid email! Please try again!");
Messages.AuthDB_message_email_badcharacters = Config.getConfigString("Core.email.badcharacters", "{RED}Email contains bad characters! {BADCHARACTERS}!");
Messages.AuthDB_message_filter_renamed = Config.getConfigString("Core.filter.renamed", "{RED}{PLAYER} renamed to {PLAYERNEW} due to bad characters: {USERBADCHARACTERS}.");
Messages.AuthDB_message_filter_username = Config.getConfigString("Core.filter.username", "{RED}Username contains bad characters: {USERBADCHARACTERS}!");
Messages.AuthDB_message_filter_password = Config.getConfigString("Core.filter.password", "{RED}Password contains bad characters: {PASSBADCHARACTERS}!");
Messages.AuthDB_message_filter_whitelist = Config.getConfigString("Core.filter.whitelist", "{BRIGHTGREEN}{PLAYER} is on the filter {WHITE}whitelist{BRIGHTGREEN}, bypassing restrictions!");
Messages.AuthDB_message_username_minimum = Config.getConfigString("Core.username.minimum", "{RED}Your username does not meet the minimum requirement of {USERMIN} characters!");
Messages.AuthDB_message_username_maximum = Config.getConfigString("Core.username.maximum", "{RED}Your username does not meet the maximum requirement of {USERMAX} characters!");
Messages.AuthDB_message_password_minimum = Config.getConfigString("Core.password.minimum", "{RED}Your password does not meet the minimum requirement of {PASSMIN} characters!");
Messages.AuthDB_message_password_maximum = Config.getConfigString("Core.password.maximum", "{RED}Your password does not meet the maximum requirement of {PASSMAX} characters!");
Messages.AuthDB_message_password_success = Config.getConfigString("Core.password.success", "{BRIGHTGREEN}Password changed successfully!");
Messages.AuthDB_message_password_failure = Config.getConfigString("Core.password.failure", "{RED}Error! Password change failed!");
Messages.AuthDB_message_password_notregistered = Config.getConfigString("Core.password.notregistered", "{RED}Register first!");
Messages.AuthDB_message_password_usage = Config.getConfigString("Core.password.usage", "{RED}Correct usage is: /password oldpassword password");
Messages.AuthDB_message_session_valid = Config.getConfigString("Core.session.valid", "{BRIGHTGREEN}Hey, I remember you! You are logged in!");
Messages.AuthDB_message_session_protected = Config.getConfigString("Core.session.protected", "{RED}Sorry, a player with that name is already logged in on this server.");
Messages.AuthDB_message_protection_denied = Config.getConfigString("Core.protection.denied", "You do not have permission to use that command.");
Messages.AuthDB_message_protection_notauthorized = Config.getConfigString("Core.protection.notauthorized", "{RED}You are not authorized to do that!");
Messages.CraftIRC_message_status_join = Config.getConfigString("Plugins.CraftIRC.status.join", "{PLAYER} has joined the server.");
Messages.CraftIRC_message_status_quit = Config.getConfigString("Plugins.CraftIRC.status.quit", "{PLAYER} has quit the server.");
Messages.CraftIRC_message_register_success = Config.getConfigString("Plugins.CraftIRC.register.success", "{PLAYER} just registered successfully!");
Messages.CraftIRC_message_register_failure = Config.getConfigString("Plugins.CraftIRC.register.failure", "{PLAYER} had some errors while registering!");
Messages.CraftIRC_message_register_registered = Config.getConfigString("Plugins.CraftIRC.register.registered", "{PLAYER} had a lapse in memory and tried to register again.");
Messages.CraftIRC_message_password_success = Config.getConfigString("Plugins.CraftIRC.password.success", "{PLAYER} logged in successfully!");
Messages.CraftIRC_message_password_failure = Config.getConfigString("Plugins.CraftIRC.password.failure", "{PLAYER} tried to login with the wrong password!");
Messages.CraftIRC_message_idle_kicked = Config.getConfigString("Plugins.CraftIRC.idle.kicked", "{PLAYER} was kicked due to bad characters in username!");
Messages.CraftIRC_message_idle_whitelist = Config.getConfigString("Plugins.CraftIRC.idle.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!");
Messages.CraftIRC_message_filter_renamed = Config.getConfigString("Plugins.CraftIRC.filter.renamed", "{PLAYER} renamed to {PLAYERNEW} due to bad characters.");
Messages.CraftIRC_message_filter_kicked = Config.getConfigString("Plugins.CraftIRC.filter.kicked", "{PLAYER} was kicked due to bad characters in username!");
Messages.CraftIRC_message_filter_whitelist = Config.getConfigString("Plugins.CraftIRC.filter.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!");
} else if (config.equalsIgnoreCase("commands")) {
commands_register = Config.getConfigString("Core.commands.register", "/register");
commands_link = Config.getConfigString("Core.commands.link", "/link");
commands_unlink = Config.getConfigString("Core.commands.unlink", "/unlink");
commands_login = Config.getConfigString("Core.commands.login", "/login");
commands_logout = Config.getConfigString("Core.commands.logout", "/logout");
commands_setspawn = Config.getConfigString("Core.commands.setspawn", "/authdb setspawn");
commands_reload = Config.getConfigString("Core.commands.reload", "/authdb reload");
aliases_register = Config.getConfigString("Core.aliases.register", "/r");
aliases_link = Config.getConfigString("Core.aliases.link", "/li");
aliases_unlink = Config.getConfigString("Core.aliases.unlink", "/ul");
aliases_login = Config.getConfigString("Core.aliases.login", "/l");
aliases_logout = Config.getConfigString("Core.aliases.logout", "/lo");
aliases_setspawn = Config.getConfigString("Core.aliases.setspawn", "/s");
aliases_reload = Config.getConfigString("Core.aliases.reload", "/ar");
}
}
| public Config(String config, String directory, String filename) {
template = new Configuration(new File(directory, filename));
template.load();
if (config.equalsIgnoreCase("basic")) {
language = getConfigString("plugin.language", "English");
autoupdate_enable = getConfigBoolean("plugin.autoupdate", true);
debug_enable = getConfigBoolean("plugin.debugmode", false);
usagestats_enabled = getConfigBoolean("plugin.usagestats", true);
logformat = getConfigString("plugin.logformat", "yyyy-MM-dd");
logging_enabled = getConfigBoolean("plugin.logging", true);
database_type = getConfigString("database.type", "mysql");
database_username = getConfigString("database.username", "root");
database_password = getConfigString("database.password", "");
database_port = getConfigString("database.port", "3306");
database_host = getConfigString("database.host", "localhost");
database_database = getConfigString("database.name", "forum");
database_keepalive = getConfigBoolean("database.keepalive", false);
dbDb = "jdbc:mysql://" + database_host + ":" + database_port + "/" + database_database;
script_name = getConfigString("script.name", "phpbb").toLowerCase();
script_version = getConfigString("script.version", "3.0.8");
script_tableprefix = getConfigString("script.tableprefix", "");
script_updatestatus = getConfigBoolean("script.updatestatus", true);
script_salt = getConfigString("script.salt", "");
} else if (config.equalsIgnoreCase("advanced")) {
custom_enabled = getConfigBoolean("customdb.enabled", false);
custom_autocreate = getConfigBoolean("customdb.autocreate", true);
custom_emailrequired = getConfigBoolean("customdb.emailrequired", false);
custom_table = getConfigString("customdb.table", "authdb_users");
custom_userfield = getConfigString("customdb.userfield", "username");
custom_passfield = getConfigString("customdb.passfield", "password");
custom_emailfield = getConfigString("customdb.emailfield", "email");
custom_encryption = getConfigString("customdb.encryption", "md5").toLowerCase();
register_enabled = getConfigBoolean("register.enabled", true);
register_force = getConfigBoolean("register.force", true);
register_delay_length = Util.split(getConfigString("register.delay", "4 seconds"), " ")[0];
register_delay_time = Util.split(getConfigString("register.delay", "4 seconds"), " ")[1];
register_delay = Util.toTicks(register_delay_time,register_delay_length);
register_show_length = Util.split(getConfigString("register.show", "10 seconds"), " ")[0];
register_show_time = Util.split(getConfigString("register.show", "10 seconds"), " ")[1];
register_show = Util.toSeconds(register_show_time,register_show_length);
register_timeout_length = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[0];
register_timeout_time = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[1];
register_timeout = Util.toTicks(register_timeout_time,register_timeout_length);
login_method = getConfigString("login.method", "prompt");
login_tries = getConfigString("login.tries", "3");
login_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase());
login_delay_length = Util.split(getConfigString("login.delay", "4 seconds"), " ")[0];
login_delay_time = Util.split(getConfigString("login.delay", "4 seconds"), " ")[1];
login_delay = Util.toTicks(login_delay_time,login_delay_length);
login_show_length = Util.split(getConfigString("login.show", "10 seconds"), " ")[0];
login_show_time = Util.split(getConfigString("login.show", "10 seconds"), " ")[1];
login_show = Util.toSeconds(login_show_time,login_show_length);
login_timeout_length = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[0];
login_timeout_time = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[1];
login_timeout = Util.toTicks(login_timeout_time,login_timeout_length);
link_enabled = getConfigBoolean("link.enabled", true);
link_rename = getConfigBoolean("link.rename", true);
unlink_enabled = getConfigBoolean("unlink.enabled", true);
unlink_rename = getConfigBoolean("unlink.rename", true);
username_minimum = getConfigString("username.minimum", "3");
username_maximum = getConfigString("username.maximum", "16");
password_minimum = getConfigString("password.minimum", "6");
password_maximum = getConfigString("password.maximum", "16");
session_enabled = getConfigBoolean("session.enabled", false);
session_protect = getConfigBoolean("session.protect", true);
session_thelength = Util.split(getConfigString("session.length", "1 hour"), " ")[0];
session_time = Util.split(getConfigString("session.length", "1 hour"), " ")[1];
session_length = Util.toSeconds(session_time,session_thelength);
session_start = Util.checkSessionStart(getConfigString("session.start", "login"));
guests_commands = getConfigBoolean("guest.commands", false);
guests_movement = getConfigBoolean("guest.movement", false);
guests_inventory = getConfigBoolean("guest.inventory", false);
guests_drop = getConfigBoolean("guest.drop", false);
guests_pickup = getConfigBoolean("guest.pickup", false);
guests_health = getConfigBoolean("guest.health", false);
guests_mobdamage = getConfigBoolean("guest.mobdamage", false);
guests_interact = getConfigBoolean("guest.interactions", false);
guests_build = getConfigBoolean("guest.building", false);
guests_destroy = getConfigBoolean("guest.destruction", false);
guests_chat = getConfigBoolean("guest.chat", false);
guests_mobtargeting = getConfigBoolean("guest.mobtargeting", false);
guests_pvp = getConfigBoolean("guest.pvp", false);
protection_freeze = getConfigBoolean("protection.freeze.enabled", true);
protection_freeze_delay_length = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[0];
protection_freeze_delay_time = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[1];
protection_freeze_delay = Util.toSeconds(protection_freeze_delay_time, protection_freeze_delay_length);
protection_notify = getConfigBoolean("protection.notify.enabled", true);
protection_notify_delay_length = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[0];
protection_notify_delay_time = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[1];
protection_notify_delay = Util.toSeconds(protection_notify_delay_time, protection_notify_delay_length);
filter_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase());
filter_username = getConfigString("filter.username", "`~!@#$%^&*()-= + {[]}|\\:;\"<,>.?/");
filter_password = getConfigString("filter.password", "&");
filter_whitelist= getConfigString("filter.whitelist", "");
} else if (config.equalsIgnoreCase("plugins")) {
CraftIRC_enabled = getConfigBoolean("CraftIRC.enabled", true);
CraftIRC_tag = getConfigString("CraftIRC.tag", "admin");
CraftIRC_prefix = getConfigString("CraftIRC.prefix", "%b%%green%[{PLUGIN}]%k%%b%");
/*
CraftIRC_messages_enabled = getConfigBoolean("CraftIRC.messages.enabled", true);
CraftIRC_messages_welcome_enabled = getConfigBoolean("CraftIRC.messages.welcome", true);
CraftIRC_messages_register_enabled = getConfigBoolean("CraftIRC.messages.register", true);
CraftIRC_messages_unregister_enabled = getConfigBoolean("CraftIRC.messages.unregister", true);
CraftIRC_messages_login_enabled = getConfigBoolean("CraftIRC.messages.login", true);
CraftIRC_messages_email_enabled = getConfigBoolean("CraftIRC.messages.email", true);
CraftIRC_messages_username_enabled = getConfigBoolean("CraftIRC.messages.username", true);
CraftIRC_messages_password_enabled = getConfigBoolean("CraftIRC.messages.password", true);
CraftIRC_messages_idle_enabled = getConfigBoolean("CraftIRC.messages.idle", true);
*/
} else if (config.equalsIgnoreCase("messages")) {
Messages.time_millisecond = Config.getConfigString("Core.time.millisecond.", "millisecond");
Messages.time_milliseconds = Config.getConfigString("Core.time.milliseconds", "milliseconds");
Messages.time_second = Config.getConfigString("Core.time.second.", "second");
Messages.time_seconds = Config.getConfigString("Core.time.seconds", "seconds");
Messages.time_minute = Config.getConfigString("Core.time.minute.", "minute");
Messages.time_minutes = Config.getConfigString("Core.time.minutes", "minutes");
Messages.time_hour = Config.getConfigString("Core.time.hour.", "hour");
Messages.time_hours = Config.getConfigString("Core.time.hours", "hours");
Messages.time_day = Config.getConfigString("Core.time.day", "day");
Messages.time_days = Config.getConfigString("Core.time.days", "days");
Messages.AuthDB_message_reload_success = Config.getConfigString("Core.reload.success", "AuthDB has successfully reloaded!");
Messages.AuthDB_message_database_failure = Config.getConfigString("Core.database.failure", "{RED}database connection failed! Access is denied! Contact admin.");
Messages.AuthDB_message_register_welcome = (String)Config.getConfigString("Core.register.welcome", "{YELLOW}Welcome {WHITE}guest{YELLOW}! Please use {REGISTERCMD} password email");
Messages.AuthDB_message_register_success = Config.getConfigString("Core.register.success", "{RED}You have been registered!");
Messages.AuthDB_message_register_failure = Config.getConfigString("Core.register.failure", "{RED}Registration failed!");
Messages.AuthDB_message_register_offline = Config.getConfigString("Core.register.offline", "{RED}Database is unavailable. Unable to verify password!");
Messages.AuthDB_message_register_exists = Config.getConfigString("Core.register.exists", "{RED}You are already registered!");
Messages.AuthDB_message_register_disabled = Config.getConfigString("Core.register.disabled", "{RED}Registration not allowed!");
Messages.AuthDB_message_register_usage = Config.getConfigString("Core.register.usage", "{RED}Correct usage is: /register password email");
Messages.AuthDB_message_register_timeout = Config.getConfigString("Core.register.timeout", "Kicked because you failed to register within {REGISTERTIMEOUT}.");
Messages.AuthDB_message_unregister_success = Config.getConfigString("Core.unregister.success", "{BRIGHTGREEN}Unregistered successfully!");
Messages.AuthDB_message_unregister_failure = Config.getConfigString("Core.unregister.failure", "{RED}An error occurred while unregistering!");
Messages.AuthDB_message_unregister_usage = Config.getConfigString("Core.unregister.usage", "{RED}Correct usage is: /unregister password");
Messages.AuthDB_message_logout_success = Config.getConfigString("Core.logout.success", "Successfully logged out!");
Messages.AuthDB_message_logout_failure = Config.getConfigString("Core.logout.failure", "You are not logged in!");
Messages.AuthDB_message_logout_admin = Config.getConfigString("Core.logout.admin", "You have been logged out by an admin.");
Messages.AuthDB_message_logout_admin_success = Config.getConfigString("Core.logout.adminsuccess", "Successfully logged out player, {PLAYER}.");
Messages.AuthDB_message_logout_admin_failure = Config.getConfigString("Core.logout.adminfailure", "You cannot logout player, {PLAYER}! That player is not logged in");
Messages.AuthDB_message_logout_admin_notfound = Config.getConfigString("Core.logout.adminnotfound", "Could not find player, {PLAYER}! Please try again.");
Messages.AuthDB_message_logout_usage = Config.getConfigString("Core.logout.usage", "{YELLOW}Correct usage is: {WHITE}{LOGOUTCMD}");
Messages.AuthDB_message_login_normal = Config.getConfigString("Core.login.normal", "{YELLOW}Welcome back {WHITE}{PLAYER}{YELLOW}! Please use /login password");
Messages.AuthDB_message_login_prompt = Config.getConfigString("Core.login.prompt", "{WHITE}Welcome {TEAL}{PLAYER}{WHITE}! Please enter your password:");
Messages.AuthDB_message_login_success = Config.getConfigString("Core.login.success", "{BRIGHTGREEN}Password accepted. Welcome!");
Messages.AuthDB_message_login_failure = Config.getConfigString("Core.login.failure", "{RED}Password incorrect, please try again.");
Messages.AuthDB_message_login_offline = Config.getConfigString("Core.login.offline", "{RED}Database is unavailable. Unable to verify password!");
Messages.AuthDB_message_login_authorized = Config.getConfigString("Core.login.authorized", "{BRIGHTGREEN}You are already logged in!");
Messages.AuthDB_message_login_notregistered = Config.getConfigString("Core.login.notregistered", "{RED}You are not registred yet!");
Messages.AuthDB_message_login_timeout = Config.getConfigString("Core.login.timeout", "Kicked because you failed to login within {LOGINTIMEOUT}.");
Messages.AuthDB_message_login_admin = Config.getConfigString("Core.login.admin", "You have been logged in by an admin.");
Messages.AuthDB_message_login_admin_success = Config.getConfigString("Core.login.admin.success", "Successfully logged in player, {PLAYER}.");
Messages.AuthDB_message_login_admin_failure = Config.getConfigString("Core.login.adminfailure", "You cannot login player {PLAYER}! That player is already logged in.");
Messages.AuthDB_message_login_admin_notfound = Config.getConfigString("Core.login.adminnotfound", "Could not find player, {PLAYER}! Please try again.");
Messages.AuthDB_message_login_usage = Config.getConfigString("Core.login.usage", "{RED}Correct usage is: /login password");
Messages.AuthDB_message_link_welcome = (String)Config.getConfigString("Core.link.welcome", "or {LINKCMD} otherusername password");
Messages.AuthDB_message_link_success = Config.getConfigString("Core.link.success", "{BRIGHTGREEN}You have successfully linked!. You are now logged in");
Messages.AuthDB_message_link_failure = Config.getConfigString("Core.link.failure", "{RED}Error while linking!");
Messages.AuthDB_message_link_exists = Config.getConfigString("Core.link.exists", "{RED}You are already linked to a username!");
Messages.AuthDB_message_link_duplicate = Config.getConfigString("Core.link.duplicate", "{RED}Username is already linked to another player!");
Messages.AuthDB_message_link_registred = Config.getConfigString("Core.link.registred", "{RED}You cannot link as this username is already registered!");
Messages.AuthDB_message_link_invaliduser = Config.getConfigString("Core.link.invaliduser", "{RED}You cannot link with yourself!");
Messages.AuthDB_message_link_usage = Config.getConfigString("Core.link.usage", "{RED}Correct usage is: /link otherusername password");
Messages.AuthDB_message_unlink_success = Config.getConfigString("Core.unlink.success", "{BRIGHTGREEN}You have successfully unlinked!");
Messages.AuthDB_message_unlink_failure = Config.getConfigString("Core.unlink.failure", "{RED}Error while unlinking!");
Messages.AuthDB_message_unlink_nonexist = Config.getConfigString("Core.unlink.nonexist", "{RED}You do not have a linked username!");
Messages.AuthDB_message_unlink_invaliduser = Config.getConfigString("Core.unlink.invaliduser", "{RED}Invalid linked username!");
Messages.AuthDB_message_unlink_invalidpass = Config.getConfigString("Core.unlink.invalidpass", "{RED}Invalid linked password!");
Messages.AuthDB_message_unlink_usage = Config.getConfigString("Core.unlink.usage", "{RED}Correct usage is: /unlink otherusername password");
Messages.AuthDB_message_email_required = Config.getConfigString("Core.email.required", "{RED}Email required for registration!");
Messages.AuthDB_message_email_invalid = Config.getConfigString("Core.email.invalid", "{RED}Invalid email! Please try again!");
Messages.AuthDB_message_email_badcharacters = Config.getConfigString("Core.email.badcharacters", "{RED}Email contains bad characters! {BADCHARACTERS}!");
Messages.AuthDB_message_filter_renamed = Config.getConfigString("Core.filter.renamed", "{RED}{PLAYER} renamed to {PLAYERNEW} due to bad characters: {USERBADCHARACTERS}.");
Messages.AuthDB_message_filter_username = Config.getConfigString("Core.filter.username", "{RED}Username contains bad characters: {USERBADCHARACTERS}!");
Messages.AuthDB_message_filter_password = Config.getConfigString("Core.filter.password", "{RED}Password contains bad characters: {PASSBADCHARACTERS}!");
Messages.AuthDB_message_filter_whitelist = Config.getConfigString("Core.filter.whitelist", "{BRIGHTGREEN}{PLAYER} is on the filter {WHITE}whitelist{BRIGHTGREEN}, bypassing restrictions!");
Messages.AuthDB_message_username_minimum = Config.getConfigString("Core.username.minimum", "{RED}Your username does not meet the minimum requirement of {USERMIN} characters!");
Messages.AuthDB_message_username_maximum = Config.getConfigString("Core.username.maximum", "{RED}Your username does not meet the maximum requirement of {USERMAX} characters!");
Messages.AuthDB_message_password_minimum = Config.getConfigString("Core.password.minimum", "{RED}Your password does not meet the minimum requirement of {PASSMIN} characters!");
Messages.AuthDB_message_password_maximum = Config.getConfigString("Core.password.maximum", "{RED}Your password does not meet the maximum requirement of {PASSMAX} characters!");
Messages.AuthDB_message_password_success = Config.getConfigString("Core.password.success", "{BRIGHTGREEN}Password changed successfully!");
Messages.AuthDB_message_password_failure = Config.getConfigString("Core.password.failure", "{RED}Error! Password change failed!");
Messages.AuthDB_message_password_notregistered = Config.getConfigString("Core.password.notregistered", "{RED}Register first!");
Messages.AuthDB_message_password_usage = Config.getConfigString("Core.password.usage", "{RED}Correct usage is: /password oldpassword password");
Messages.AuthDB_message_session_valid = Config.getConfigString("Core.session.valid", "{BRIGHTGREEN}Hey, I remember you! You are logged in!");
Messages.AuthDB_message_session_protected = Config.getConfigString("Core.session.protected", "{RED}Sorry, a player with that name is already logged in on this server.");
Messages.AuthDB_message_protection_denied = Config.getConfigString("Core.protection.denied", "You do not have permission to use that command.");
Messages.AuthDB_message_protection_notauthorized = Config.getConfigString("Core.protection.notauthorized", "{RED}You are not authorized to do that!");
Messages.CraftIRC_message_status_join = Config.getConfigString("Plugins.CraftIRC.status.join", "{PLAYER} has joined the server.");
Messages.CraftIRC_message_status_quit = Config.getConfigString("Plugins.CraftIRC.status.quit", "{PLAYER} has quit the server.");
Messages.CraftIRC_message_register_success = Config.getConfigString("Plugins.CraftIRC.register.success", "{PLAYER} just registered successfully!");
Messages.CraftIRC_message_register_failure = Config.getConfigString("Plugins.CraftIRC.register.failure", "{PLAYER} had some errors while registering!");
Messages.CraftIRC_message_register_registered = Config.getConfigString("Plugins.CraftIRC.register.registered", "{PLAYER} had a lapse in memory and tried to register again.");
Messages.CraftIRC_message_password_success = Config.getConfigString("Plugins.CraftIRC.password.success", "{PLAYER} logged in successfully!");
Messages.CraftIRC_message_password_failure = Config.getConfigString("Plugins.CraftIRC.password.failure", "{PLAYER} tried to login with the wrong password!");
Messages.CraftIRC_message_idle_kicked = Config.getConfigString("Plugins.CraftIRC.idle.kicked", "{PLAYER} was kicked due to bad characters in username!");
Messages.CraftIRC_message_idle_whitelist = Config.getConfigString("Plugins.CraftIRC.idle.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!");
Messages.CraftIRC_message_filter_renamed = Config.getConfigString("Plugins.CraftIRC.filter.renamed", "{PLAYER} renamed to {PLAYERNEW} due to bad characters.");
Messages.CraftIRC_message_filter_kicked = Config.getConfigString("Plugins.CraftIRC.filter.kicked", "{PLAYER} was kicked due to bad characters in username!");
Messages.CraftIRC_message_filter_whitelist = Config.getConfigString("Plugins.CraftIRC.filter.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!");
} else if (config.equalsIgnoreCase("commands")) {
commands_register = Config.getConfigString("Core.commands.register", "/register");
commands_link = Config.getConfigString("Core.commands.link", "/link");
commands_unlink = Config.getConfigString("Core.commands.unlink", "/unlink");
commands_login = Config.getConfigString("Core.commands.login", "/login");
commands_logout = Config.getConfigString("Core.commands.logout", "/logout");
commands_setspawn = Config.getConfigString("Core.commands.setspawn", "/authdb setspawn");
commands_reload = Config.getConfigString("Core.commands.reload", "/authdb reload");
aliases_register = Config.getConfigString("Core.aliases.register", "/r");
aliases_link = Config.getConfigString("Core.aliases.link", "/li");
aliases_unlink = Config.getConfigString("Core.aliases.unlink", "/ul");
aliases_login = Config.getConfigString("Core.aliases.login", "/l");
aliases_logout = Config.getConfigString("Core.aliases.logout", "/lo");
aliases_setspawn = Config.getConfigString("Core.aliases.setspawn", "/s");
aliases_reload = Config.getConfigString("Core.aliases.reload", "/ar");
}
}
|
diff --git a/src/Util/Analyzer.java b/src/Util/Analyzer.java
index 1b17cef..fcf30eb 100644
--- a/src/Util/Analyzer.java
+++ b/src/Util/Analyzer.java
@@ -1,673 +1,675 @@
/*----------------------------------------------------------------------*/
/*
Module : Analyzer.java
Package : Util
Classes Included: Analyzer, VoiceAnalysisData
Purpose : Music analysis utilities
Programmer : Ted Dumitrescu
Date Started : 7/14/07
Updates :
*/
/*----------------------------------------------------------------------*/
package Util;
/*----------------------------------------------------------------------*/
/* Imported packages */
import java.io.*;
import java.net.*;
import java.util.*;
import DataStruct.*;
import Gfx.*;
/*----------------------------------------------------------------------*/
/*------------------------------------------------------------------------
Class: Analyzer
Extends: -
Purpose: Music analysis utilities for one score
------------------------------------------------------------------------*/
public class Analyzer
{
/*----------------------------------------------------------------------*/
/* Class variables */
/* for standalone application use */
static boolean screenoutput=false,
recursive=false;
public static final String BaseDataDir="/data/";
public static String BaseDataURL;
static String initdirectory;
static final int NUM_MENSURATIONS=4,
MENS_O=0,
MENS_C=1,
MENS_3=2,
MENS_P=3;
static final String MENSURATION_NAMES[]=new String[] { "O","C","3","P" };
static final int NUMVOICES_FOR_RHYTHM_AVG=2;
/*----------------------------------------------------------------------*/
/*----------------------------------------------------------------------*/
/* Instance variables */
PieceData musicData;
ScoreRenderer renderedSections[];
int numVoices;
/* analysis results */
public VoiceAnalysisData vad[];
public int totalUnpreparedSBDiss=0,
totalPassingDissSMPair=0,
totalOffbeatDissM=0;
public double avgRhythmicDensity[],
avgSyncopationDensity=0,
OCLength=0,
passingSMDissDensity=0,
offbeatMDissDensity=0,
dissDensity=0;
/*----------------------------------------------------------------------*/
/*----------------------------------------------------------------------*/
/* Class methods */
/*------------------------------------------------------------------------
Method: void main(String args[])
Purpose: Main routine
Parameters:
Input: String args[] - program arguments
Output: -
Return: -
------------------------------------------------------------------------*/
public static void main(String args[])
{
String cmdlineFilename=parseCmdLine(args);
/* initialize data locations */
try
{
initdirectory=new File(".").getCanonicalPath()+BaseDataDir;
BaseDataURL="file:///"+initdirectory;
}
catch (Exception e)
{
System.err.println("Error loading local file locations: "+e);
e.printStackTrace();
}
DataStruct.XMLReader.initparser(BaseDataURL,false);
MusicWin.initScoreWindowing(BaseDataURL,initdirectory+"music/",false);
try
{
Gfx.MusicFont.loadmusicface(BaseDataURL);
}
catch (Exception e)
{
System.err.println("Error loading font: "+e);
e.printStackTrace();
}
analyzeFiles(cmdlineFilename);
}
/*------------------------------------------------------------------------
Method: void analyzeFiles(String mainFilename)
Purpose: Analyze one set of files (recursing to subdirectories if necessary)
Parameters:
Input: String mainFilename - name of file set in one directory
String subdirName - name of subdirectory (null for base directory)
Output: -
Return: -
------------------------------------------------------------------------*/
static void analyzeFiles(String mainFilename)
{
try
{
PrintStream outs;
OptionSet optSet=new OptionSet(null);
RecursiveFileList fl=new RecursiveFileList(mainFilename,recursive);
LinkedList<Analyzer> results=new LinkedList<Analyzer>();
/* analyze individual pieces */
for (File curfile : fl)
{
URL fileURL=curfile.toURI().toURL();
String fileName=curfile.getName();
System.out.print("Analyzing: "+fileName+"...");
PieceData musicData=new CMMEParser(fileURL).piece;
ScoreRenderer[] renderedSections=renderSections(musicData,optSet);
Analyzer a=new Analyzer(musicData,renderedSections);
outs=screenoutput ? System.out : new PrintStream("data/stats/"+fileName+".txt");
a.printGeneralAnalysis(outs);
if (!screenoutput)
outs.close();
System.out.println("done");
results.add(a);
}
/* output result summary */
outs=screenoutput ? System.out : new PrintStream("data/stats/summary.txt");
if (screenoutput)
{
outs.println();
outs.println("SUMMARY");
outs.println();
}
outs.println("Composer\tTitle\tDensity (O)\tDensity (C)\tDensity (3)\tDensity (P)\tSyncop density\tUnprepared syncop diss\tPassing SM diss density\tOffbeat M diss density");
for (Analyzer a : results)
{
outs.print(a.musicData.getComposer()+"\t"+a.musicData.getFullTitle());
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
{
outs.print("\t");
if (a.avgRhythmicDensity[mi]>0)
outs.print(String.valueOf(a.avgRhythmicDensity[mi]));
else
outs.print("-");
}
outs.print("\t"+a.avgSyncopationDensity+"\t"+a.totalUnpreparedSBDiss);
outs.print("\t"+a.passingSMDissDensity+"\t"+a.offbeatMDissDensity);
outs.println();
}
if (!screenoutput)
outs.close();
}
catch (Exception e)
{
System.err.println("Error: "+e);
e.printStackTrace();
}
}
/*------------------------------------------------------------------------
Method: String parseCmdLine(String args[])
Purpose: Parse command line
Parameters:
Input: String args[] - program arguments
Output: -
Return: filename (or "*" if recursive with no filename specified)
------------------------------------------------------------------------*/
static String parseCmdLine(String args[])
{
String fn=null;
if (args.length<1)
usage_exit();
for (int i=0; i<args.length; i++)
if (args[i].charAt(0)=='-')
/* options */
for (int opti=1; opti<args[i].length(); opti++)
switch (args[i].charAt(opti))
{
case 's':
screenoutput=true;
break;
case 'r':
recursive=true;
break;
default:
usage_exit();
}
else
/* filename */
if (i!=args.length-1)
usage_exit();
else
fn=args[i];
if (fn==null)
if (recursive)
fn="*";
else
usage_exit();
return "data\\music\\"+fn;
}
/*------------------------------------------------------------------------
Method: void usage_exit()
Purpose: Exit for invalid command line
Parameters:
Input: -
Output: -
Return: -
------------------------------------------------------------------------*/
static void usage_exit()
{
System.err.println("Usage: java Util.Analyzer [options] filename");
System.err.println("Options:");
System.err.println(" -s: Screen output");
System.err.println(" -r: Recursively search subdirectories");
System.exit(1);
}
/*------------------------------------------------------------------------
Method: ScoreRenderer[] void renderSections()
Purpose: Pre-render all sections of one piece
Parameters:
Input: -
Output: -
Return: rendered section array
------------------------------------------------------------------------*/
static final double SECTION_END_SPACING=10;
static ScoreRenderer[] renderSections(PieceData musicData,OptionSet options)
{
double startX=0;
/* initialize voice parameters */
int numVoices=musicData.getVoiceData().length;
RenderedSectionParams[] sectionParams=new RenderedSectionParams[numVoices];
for (int i=0; i<numVoices; i++)
sectionParams[i]=new RenderedSectionParams();
/* initialize sections */
int numSections=musicData.getNumSections();
ScoreRenderer[] renderedSections=new ScoreRenderer[numSections];
int nummeasures=0;
for (int i=0; i<numSections; i++)
{
renderedSections[i]=new ScoreRenderer(
i,musicData.getSection(i),musicData,
sectionParams,
options,nummeasures,startX);
sectionParams=renderedSections[i].getEndingParams();
nummeasures+=renderedSections[i].getNumMeasures();
startX+=renderedSections[i].getXsize()+SECTION_END_SPACING;
}
return renderedSections;
}
/*----------------------------------------------------------------------*/
/* Instance methods */
/*------------------------------------------------------------------------
Constructor: Analyzer(PieceData musicData,ScoreRenderer renderedSections[])
Purpose: Initialize analysis functions for one score
Parameters:
Input: PieceData musicData - original music data
ScoreRenderer renderedSections[] - scored+rendered music data
Output: -
------------------------------------------------------------------------*/
public Analyzer(PieceData musicData,ScoreRenderer renderedSections[])
{
this.musicData=musicData;
this.renderedSections=renderedSections;
this.numVoices=musicData.getVoiceData().length;
}
/*------------------------------------------------------------------------
Method: void printGeneralAnalysis(PrintStream outp)
Purpose: Print generic score analysis
Parameters:
Input: -
Output: PrintStream outp - output destination
Return: -
------------------------------------------------------------------------*/
public void printGeneralAnalysis(PrintStream outp)
{
outp.println("General analysis: "+musicData.getComposer()+", "+musicData.getFullTitle());
outp.println();
outp.println("Number of voices: "+numVoices);
outp.println("Number of sections: "+renderedSections.length);
outp.println();
vad=new VoiceAnalysisData[numVoices];
for (int i=0; i<numVoices; i++)
{
vad[i]=new VoiceAnalysisData();
vad[i].vData=musicData.getVoiceData()[i];
}
totalUnpreparedSBDiss=0;
totalPassingDissSMPair=0;
for (ScoreRenderer s : renderedSections)
{
for (int i=0; i<s.getNumVoices(); i++)
{
int curMens=MENS_C;
Proportion curProp=new Proportion(Proportion.EQUALITY);
double curPropVal=curProp.toDouble(),
curMensStartTime=0;
RenderList rl=s.getRenderedVoice(i);
+ if (rl==null)
+ break;
int vnum=-1;
for (int i1=0; i1<numVoices; i1++)
if (rl.getVoiceData()==vad[i1].vData)
vnum=i1;
NoteEvent ne=null;
RenderedEvent rne=null;
int renum=0;
for (RenderedEvent re : rl)
{
switch (re.getEvent().geteventtype())
{
case Event.EVENT_NOTE:
ne=(NoteEvent)re.getEvent();
rne=re;
vad[i].numNotes[curMens]++;
vad[i].totalNumNotes++;
vad[i].totalNoteLengths[curMens]+=ne.getmusictime().toDouble()*curPropVal;
if (ne.getPitch().isLowerThan(vad[i].lowestPitch))
vad[i].lowestPitch=ne.getPitch();
if (ne.getPitch().isHigherThan(vad[i].highestPitch))
vad[i].highestPitch=ne.getPitch();
if (curMens!=MENS_3 &&
curMens!=MENS_P)
{
vad[i].numNotesOC++;
if (syncopated(s,re))
vad[i].totalOffbeat++;
if (isUnpreparedSuspension(s,re))
{
totalUnpreparedSBDiss++;
outp.println("Unprepared SB/M dissonance in m. "+(re.getmeasurenum()+1));
}
if (isPassingDissonantSMPair(s,i,renum))
totalPassingDissSMPair++;
if (isOffbeatDissonantM(s,re))
totalOffbeatDissM++;
}
break;
case Event.EVENT_MULTIEVENT:
// to be implemented
Mensuration m=re.getEvent().getMensInfo();
if (m!=null)
curMens=getMensType(m);
break;
case Event.EVENT_MENS:
vad[i].totalPassageLengths[curMens]+=re.getmusictime().toDouble()-curMensStartTime;
curMensStartTime=re.getmusictime().toDouble();
curMens=getMensType(re.getEvent().getMensInfo());
if (curMens==MENS_O &&
((MensEvent)re.getEvent()).getSigns().size()>1 ||
((MensEvent)re.getEvent()).getMainSign().signType==MensSignElement.NUMBERS)
curMens=MENS_3;
break;
case Event.EVENT_PROPORTION:
curProp.multiply(((ProportionEvent)re.getEvent()).getproportion());
curPropVal=curProp.toDouble();
break;
}
renum++;
}
if (ne!=null)
{
/* discount final longa */
vad[i].numNotes[curMens]--;
vad[i].totalNumNotes--;
vad[i].totalNoteLengths[curMens]-=ne.getmusictime().toDouble()*curPropVal;
vad[i].totalPassageLengths[curMens]+=rne.getmusictime().toDouble()-curMensStartTime;
}
}
}
if (totalUnpreparedSBDiss>0)
outp.println();
for (int i=0; i<numVoices; i++)
{
outp.println("Voice "+(i+1)+": "+musicData.getVoiceData()[i].getName());
outp.println(" Range: "+vad[i].lowestPitch+" - "+vad[i].highestPitch);
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
if (vad[i].numNotes[mi]!=0)
{
outp.println(" Mensuration type: "+MENSURATION_NAMES[mi]);
outp.println(" Number of notes (not including final): "+vad[i].numNotes[mi]);
outp.println(" Total note lengths: "+vad[i].totalNoteLengths[mi]);
vad[i].rhythmicDensity[mi]=vad[i].totalNoteLengths[mi]/(double)vad[i].numNotes[mi];
outp.println(" Rhythmic density: "+vad[i].rhythmicDensity[mi]);
}
vad[i].syncopationDensity=(double)vad[i].totalOffbeat/(double)vad[i].numNotesOC;
outp.println(" Number of syncopated notes: "+vad[i].totalOffbeat);
outp.println(" Syncopation density: "+vad[i].syncopationDensity);
outp.println();
}
/* averages of the top two voices */
avgRhythmicDensity=new double[] { 0,0,0,0 };
outp.println();
outp.println("Averages for highest "+NUMVOICES_FOR_RHYTHM_AVG+" voices");
for (int i=0; i<numVoices && i<NUMVOICES_FOR_RHYTHM_AVG; i++)
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
if (vad[i].numNotes[mi]>0)
avgRhythmicDensity[mi]+=vad[i].rhythmicDensity[mi]/2; // for SB, not minims
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
{
if (numVoices>NUMVOICES_FOR_RHYTHM_AVG-1)
avgRhythmicDensity[mi]/=(double)NUMVOICES_FOR_RHYTHM_AVG;
if (avgRhythmicDensity[mi]>0)
outp.println(" Rhythmic density in SB ("+MENSURATION_NAMES[mi]+"): "+
avgRhythmicDensity[mi]);
}
avgSyncopationDensity=0;
for (int i=0; i<numVoices && i<NUMVOICES_FOR_RHYTHM_AVG; i++)
avgSyncopationDensity+=vad[i].syncopationDensity;
if (numVoices>NUMVOICES_FOR_RHYTHM_AVG-1)
avgSyncopationDensity/=(double)NUMVOICES_FOR_RHYTHM_AVG;
outp.println(" Syncopation density: "+avgSyncopationDensity);
if (totalUnpreparedSBDiss>0)
outp.println("Number of unprepared syncopated SB/M dissonances: "+totalUnpreparedSBDiss);
outp.println("Number of passing dissonant SM pairs: "+totalPassingDissSMPair);
outp.println("Number of dissonant offbeat Ms: "+totalOffbeatDissM);
double avgMensLengths[]=new double[] { 0,0,0,0 };
for (int i=0; i<numVoices; i++)
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
avgMensLengths[mi]+=vad[i].totalPassageLengths[mi];
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
avgMensLengths[mi]/=(double)numVoices;
OCLength=(avgMensLengths[MENS_O]+avgMensLengths[MENS_C])/2; /* in SB */
passingSMDissDensity=totalPassingDissSMPair/OCLength;
offbeatMDissDensity=totalOffbeatDissM/OCLength;
dissDensity=(totalPassingDissSMPair+totalOffbeatDissM)/OCLength;
outp.println("Total length of O/C sections: "+OCLength);
outp.println("Passing dissonant SM pair density: "+passingSMDissDensity);
outp.println("Offbeat dissonant M density: "+offbeatMDissDensity);
// outp.println("Basic dissonance density: "+dissDensity);
}
int getMensType(Mensuration m)
{
if (m.prolatio==Mensuration.MENS_TERNARY)
return MENS_P;
if (m.tempus==Mensuration.MENS_TERNARY)
return MENS_O;
return MENS_C;
}
boolean isUnpreparedSuspension(ScoreRenderer s,RenderedEvent re)
{
MeasureInfo measure=s.getMeasure(re.getmeasurenum());
double mt=re.getmusictime().toDouble(),
measurePos=mt-measure.startMusicTime.toDouble(),
len=re.getEvent().getLength().toDouble();
NoteEvent ne=(NoteEvent)re.getEvent();
if (re.getmusictime().i2%3==0) /* avoid sesquialtera/tripla */
return false;
if (len<1)
return false;
if (len>=2 &&
((int)measurePos)%2==0)
return false;
if (len>=1 && len<2 &&
(double)(measurePos-(int)measurePos)<=0.0)
return false;
Pitch p=ne.getPitch();
RenderedSonority rs=re.getFullSonority();
for (int i=0; i<rs.getNumPitches(); i++)
if (isDissonant(p,rs.getPitch(i),i==0) &&
rs.getRenderedNote(i).getmusictime().toDouble()<mt)
return true;
return false;
}
boolean isPassingDissonantSMPair(ScoreRenderer s,int vnum,int renum)
{
RenderedEvent re=s.eventinfo[vnum].getEvent(renum);
MeasureInfo measure=s.getMeasure(re.getmeasurenum());
double mt=re.getmusictime().toDouble(),
measurePos=mt-measure.startMusicTime.toDouble();
NoteEvent ne=(NoteEvent)re.getEvent();
if (ne.getnotetype()!=NoteEvent.NT_Semiminima ||
(double)(measurePos-(int)measurePos)>0 ||
((int)measurePos)%2==0)
return false;
/* check next note */
RenderedEvent nextNote=s.getNeighboringEventOfType(Event.EVENT_NOTE,vnum,renum+1,1);
if (nextNote==null ||
nextNote.getmusictime().toDouble()>mt+0.5)
return false;
Event e=nextNote.getEvent();
NoteEvent ne2=e.geteventtype()==Event.EVENT_MULTIEVENT ?
((MultiEvent)e).getLowestNote() :
(NoteEvent)e;
if (ne2.getnotetype()!=NoteEvent.NT_Semiminima)
return false;
/* check for dissonance */
Pitch p=ne.getPitch();
RenderedSonority rs=re.getFullSonority();
for (int i=0; i<rs.getNumPitches(); i++)
if (isDissonant(p,rs.getPitch(i),i==0))
return true;
return false;
}
boolean isOffbeatDissonantM(ScoreRenderer s,RenderedEvent re)
{
MeasureInfo measure=s.getMeasure(re.getmeasurenum());
double mt=re.getmusictime().toDouble(),
measurePos=mt-measure.startMusicTime.toDouble(),
len=re.getEvent().getLength().toDouble();
NoteEvent ne=(NoteEvent)re.getEvent();
if (ne.getnotetype()!=NoteEvent.NT_Minima ||
(double)(measurePos-(int)measurePos)>0 ||
((int)measurePos)%2==0)
return false;
if (len>1)
return false;
Pitch p=ne.getPitch();
RenderedSonority rs=re.getFullSonority();
for (int i=0; i<rs.getNumPitches(); i++)
if (isDissonant(p,rs.getPitch(i),i==0) &&
rs.getRenderedNote(i).getmusictime().toDouble()<mt)
return true;
return false;
}
boolean isDissonant(Pitch p1,Pitch p2,boolean bassInterval)
{
int interval=getAbsInterval(p1,p2);
if (interval==2 || interval==7 ||
(bassInterval && interval==4))
return true;
return false;
}
int getAbsInterval(Pitch p1,Pitch p2)
{
return Math.abs(p1.placenum-p2.placenum)%7+1;
}
boolean syncopated(ScoreRenderer s,RenderedEvent re)
{
MeasureInfo measure=s.getMeasure(re.getmeasurenum());
double mt=re.getmusictime().toDouble(),
measurePos=mt-measure.startMusicTime.toDouble(),
len=re.getEvent().getLength().toDouble();
if (re.getmusictime().i2%3==0) /* avoid sesquialtera/tripla */
return false;
if (len<=.5) /* no SM or smaller */
return false;
if (len<=1 &&
measurePos-(int)measurePos>0)
return true;
if (len>1 &&
(measurePos-(int)measurePos>0 ||
((int)measurePos)%2!=0))
return true;
return false;
}
}
/*------------------------------------------------------------------------
Class: VoiceAnalysisData
Extends: -
Purpose: Analysis parameters for one voice
------------------------------------------------------------------------*/
class VoiceAnalysisData
{
Voice vData=null;
int numNotes[]=new int[] { 0,0,0,0 },
totalNumNotes=0,
numNotesOC=0;
double totalNoteLengths[]=new double[] { 0,0,0,0 },
rhythmicDensity[]=new double[] { 0,0,0,0 },
totalPassageLengths[]=new double[] { 0,0,0,0 };
Pitch lowestPitch=Pitch.HIGHEST_PITCH,
highestPitch=Pitch.LOWEST_PITCH;
int totalOffbeat=0;
double syncopationDensity=0;
public VoiceAnalysisData()
{
}
}
| true | true | public void printGeneralAnalysis(PrintStream outp)
{
outp.println("General analysis: "+musicData.getComposer()+", "+musicData.getFullTitle());
outp.println();
outp.println("Number of voices: "+numVoices);
outp.println("Number of sections: "+renderedSections.length);
outp.println();
vad=new VoiceAnalysisData[numVoices];
for (int i=0; i<numVoices; i++)
{
vad[i]=new VoiceAnalysisData();
vad[i].vData=musicData.getVoiceData()[i];
}
totalUnpreparedSBDiss=0;
totalPassingDissSMPair=0;
for (ScoreRenderer s : renderedSections)
{
for (int i=0; i<s.getNumVoices(); i++)
{
int curMens=MENS_C;
Proportion curProp=new Proportion(Proportion.EQUALITY);
double curPropVal=curProp.toDouble(),
curMensStartTime=0;
RenderList rl=s.getRenderedVoice(i);
int vnum=-1;
for (int i1=0; i1<numVoices; i1++)
if (rl.getVoiceData()==vad[i1].vData)
vnum=i1;
NoteEvent ne=null;
RenderedEvent rne=null;
int renum=0;
for (RenderedEvent re : rl)
{
switch (re.getEvent().geteventtype())
{
case Event.EVENT_NOTE:
ne=(NoteEvent)re.getEvent();
rne=re;
vad[i].numNotes[curMens]++;
vad[i].totalNumNotes++;
vad[i].totalNoteLengths[curMens]+=ne.getmusictime().toDouble()*curPropVal;
if (ne.getPitch().isLowerThan(vad[i].lowestPitch))
vad[i].lowestPitch=ne.getPitch();
if (ne.getPitch().isHigherThan(vad[i].highestPitch))
vad[i].highestPitch=ne.getPitch();
if (curMens!=MENS_3 &&
curMens!=MENS_P)
{
vad[i].numNotesOC++;
if (syncopated(s,re))
vad[i].totalOffbeat++;
if (isUnpreparedSuspension(s,re))
{
totalUnpreparedSBDiss++;
outp.println("Unprepared SB/M dissonance in m. "+(re.getmeasurenum()+1));
}
if (isPassingDissonantSMPair(s,i,renum))
totalPassingDissSMPair++;
if (isOffbeatDissonantM(s,re))
totalOffbeatDissM++;
}
break;
case Event.EVENT_MULTIEVENT:
// to be implemented
Mensuration m=re.getEvent().getMensInfo();
if (m!=null)
curMens=getMensType(m);
break;
case Event.EVENT_MENS:
vad[i].totalPassageLengths[curMens]+=re.getmusictime().toDouble()-curMensStartTime;
curMensStartTime=re.getmusictime().toDouble();
curMens=getMensType(re.getEvent().getMensInfo());
if (curMens==MENS_O &&
((MensEvent)re.getEvent()).getSigns().size()>1 ||
((MensEvent)re.getEvent()).getMainSign().signType==MensSignElement.NUMBERS)
curMens=MENS_3;
break;
case Event.EVENT_PROPORTION:
curProp.multiply(((ProportionEvent)re.getEvent()).getproportion());
curPropVal=curProp.toDouble();
break;
}
renum++;
}
if (ne!=null)
{
/* discount final longa */
vad[i].numNotes[curMens]--;
vad[i].totalNumNotes--;
vad[i].totalNoteLengths[curMens]-=ne.getmusictime().toDouble()*curPropVal;
vad[i].totalPassageLengths[curMens]+=rne.getmusictime().toDouble()-curMensStartTime;
}
}
}
if (totalUnpreparedSBDiss>0)
outp.println();
for (int i=0; i<numVoices; i++)
{
outp.println("Voice "+(i+1)+": "+musicData.getVoiceData()[i].getName());
outp.println(" Range: "+vad[i].lowestPitch+" - "+vad[i].highestPitch);
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
if (vad[i].numNotes[mi]!=0)
{
outp.println(" Mensuration type: "+MENSURATION_NAMES[mi]);
outp.println(" Number of notes (not including final): "+vad[i].numNotes[mi]);
outp.println(" Total note lengths: "+vad[i].totalNoteLengths[mi]);
vad[i].rhythmicDensity[mi]=vad[i].totalNoteLengths[mi]/(double)vad[i].numNotes[mi];
outp.println(" Rhythmic density: "+vad[i].rhythmicDensity[mi]);
}
vad[i].syncopationDensity=(double)vad[i].totalOffbeat/(double)vad[i].numNotesOC;
outp.println(" Number of syncopated notes: "+vad[i].totalOffbeat);
outp.println(" Syncopation density: "+vad[i].syncopationDensity);
outp.println();
}
/* averages of the top two voices */
avgRhythmicDensity=new double[] { 0,0,0,0 };
outp.println();
outp.println("Averages for highest "+NUMVOICES_FOR_RHYTHM_AVG+" voices");
for (int i=0; i<numVoices && i<NUMVOICES_FOR_RHYTHM_AVG; i++)
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
if (vad[i].numNotes[mi]>0)
avgRhythmicDensity[mi]+=vad[i].rhythmicDensity[mi]/2; // for SB, not minims
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
{
if (numVoices>NUMVOICES_FOR_RHYTHM_AVG-1)
avgRhythmicDensity[mi]/=(double)NUMVOICES_FOR_RHYTHM_AVG;
if (avgRhythmicDensity[mi]>0)
outp.println(" Rhythmic density in SB ("+MENSURATION_NAMES[mi]+"): "+
avgRhythmicDensity[mi]);
}
avgSyncopationDensity=0;
for (int i=0; i<numVoices && i<NUMVOICES_FOR_RHYTHM_AVG; i++)
avgSyncopationDensity+=vad[i].syncopationDensity;
if (numVoices>NUMVOICES_FOR_RHYTHM_AVG-1)
avgSyncopationDensity/=(double)NUMVOICES_FOR_RHYTHM_AVG;
outp.println(" Syncopation density: "+avgSyncopationDensity);
if (totalUnpreparedSBDiss>0)
outp.println("Number of unprepared syncopated SB/M dissonances: "+totalUnpreparedSBDiss);
outp.println("Number of passing dissonant SM pairs: "+totalPassingDissSMPair);
outp.println("Number of dissonant offbeat Ms: "+totalOffbeatDissM);
double avgMensLengths[]=new double[] { 0,0,0,0 };
for (int i=0; i<numVoices; i++)
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
avgMensLengths[mi]+=vad[i].totalPassageLengths[mi];
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
avgMensLengths[mi]/=(double)numVoices;
OCLength=(avgMensLengths[MENS_O]+avgMensLengths[MENS_C])/2; /* in SB */
passingSMDissDensity=totalPassingDissSMPair/OCLength;
offbeatMDissDensity=totalOffbeatDissM/OCLength;
dissDensity=(totalPassingDissSMPair+totalOffbeatDissM)/OCLength;
outp.println("Total length of O/C sections: "+OCLength);
outp.println("Passing dissonant SM pair density: "+passingSMDissDensity);
outp.println("Offbeat dissonant M density: "+offbeatMDissDensity);
// outp.println("Basic dissonance density: "+dissDensity);
}
| public void printGeneralAnalysis(PrintStream outp)
{
outp.println("General analysis: "+musicData.getComposer()+", "+musicData.getFullTitle());
outp.println();
outp.println("Number of voices: "+numVoices);
outp.println("Number of sections: "+renderedSections.length);
outp.println();
vad=new VoiceAnalysisData[numVoices];
for (int i=0; i<numVoices; i++)
{
vad[i]=new VoiceAnalysisData();
vad[i].vData=musicData.getVoiceData()[i];
}
totalUnpreparedSBDiss=0;
totalPassingDissSMPair=0;
for (ScoreRenderer s : renderedSections)
{
for (int i=0; i<s.getNumVoices(); i++)
{
int curMens=MENS_C;
Proportion curProp=new Proportion(Proportion.EQUALITY);
double curPropVal=curProp.toDouble(),
curMensStartTime=0;
RenderList rl=s.getRenderedVoice(i);
if (rl==null)
break;
int vnum=-1;
for (int i1=0; i1<numVoices; i1++)
if (rl.getVoiceData()==vad[i1].vData)
vnum=i1;
NoteEvent ne=null;
RenderedEvent rne=null;
int renum=0;
for (RenderedEvent re : rl)
{
switch (re.getEvent().geteventtype())
{
case Event.EVENT_NOTE:
ne=(NoteEvent)re.getEvent();
rne=re;
vad[i].numNotes[curMens]++;
vad[i].totalNumNotes++;
vad[i].totalNoteLengths[curMens]+=ne.getmusictime().toDouble()*curPropVal;
if (ne.getPitch().isLowerThan(vad[i].lowestPitch))
vad[i].lowestPitch=ne.getPitch();
if (ne.getPitch().isHigherThan(vad[i].highestPitch))
vad[i].highestPitch=ne.getPitch();
if (curMens!=MENS_3 &&
curMens!=MENS_P)
{
vad[i].numNotesOC++;
if (syncopated(s,re))
vad[i].totalOffbeat++;
if (isUnpreparedSuspension(s,re))
{
totalUnpreparedSBDiss++;
outp.println("Unprepared SB/M dissonance in m. "+(re.getmeasurenum()+1));
}
if (isPassingDissonantSMPair(s,i,renum))
totalPassingDissSMPair++;
if (isOffbeatDissonantM(s,re))
totalOffbeatDissM++;
}
break;
case Event.EVENT_MULTIEVENT:
// to be implemented
Mensuration m=re.getEvent().getMensInfo();
if (m!=null)
curMens=getMensType(m);
break;
case Event.EVENT_MENS:
vad[i].totalPassageLengths[curMens]+=re.getmusictime().toDouble()-curMensStartTime;
curMensStartTime=re.getmusictime().toDouble();
curMens=getMensType(re.getEvent().getMensInfo());
if (curMens==MENS_O &&
((MensEvent)re.getEvent()).getSigns().size()>1 ||
((MensEvent)re.getEvent()).getMainSign().signType==MensSignElement.NUMBERS)
curMens=MENS_3;
break;
case Event.EVENT_PROPORTION:
curProp.multiply(((ProportionEvent)re.getEvent()).getproportion());
curPropVal=curProp.toDouble();
break;
}
renum++;
}
if (ne!=null)
{
/* discount final longa */
vad[i].numNotes[curMens]--;
vad[i].totalNumNotes--;
vad[i].totalNoteLengths[curMens]-=ne.getmusictime().toDouble()*curPropVal;
vad[i].totalPassageLengths[curMens]+=rne.getmusictime().toDouble()-curMensStartTime;
}
}
}
if (totalUnpreparedSBDiss>0)
outp.println();
for (int i=0; i<numVoices; i++)
{
outp.println("Voice "+(i+1)+": "+musicData.getVoiceData()[i].getName());
outp.println(" Range: "+vad[i].lowestPitch+" - "+vad[i].highestPitch);
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
if (vad[i].numNotes[mi]!=0)
{
outp.println(" Mensuration type: "+MENSURATION_NAMES[mi]);
outp.println(" Number of notes (not including final): "+vad[i].numNotes[mi]);
outp.println(" Total note lengths: "+vad[i].totalNoteLengths[mi]);
vad[i].rhythmicDensity[mi]=vad[i].totalNoteLengths[mi]/(double)vad[i].numNotes[mi];
outp.println(" Rhythmic density: "+vad[i].rhythmicDensity[mi]);
}
vad[i].syncopationDensity=(double)vad[i].totalOffbeat/(double)vad[i].numNotesOC;
outp.println(" Number of syncopated notes: "+vad[i].totalOffbeat);
outp.println(" Syncopation density: "+vad[i].syncopationDensity);
outp.println();
}
/* averages of the top two voices */
avgRhythmicDensity=new double[] { 0,0,0,0 };
outp.println();
outp.println("Averages for highest "+NUMVOICES_FOR_RHYTHM_AVG+" voices");
for (int i=0; i<numVoices && i<NUMVOICES_FOR_RHYTHM_AVG; i++)
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
if (vad[i].numNotes[mi]>0)
avgRhythmicDensity[mi]+=vad[i].rhythmicDensity[mi]/2; // for SB, not minims
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
{
if (numVoices>NUMVOICES_FOR_RHYTHM_AVG-1)
avgRhythmicDensity[mi]/=(double)NUMVOICES_FOR_RHYTHM_AVG;
if (avgRhythmicDensity[mi]>0)
outp.println(" Rhythmic density in SB ("+MENSURATION_NAMES[mi]+"): "+
avgRhythmicDensity[mi]);
}
avgSyncopationDensity=0;
for (int i=0; i<numVoices && i<NUMVOICES_FOR_RHYTHM_AVG; i++)
avgSyncopationDensity+=vad[i].syncopationDensity;
if (numVoices>NUMVOICES_FOR_RHYTHM_AVG-1)
avgSyncopationDensity/=(double)NUMVOICES_FOR_RHYTHM_AVG;
outp.println(" Syncopation density: "+avgSyncopationDensity);
if (totalUnpreparedSBDiss>0)
outp.println("Number of unprepared syncopated SB/M dissonances: "+totalUnpreparedSBDiss);
outp.println("Number of passing dissonant SM pairs: "+totalPassingDissSMPair);
outp.println("Number of dissonant offbeat Ms: "+totalOffbeatDissM);
double avgMensLengths[]=new double[] { 0,0,0,0 };
for (int i=0; i<numVoices; i++)
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
avgMensLengths[mi]+=vad[i].totalPassageLengths[mi];
for (int mi=0; mi<NUM_MENSURATIONS; mi++)
avgMensLengths[mi]/=(double)numVoices;
OCLength=(avgMensLengths[MENS_O]+avgMensLengths[MENS_C])/2; /* in SB */
passingSMDissDensity=totalPassingDissSMPair/OCLength;
offbeatMDissDensity=totalOffbeatDissM/OCLength;
dissDensity=(totalPassingDissSMPair+totalOffbeatDissM)/OCLength;
outp.println("Total length of O/C sections: "+OCLength);
outp.println("Passing dissonant SM pair density: "+passingSMDissDensity);
outp.println("Offbeat dissonant M density: "+offbeatMDissDensity);
// outp.println("Basic dissonance density: "+dissDensity);
}
|
diff --git a/eu/icecraft/iceban/commands/BanCommands.java b/eu/icecraft/iceban/commands/BanCommands.java
index 8dc789a..a8c3c56 100644
--- a/eu/icecraft/iceban/commands/BanCommands.java
+++ b/eu/icecraft/iceban/commands/BanCommands.java
@@ -1,130 +1,130 @@
package eu.icecraft.iceban.commands;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import eu.icecraft.iceban.BanInfo;
import eu.icecraft.iceban.BanInfo.BanType;
import eu.icecraft.iceban.IceBan;
import eu.icecraft.iceban.Utils;
public class BanCommands implements CommandExecutor {
public IceBan plugin;
public Pattern timePattern;
public BanCommands(IceBan iceBan) {
this.plugin = iceBan;
timePattern = Pattern.compile("^(.+?) (.+?) \\-t (.+?)$");
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String cmdLbl, String[] args) {
if(!sender.hasPermission("iceban." + cmdLbl)) return false;
if(cmdLbl.equals("ban") || cmdLbl.equals("sbh")) {
boolean forceBan = false;
boolean permanent = false;
boolean silent = false;
String nick = "";
String reason = "";
String time = "";
String allArgs = "";
for (String word : args) {
if(word.equals("-f")) { forceBan = true; continue; }
if(word.equals("-p")) { permanent = true; continue; }
if(word.equals("-s")) { silent = true; continue; }
allArgs = allArgs + " " + word;
}
Matcher m = timePattern.matcher(allArgs);
if (m.find() && !permanent) {
nick = m.group(1).trim(); // nick
reason = m.group(2).trim(); // reason
time = m.group(3).trim(); // time
} else {
nick = args[0];
int i = 0;
for (String word : args) {
i++;
if(i == 1 || word.equals("-f") || word.equals("-p") || word.equals("-s")) continue;
reason = reason + " " + word;
}
reason = reason.trim();
if(!sender.hasPermission("iceban.longbans")) time = "1d";
else time = "30d";
}
int banTime;
if(sender.hasPermission("iceban.permabans") && permanent) banTime = 0;
else {
banTime = Utils.parseTimeSpec(time.trim()) * 60;
if(banTime < 0) {
sender.sendMessage(ChatColor.RED + "Invalid time string!");
return true;
}
if(!sender.hasPermission("iceban.longbans") && banTime > 86400) {
- sender.sendMessage(ChatColor.RED + "Ban lenght was above your limit, setting to 1 day");
+ sender.sendMessage(ChatColor.RED + "Ban length was above your limit, setting to 1 day");
banTime = 86400;
}
banTime += (int) (System.currentTimeMillis() / 1000L);
}
if(reason.equals("") || reason.startsWith("-t") || reason.startsWith("-s") || reason.startsWith("-f") || reason.startsWith("-p")) {
sender.sendMessage(ChatColor.RED + "Invalid reason.");
return true;
}
String ip = plugin.iceAuth.getIP(nick);
if(ip == null && !forceBan) {
sender.sendMessage(ChatColor.RED + "Player IP not found in history! Use -f to override");
return true;
}
BanInfo oldBan = plugin.getNameBan(nick.toLowerCase());
if(oldBan.getBanType() != BanType.NOT_BANNED) {
sender.sendMessage(ChatColor.RED + "Player has previous active bans, marking them as past.");
plugin.unban(oldBan);
}
plugin.sql.ban(nick, ip, banTime, reason, sender.getName());
BanInfo newBan = plugin.getNameBan(nick.toLowerCase());
for(Player currPlayer : Bukkit.getServer().getOnlinePlayers()) {
if(currPlayer.getName().equalsIgnoreCase(nick)) currPlayer.kickPlayer(plugin.getKickMessage(newBan));
- if(!silent || !currPlayer.isOp()) sender.sendMessage(ChatColor.RED + "IceBan: " + ChatColor.AQUA + nick + " was banned by " + sender.getName());
+ if(!silent || !currPlayer.isOp()) currPlayer.sendMessage(ChatColor.RED + "IceBan: " + ChatColor.AQUA + nick + " was banned by " + sender.getName());
}
System.out.println(sender.getName() + " banned " + nick + " with reason " + reason + " for " + (permanent ? "a long time" : time) + " ban id: " + newBan.getBanID());
sender.sendMessage(ChatColor.GREEN + "Banned " + nick + " with reason " + reason + " for " + (permanent ? "a long time" : time) + " ban id: " + newBan.getBanID());
return true;
}
if(cmdLbl.equals("unban") || cmdLbl.equals("sunban")) {
BanInfo ban = plugin.getNameBan(args[0]);
if(ban.isNameBanned()) {
plugin.unban(ban);
sender.sendMessage(ChatColor.GOLD + "Player " + ChatColor.GRAY + args[0] + ChatColor.GOLD + " unbanned sucessfully.");
} else {
sender.sendMessage(ChatColor.GOLD + "Player " + ChatColor.GRAY + args[0] + ChatColor.GOLD + " isn't banned.");
}
return true;
}
return false;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String cmdLbl, String[] args) {
if(!sender.hasPermission("iceban." + cmdLbl)) return false;
if(cmdLbl.equals("ban") || cmdLbl.equals("sbh")) {
boolean forceBan = false;
boolean permanent = false;
boolean silent = false;
String nick = "";
String reason = "";
String time = "";
String allArgs = "";
for (String word : args) {
if(word.equals("-f")) { forceBan = true; continue; }
if(word.equals("-p")) { permanent = true; continue; }
if(word.equals("-s")) { silent = true; continue; }
allArgs = allArgs + " " + word;
}
Matcher m = timePattern.matcher(allArgs);
if (m.find() && !permanent) {
nick = m.group(1).trim(); // nick
reason = m.group(2).trim(); // reason
time = m.group(3).trim(); // time
} else {
nick = args[0];
int i = 0;
for (String word : args) {
i++;
if(i == 1 || word.equals("-f") || word.equals("-p") || word.equals("-s")) continue;
reason = reason + " " + word;
}
reason = reason.trim();
if(!sender.hasPermission("iceban.longbans")) time = "1d";
else time = "30d";
}
int banTime;
if(sender.hasPermission("iceban.permabans") && permanent) banTime = 0;
else {
banTime = Utils.parseTimeSpec(time.trim()) * 60;
if(banTime < 0) {
sender.sendMessage(ChatColor.RED + "Invalid time string!");
return true;
}
if(!sender.hasPermission("iceban.longbans") && banTime > 86400) {
sender.sendMessage(ChatColor.RED + "Ban lenght was above your limit, setting to 1 day");
banTime = 86400;
}
banTime += (int) (System.currentTimeMillis() / 1000L);
}
if(reason.equals("") || reason.startsWith("-t") || reason.startsWith("-s") || reason.startsWith("-f") || reason.startsWith("-p")) {
sender.sendMessage(ChatColor.RED + "Invalid reason.");
return true;
}
String ip = plugin.iceAuth.getIP(nick);
if(ip == null && !forceBan) {
sender.sendMessage(ChatColor.RED + "Player IP not found in history! Use -f to override");
return true;
}
BanInfo oldBan = plugin.getNameBan(nick.toLowerCase());
if(oldBan.getBanType() != BanType.NOT_BANNED) {
sender.sendMessage(ChatColor.RED + "Player has previous active bans, marking them as past.");
plugin.unban(oldBan);
}
plugin.sql.ban(nick, ip, banTime, reason, sender.getName());
BanInfo newBan = plugin.getNameBan(nick.toLowerCase());
for(Player currPlayer : Bukkit.getServer().getOnlinePlayers()) {
if(currPlayer.getName().equalsIgnoreCase(nick)) currPlayer.kickPlayer(plugin.getKickMessage(newBan));
if(!silent || !currPlayer.isOp()) sender.sendMessage(ChatColor.RED + "IceBan: " + ChatColor.AQUA + nick + " was banned by " + sender.getName());
}
System.out.println(sender.getName() + " banned " + nick + " with reason " + reason + " for " + (permanent ? "a long time" : time) + " ban id: " + newBan.getBanID());
sender.sendMessage(ChatColor.GREEN + "Banned " + nick + " with reason " + reason + " for " + (permanent ? "a long time" : time) + " ban id: " + newBan.getBanID());
return true;
}
if(cmdLbl.equals("unban") || cmdLbl.equals("sunban")) {
BanInfo ban = plugin.getNameBan(args[0]);
if(ban.isNameBanned()) {
plugin.unban(ban);
sender.sendMessage(ChatColor.GOLD + "Player " + ChatColor.GRAY + args[0] + ChatColor.GOLD + " unbanned sucessfully.");
} else {
sender.sendMessage(ChatColor.GOLD + "Player " + ChatColor.GRAY + args[0] + ChatColor.GOLD + " isn't banned.");
}
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String cmdLbl, String[] args) {
if(!sender.hasPermission("iceban." + cmdLbl)) return false;
if(cmdLbl.equals("ban") || cmdLbl.equals("sbh")) {
boolean forceBan = false;
boolean permanent = false;
boolean silent = false;
String nick = "";
String reason = "";
String time = "";
String allArgs = "";
for (String word : args) {
if(word.equals("-f")) { forceBan = true; continue; }
if(word.equals("-p")) { permanent = true; continue; }
if(word.equals("-s")) { silent = true; continue; }
allArgs = allArgs + " " + word;
}
Matcher m = timePattern.matcher(allArgs);
if (m.find() && !permanent) {
nick = m.group(1).trim(); // nick
reason = m.group(2).trim(); // reason
time = m.group(3).trim(); // time
} else {
nick = args[0];
int i = 0;
for (String word : args) {
i++;
if(i == 1 || word.equals("-f") || word.equals("-p") || word.equals("-s")) continue;
reason = reason + " " + word;
}
reason = reason.trim();
if(!sender.hasPermission("iceban.longbans")) time = "1d";
else time = "30d";
}
int banTime;
if(sender.hasPermission("iceban.permabans") && permanent) banTime = 0;
else {
banTime = Utils.parseTimeSpec(time.trim()) * 60;
if(banTime < 0) {
sender.sendMessage(ChatColor.RED + "Invalid time string!");
return true;
}
if(!sender.hasPermission("iceban.longbans") && banTime > 86400) {
sender.sendMessage(ChatColor.RED + "Ban length was above your limit, setting to 1 day");
banTime = 86400;
}
banTime += (int) (System.currentTimeMillis() / 1000L);
}
if(reason.equals("") || reason.startsWith("-t") || reason.startsWith("-s") || reason.startsWith("-f") || reason.startsWith("-p")) {
sender.sendMessage(ChatColor.RED + "Invalid reason.");
return true;
}
String ip = plugin.iceAuth.getIP(nick);
if(ip == null && !forceBan) {
sender.sendMessage(ChatColor.RED + "Player IP not found in history! Use -f to override");
return true;
}
BanInfo oldBan = plugin.getNameBan(nick.toLowerCase());
if(oldBan.getBanType() != BanType.NOT_BANNED) {
sender.sendMessage(ChatColor.RED + "Player has previous active bans, marking them as past.");
plugin.unban(oldBan);
}
plugin.sql.ban(nick, ip, banTime, reason, sender.getName());
BanInfo newBan = plugin.getNameBan(nick.toLowerCase());
for(Player currPlayer : Bukkit.getServer().getOnlinePlayers()) {
if(currPlayer.getName().equalsIgnoreCase(nick)) currPlayer.kickPlayer(plugin.getKickMessage(newBan));
if(!silent || !currPlayer.isOp()) currPlayer.sendMessage(ChatColor.RED + "IceBan: " + ChatColor.AQUA + nick + " was banned by " + sender.getName());
}
System.out.println(sender.getName() + " banned " + nick + " with reason " + reason + " for " + (permanent ? "a long time" : time) + " ban id: " + newBan.getBanID());
sender.sendMessage(ChatColor.GREEN + "Banned " + nick + " with reason " + reason + " for " + (permanent ? "a long time" : time) + " ban id: " + newBan.getBanID());
return true;
}
if(cmdLbl.equals("unban") || cmdLbl.equals("sunban")) {
BanInfo ban = plugin.getNameBan(args[0]);
if(ban.isNameBanned()) {
plugin.unban(ban);
sender.sendMessage(ChatColor.GOLD + "Player " + ChatColor.GRAY + args[0] + ChatColor.GOLD + " unbanned sucessfully.");
} else {
sender.sendMessage(ChatColor.GOLD + "Player " + ChatColor.GRAY + args[0] + ChatColor.GOLD + " isn't banned.");
}
return true;
}
return false;
}
|
diff --git a/src/com/warrows/plugins/TreeSpirit/PlayerMoveListener.java b/src/com/warrows/plugins/TreeSpirit/PlayerMoveListener.java
index e760882..b72d242 100644
--- a/src/com/warrows/plugins/TreeSpirit/PlayerMoveListener.java
+++ b/src/com/warrows/plugins/TreeSpirit/PlayerMoveListener.java
@@ -1,25 +1,27 @@
package com.warrows.plugins.TreeSpirit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
public class PlayerMoveListener implements Listener
{
@EventHandler(ignoreCancelled = true)
public void onPlayerMoveEvent(PlayerMoveEvent event)
{
Player player = event.getPlayer();
GreatTree tree = TreeSpiritPlugin.getGreatTree(player);
+ if (tree == null)
+ return;
if (tree.isAtProximity(event.getTo().getBlock()))
{
} else
{
event.setCancelled(true);
}
}
}
| true | true | public void onPlayerMoveEvent(PlayerMoveEvent event)
{
Player player = event.getPlayer();
GreatTree tree = TreeSpiritPlugin.getGreatTree(player);
if (tree.isAtProximity(event.getTo().getBlock()))
{
} else
{
event.setCancelled(true);
}
}
| public void onPlayerMoveEvent(PlayerMoveEvent event)
{
Player player = event.getPlayer();
GreatTree tree = TreeSpiritPlugin.getGreatTree(player);
if (tree == null)
return;
if (tree.isAtProximity(event.getTo().getBlock()))
{
} else
{
event.setCancelled(true);
}
}
|
diff --git a/src/testopia/API/Lookup.java b/src/testopia/API/Lookup.java
index 283ad6b..29a2b1b 100644
--- a/src/testopia/API/Lookup.java
+++ b/src/testopia/API/Lookup.java
@@ -1,156 +1,156 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Bugzilla Testopia Java API.
*
* The Initial Developer of the Original Code is Andrew Nelson.
* Portions created by Andrew Nelson are Copyright (C) 2006
* Novell. All Rights Reserved.
*
* Contributor(s): Andrew Nelson <[email protected]>
*
*/
package testopia.API;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Map.Entry;
public class Lookup {
public static URL url;
public static void main(String args[]) throws Exception
{
//declare variables
url = new URL("https://testopia-01.lab.bos.redhat.com/bugzilla/tr_xmlrpc.cgi");
//get username and password
System.out.println("Welcome to Testopia Lookup tool 1.0");
StringBuilder command = new StringBuilder();
StringBuilder object = new StringBuilder();
System.out.println("Please Eneter your bugzilla username");
StringBuilder userNameStringBuilder = new StringBuilder();
processInput(userNameStringBuilder, null, null);
System.out.println("Please enter your bugzilla password");
StringBuilder passwordStringBuilder = new StringBuilder();
processInput(passwordStringBuilder, null, null);
System.out.println("You may now enter a command query");
System.out.println("To see a list of supported queries, please");
System.out.println("read the lookupHelp.txt");
//begin query loop
String username = userNameStringBuilder.toString();
String password = passwordStringBuilder.toString();
StringBuilder secondObject;
Session session = new Session(username, password, url);
session.login();
while(true)
{
command = new StringBuilder();
object = new StringBuilder();
secondObject = new StringBuilder();
//get input from console
processInput(command, object, null);
System.out.println("Query Result:");
if(command.toString().equals("build"))
{
Build build = new Build(session);
int buildId = build.getBuildIDByName(object.toString());
System.out.println(buildId);
}
else if(command.toString().equals("component"))
{
- TestPlan testPlan = new TestPlan(username, password, url, new Integer(object.toString()));
+ TestPlan testPlan = new TestPlan(session, new Integer(object.toString()));
Object[] objects = testPlan.getComponents();
for(Object o : objects)
System.out.println(o.toString());
}
else if(command.toString().equals("environmentByProduct"))
{
Environment environment = new Environment(username, password, url);
HashMap<String, Object> map = environment.listEnvironments(object.toString(), null);
System.out.println("Environment Name: " + map.get("name"));
System.out.println("Environment ID: " + map.get("environment_id"));
}
else if(command.toString().equals("environmentByName"))
{
Environment environment = new Environment(username, password, url);
HashMap<String, Object> map = environment.listEnvironments(object.toString(), null);
System.out.println("Environment Name: " + map.get("name"));
System.out.println("Environment ID: " + map.get("environment_id"));
}
else if(command.toString().equals("exit"))
{
System.out.println("Thanks For Using the Lookup Tool");
break;
}
else
{
System.out.println("unrecognized command");
}
System.out.println("You may now enter another command query, or type exit to exit");
}
}
/**
* Helper method to take input from console
* @param command - first parameter
* @param object - second parameter
*/
public static void processInput(StringBuilder command, StringBuilder object, StringBuilder secondObject)
{
InputStream in = System.in;
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringTokenizer token = null;
try {
token = new StringTokenizer(reader.readLine(), ":");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(token.hasMoreTokens())
command.append(token.nextToken());
if(token.hasMoreTokens() && object != null)
object.append(token.nextToken());
if(token.hasMoreTokens() && secondObject != null)
secondObject.append(token.nextToken());
}
}
| true | true | public static void main(String args[]) throws Exception
{
//declare variables
url = new URL("https://testopia-01.lab.bos.redhat.com/bugzilla/tr_xmlrpc.cgi");
//get username and password
System.out.println("Welcome to Testopia Lookup tool 1.0");
StringBuilder command = new StringBuilder();
StringBuilder object = new StringBuilder();
System.out.println("Please Eneter your bugzilla username");
StringBuilder userNameStringBuilder = new StringBuilder();
processInput(userNameStringBuilder, null, null);
System.out.println("Please enter your bugzilla password");
StringBuilder passwordStringBuilder = new StringBuilder();
processInput(passwordStringBuilder, null, null);
System.out.println("You may now enter a command query");
System.out.println("To see a list of supported queries, please");
System.out.println("read the lookupHelp.txt");
//begin query loop
String username = userNameStringBuilder.toString();
String password = passwordStringBuilder.toString();
StringBuilder secondObject;
Session session = new Session(username, password, url);
session.login();
while(true)
{
command = new StringBuilder();
object = new StringBuilder();
secondObject = new StringBuilder();
//get input from console
processInput(command, object, null);
System.out.println("Query Result:");
if(command.toString().equals("build"))
{
Build build = new Build(session);
int buildId = build.getBuildIDByName(object.toString());
System.out.println(buildId);
}
else if(command.toString().equals("component"))
{
TestPlan testPlan = new TestPlan(username, password, url, new Integer(object.toString()));
Object[] objects = testPlan.getComponents();
for(Object o : objects)
System.out.println(o.toString());
}
else if(command.toString().equals("environmentByProduct"))
{
Environment environment = new Environment(username, password, url);
HashMap<String, Object> map = environment.listEnvironments(object.toString(), null);
System.out.println("Environment Name: " + map.get("name"));
System.out.println("Environment ID: " + map.get("environment_id"));
}
else if(command.toString().equals("environmentByName"))
{
Environment environment = new Environment(username, password, url);
HashMap<String, Object> map = environment.listEnvironments(object.toString(), null);
System.out.println("Environment Name: " + map.get("name"));
System.out.println("Environment ID: " + map.get("environment_id"));
}
else if(command.toString().equals("exit"))
{
System.out.println("Thanks For Using the Lookup Tool");
break;
}
else
{
System.out.println("unrecognized command");
}
System.out.println("You may now enter another command query, or type exit to exit");
}
}
| public static void main(String args[]) throws Exception
{
//declare variables
url = new URL("https://testopia-01.lab.bos.redhat.com/bugzilla/tr_xmlrpc.cgi");
//get username and password
System.out.println("Welcome to Testopia Lookup tool 1.0");
StringBuilder command = new StringBuilder();
StringBuilder object = new StringBuilder();
System.out.println("Please Eneter your bugzilla username");
StringBuilder userNameStringBuilder = new StringBuilder();
processInput(userNameStringBuilder, null, null);
System.out.println("Please enter your bugzilla password");
StringBuilder passwordStringBuilder = new StringBuilder();
processInput(passwordStringBuilder, null, null);
System.out.println("You may now enter a command query");
System.out.println("To see a list of supported queries, please");
System.out.println("read the lookupHelp.txt");
//begin query loop
String username = userNameStringBuilder.toString();
String password = passwordStringBuilder.toString();
StringBuilder secondObject;
Session session = new Session(username, password, url);
session.login();
while(true)
{
command = new StringBuilder();
object = new StringBuilder();
secondObject = new StringBuilder();
//get input from console
processInput(command, object, null);
System.out.println("Query Result:");
if(command.toString().equals("build"))
{
Build build = new Build(session);
int buildId = build.getBuildIDByName(object.toString());
System.out.println(buildId);
}
else if(command.toString().equals("component"))
{
TestPlan testPlan = new TestPlan(session, new Integer(object.toString()));
Object[] objects = testPlan.getComponents();
for(Object o : objects)
System.out.println(o.toString());
}
else if(command.toString().equals("environmentByProduct"))
{
Environment environment = new Environment(username, password, url);
HashMap<String, Object> map = environment.listEnvironments(object.toString(), null);
System.out.println("Environment Name: " + map.get("name"));
System.out.println("Environment ID: " + map.get("environment_id"));
}
else if(command.toString().equals("environmentByName"))
{
Environment environment = new Environment(username, password, url);
HashMap<String, Object> map = environment.listEnvironments(object.toString(), null);
System.out.println("Environment Name: " + map.get("name"));
System.out.println("Environment ID: " + map.get("environment_id"));
}
else if(command.toString().equals("exit"))
{
System.out.println("Thanks For Using the Lookup Tool");
break;
}
else
{
System.out.println("unrecognized command");
}
System.out.println("You may now enter another command query, or type exit to exit");
}
}
|
diff --git a/src/main/java/org/apache/hadoop/mapred/MesosScheduler.java b/src/main/java/org/apache/hadoop/mapred/MesosScheduler.java
index e5894e9..6b3583a 100644
--- a/src/main/java/org/apache/hadoop/mapred/MesosScheduler.java
+++ b/src/main/java/org/apache/hadoop/mapred/MesosScheduler.java
@@ -1,996 +1,996 @@
package org.apache.hadoop.mapred;
import com.google.protobuf.ByteString;
import org.apache.commons.httpclient.HttpHost;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.TaskType;
import org.apache.hadoop.mapreduce.server.jobtracker.TaskTracker;
import org.apache.hadoop.mapreduce.TaskType;
import org.apache.mesos.MesosSchedulerDriver;
import org.apache.mesos.Protos;
import org.apache.mesos.Protos.*;
import org.apache.mesos.Protos.TaskID;
import org.apache.mesos.Scheduler;
import org.apache.mesos.SchedulerDriver;
import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static org.apache.hadoop.util.StringUtils.join;
public class MesosScheduler extends TaskScheduler implements Scheduler {
public static final Log LOG = LogFactory.getLog(MesosScheduler.class);
// This is the memory overhead for a jvm process. This needs to be added
// to a jvm process's resource requirement, in addition to its heap size.
private static final double JVM_MEM_OVERHEAD_PERCENT_DEFAULT = 0.1; // 10%.
// NOTE: It appears that there's no real resource requirements for a
// map / reduce slot. We therefore define a default slot as:
// 1 cores.
// 1024 MB memory.
// 1 GB of disk space.
private static final double SLOT_CPUS_DEFAULT = 1; // 1 cores.
private static final int SLOT_DISK_DEFAULT = 1024; // 1 GB.
private static final int SLOT_JVM_HEAP_DEFAULT = 1024; // 1024MB.
private static final double TASKTRACKER_CPUS = 1.0; // 1 core.
private static final int TASKTRACKER_MEM_DEFAULT = 1024; // 1 GB.
// The default behavior in Hadoop is to use 4 slots per TaskTracker:
private static final int MAP_SLOTS_DEFAULT = 2;
private static final int REDUCE_SLOTS_DEFAULT = 2;
// The amount of time to wait for task trackers to launch before
// giving up.
private static final long LAUNCH_TIMEOUT_MS = 300000; // 5 minutes
private SchedulerDriver driver;
private TaskScheduler taskScheduler;
private JobTracker jobTracker;
private Configuration conf;
private File stateFile;
// Count of the launched trackers for TaskID generation.
private long launchedTrackers = 0;
// Use a fixed slot allocation policy?
private boolean policyIsFixed = false;
private ResourcePolicy policy;
// Maintains a mapping from {tracker host:port -> MesosTracker}.
// Used for tracking the slots of each TaskTracker and the corresponding
// Mesos TaskID.
private Map<HttpHost, MesosTracker> mesosTrackers =
new ConcurrentHashMap<HttpHost, MesosTracker>();
private JobInProgressListener jobListener = new JobInProgressListener() {
@Override
public void jobAdded(JobInProgress job) throws IOException {
LOG.info("Added job " + job.getJobID());
}
@Override
public void jobRemoved(JobInProgress job) {
LOG.info("Removed job " + job.getJobID());
}
@Override
public void jobUpdated(JobChangeEvent event) {
synchronized (MesosScheduler.this) {
JobInProgress job = event.getJobInProgress();
// If we have flaky tasktrackers, kill them.
final List<String> flakyTrackers = job.getBlackListedTrackers();
// Remove the task from the map. This is O(n^2), but there's no better
// way to do it, AFAIK. The flakyTrackers list should usually be
// small, so this is probably not bad.
for (String hostname : flakyTrackers) {
for (MesosTracker mesosTracker : mesosTrackers.values()) {
if (mesosTracker.host.getHostName().startsWith(hostname)) {
LOG.info("Killing Mesos task: " + mesosTracker.taskId + " on host "
+ mesosTracker.host + " because it has been marked as flaky");
killTracker(mesosTracker);
}
}
}
// If the job is complete, kill all the corresponding idle TaskTrackers.
if (!job.isComplete()) {
return;
}
LOG.info("Completed job : " + job.getJobID());
// Remove the task from the map.
final Set<HttpHost> trackers = new HashSet<HttpHost>(mesosTrackers.keySet());
for (HttpHost tracker : trackers) {
MesosTracker mesosTracker = mesosTrackers.get(tracker);
mesosTracker.jobs.remove(job.getJobID());
// If the TaskTracker doesn't have any running tasks, kill it.
if (mesosTracker.jobs.isEmpty() && mesosTracker.active) {
LOG.info("Killing Mesos task: " + mesosTracker.taskId + " on host "
+ mesosTracker.host + " because it is no longer needed");
killTracker(mesosTracker);
}
}
}
}
};
public MesosScheduler() {
}
// TaskScheduler methods.
@Override
public synchronized void start() throws IOException {
conf = getConf();
String taskTrackerClass = conf.get("mapred.mesos.taskScheduler",
"org.apache.hadoop.mapred.JobQueueTaskScheduler");
try {
taskScheduler =
(TaskScheduler) Class.forName(taskTrackerClass).newInstance();
taskScheduler.setConf(conf);
taskScheduler.setTaskTrackerManager(taskTrackerManager);
} catch (ClassNotFoundException e) {
LOG.fatal("Failed to initialize the TaskScheduler", e);
System.exit(1);
} catch (InstantiationException e) {
LOG.fatal("Failed to initialize the TaskScheduler", e);
System.exit(1);
} catch (IllegalAccessException e) {
LOG.fatal("Failed to initialize the TaskScheduler", e);
System.exit(1);
}
// Add the job listener to get job related updates.
taskTrackerManager.addJobInProgressListener(jobListener);
LOG.info("Starting MesosScheduler");
jobTracker = (JobTracker) super.taskTrackerManager;
String master = conf.get("mapred.mesos.master", "local");
try {
FrameworkInfo frameworkInfo = FrameworkInfo
.newBuilder()
.setUser("") // Let Mesos fill in the user.
.setCheckpoint(conf.getBoolean("mapred.mesos.checkpoint", false))
.setRole(conf.get("mapred.mesos.role", "*"))
.setName("Hadoop: (RPC port: " + jobTracker.port + ","
+ " WebUI port: " + jobTracker.infoPort + ")").build();
driver = new MesosSchedulerDriver(this, frameworkInfo, master);
driver.start();
} catch (Exception e) {
// If the MesosScheduler can't be loaded, the JobTracker won't be useful
// at all, so crash it now so that the user notices.
LOG.fatal("Failed to start MesosScheduler", e);
System.exit(1);
}
String file = conf.get("mapred.mesos.state.file", "");
if (!file.equals("")) {
this.stateFile = new File(file);
}
policyIsFixed = conf.getBoolean("mapred.mesos.scheduler.policy.fixed",
policyIsFixed);
if (policyIsFixed) {
policy = new ResourcePolicyFixed(this);
} else {
policy = new ResourcePolicyVariable(this);
}
taskScheduler.start();
}
@Override
public synchronized void terminate() throws IOException {
try {
LOG.info("Stopping MesosScheduler");
driver.stop();
} catch (Exception e) {
LOG.error("Failed to stop Mesos scheduler", e);
}
taskScheduler.terminate();
}
@Override
public List<Task> assignTasks(TaskTracker taskTracker)
throws IOException {
HttpHost tracker = new HttpHost(taskTracker.getStatus().getHost(),
taskTracker.getStatus().getHttpPort());
// Let the underlying task scheduler do the actual task scheduling.
List<Task> tasks = taskScheduler.assignTasks(taskTracker);
// The Hadoop Fair Scheduler is known to return null.
if (tasks == null) {
return null;
}
// Keep track of which TaskTracker contains which tasks.
for (Task task : tasks) {
if (mesosTrackers.containsKey(tracker)) {
mesosTrackers.get(tracker).jobs.add(task.getJobID());
} else {
LOG.info("Unknown/exited TaskTracker: " + tracker + ". ");
}
}
return tasks;
}
@Override
public synchronized Collection<JobInProgress> getJobs(String queueName) {
return taskScheduler.getJobs(queueName);
}
@Override
public synchronized void refresh() throws IOException {
taskScheduler.refresh();
}
// Mesos Scheduler methods.
// These are synchronized, where possible. Some of these methods need to access the
// JobTracker, which can lead to a deadlock:
// See: https://issues.apache.org/jira/browse/MESOS-429
// The workaround employed here is to unsynchronize those methods needing access to
// the JobTracker state and use explicit synchronization instead as appropriate.
// TODO(bmahler): Provide a cleaner solution to this issue. One solution is to
// split up the Scheduler and TaskScheduler implementations in order to break the
// locking cycle. This would require a synchronized class to store the shared
// state across our Scheduler and TaskScheduler implementations, and provide
// atomic operations as needed.
@Override
public synchronized void registered(SchedulerDriver schedulerDriver,
FrameworkID frameworkID, MasterInfo masterInfo) {
LOG.info("Registered as " + frameworkID.getValue()
+ " with master " + masterInfo);
}
@Override
public synchronized void reregistered(SchedulerDriver schedulerDriver,
MasterInfo masterInfo) {
LOG.info("Re-registered with master " + masterInfo);
}
public synchronized void killTracker(MesosTracker tracker) {
driver.killTask(tracker.taskId);
mesosTrackers.remove(tracker.host);
}
// For some reason, pendingMaps() and pendingReduces() doesn't return the
// values we expect. We observed negative values, which may be related to
// https://issues.apache.org/jira/browse/MAPREDUCE-1238. Below is the
// algorithm that is used to calculate the pending tasks within the Hadoop
// JobTracker sources (see 'printTaskSummary' in
// src/org/apache/hadoop/mapred/jobdetails_jsp.java).
private int getPendingTasks(TaskInProgress[] tasks) {
int totalTasks = tasks.length;
int runningTasks = 0;
int finishedTasks = 0;
int killedTasks = 0;
for (int i = 0; i < totalTasks; ++i) {
TaskInProgress task = tasks[i];
if (task == null) {
continue;
}
if (task.isComplete()) {
finishedTasks += 1;
} else if (task.isRunning()) {
runningTasks += 1;
} else if (task.wasKilled()) {
killedTasks += 1;
}
}
int pendingTasks = totalTasks - runningTasks - killedTasks - finishedTasks;
return pendingTasks;
}
// This method uses explicit synchronization in order to avoid deadlocks when
// accessing the JobTracker.
@Override
public void resourceOffers(SchedulerDriver schedulerDriver,
List<Offer> offers) {
policy.resourceOffers(schedulerDriver, offers);
}
@Override
public synchronized void offerRescinded(SchedulerDriver schedulerDriver,
OfferID offerID) {
LOG.warn("Rescinded offer: " + offerID.getValue());
}
@Override
public synchronized void statusUpdate(SchedulerDriver schedulerDriver,
Protos.TaskStatus taskStatus) {
LOG.info("Status update of " + taskStatus.getTaskId().getValue()
+ " to " + taskStatus.getState().name()
+ " with message " + taskStatus.getMessage());
// Remove the TaskTracker if the corresponding Mesos task has reached a
// terminal state.
switch (taskStatus.getState()) {
case TASK_FINISHED:
case TASK_FAILED:
case TASK_KILLED:
case TASK_LOST:
// Make a copy to iterate over keys and delete values.
Set<HttpHost> trackers = new HashSet<HttpHost>(mesosTrackers.keySet());
// Remove the task from the map.
for (HttpHost tracker : trackers) {
if (mesosTrackers.get(tracker).taskId.equals(taskStatus.getTaskId())) {
LOG.info("Removing terminated TaskTracker: " + tracker);
mesosTrackers.get(tracker).timer.cancel();
mesosTrackers.remove(tracker);
}
}
break;
case TASK_STAGING:
case TASK_STARTING:
case TASK_RUNNING:
break;
default:
LOG.error("Unexpected TaskStatus: " + taskStatus.getState().name());
break;
}
}
@Override
public synchronized void frameworkMessage(SchedulerDriver schedulerDriver,
ExecutorID executorID, SlaveID slaveID, byte[] bytes) {
LOG.info("Framework Message of " + bytes.length + " bytes"
+ " from executor " + executorID.getValue()
+ " on slave " + slaveID.getValue());
}
@Override
public synchronized void disconnected(SchedulerDriver schedulerDriver) {
LOG.warn("Disconnected from Mesos master.");
}
@Override
public synchronized void slaveLost(SchedulerDriver schedulerDriver,
SlaveID slaveID) {
LOG.warn("Slave lost: " + slaveID.getValue());
}
@Override
public synchronized void executorLost(SchedulerDriver schedulerDriver,
ExecutorID executorID, SlaveID slaveID, int status) {
LOG.warn("Executor " + executorID.getValue()
+ " lost with status " + status + " on slave " + slaveID);
}
@Override
public synchronized void error(SchedulerDriver schedulerDriver, String s) {
LOG.error("Error from scheduler driver: " + s);
}
private class ResourcePolicy {
public volatile MesosScheduler scheduler;
public int neededMapSlots;
public int neededReduceSlots;
public long slots, mapSlots, reduceSlots;
public int mapSlotsMax, reduceSlotsMax;
double slotCpus;
double slotDisk;
int slotMem;
long slotJVMHeap;
int tasktrackerMem;
long tasktrackerJVMHeap;
// Minimum resource requirements for the container (TaskTracker + map/red
// tasks).
double containerCpus;
double containerMem;
double containerDisk;
double cpus;
double mem;
double disk;
public ResourcePolicy(MesosScheduler scheduler) {
this.scheduler = scheduler;
mapSlotsMax = conf.getInt("mapred.tasktracker.map.tasks.maximum",
MAP_SLOTS_DEFAULT);
reduceSlotsMax =
conf.getInt("mapred.tasktracker.reduce.tasks.maximum",
REDUCE_SLOTS_DEFAULT);
slotCpus = conf.getFloat("mapred.mesos.slot.cpus",
(float) SLOT_CPUS_DEFAULT);
slotDisk = conf.getInt("mapred.mesos.slot.disk",
SLOT_DISK_DEFAULT);
slotMem = conf.getInt("mapred.mesos.slot.mem",
SLOT_JVM_HEAP_DEFAULT);
slotJVMHeap = Math.round((double) slotMem /
(JVM_MEM_OVERHEAD_PERCENT_DEFAULT + 1));
tasktrackerMem = conf.getInt("mapred.mesos.tasktracker.mem",
TASKTRACKER_MEM_DEFAULT);
tasktrackerJVMHeap = Math.round((double) tasktrackerMem /
(JVM_MEM_OVERHEAD_PERCENT_DEFAULT + 1));
containerCpus = TASKTRACKER_CPUS;
containerMem = tasktrackerMem;
containerDisk = 0;
}
public void computeNeededSlots(List<JobInProgress> jobsInProgress,
Collection<TaskTrackerStatus> taskTrackers) {
// Compute the number of pending maps and reduces.
int pendingMaps = 0;
int pendingReduces = 0;
int runningMaps = 0;
int runningReduces = 0;
for (JobInProgress progress : jobsInProgress) {
// JobStatus.pendingMaps/Reduces may return the wrong value on
// occasion. This seems to be safer.
pendingMaps += getPendingTasks(progress.getTasks(TaskType.MAP));
pendingReduces += getPendingTasks(progress.getTasks(TaskType.REDUCE));
runningMaps += progress.runningMaps();
runningReduces += progress.runningReduces();
}
// Mark active (heartbeated) TaskTrackers and compute idle slots.
int idleMapSlots = 0;
int idleReduceSlots = 0;
int unhealthyTrackers = 0;
for (TaskTrackerStatus status : taskTrackers) {
if (!status.getHealthStatus().isNodeHealthy()) {
// Skip this node if it's unhealthy.
++unhealthyTrackers;
continue;
}
HttpHost host = new HttpHost(status.getHost(), status.getHttpPort());
if (mesosTrackers.containsKey(host)) {
mesosTrackers.get(host).active = true;
mesosTrackers.get(host).timer.cancel();
idleMapSlots += status.getAvailableMapSlots();
idleReduceSlots += status.getAvailableReduceSlots();
}
}
// Consider the TaskTrackers that have yet to become active as being idle,
// otherwise we will launch excessive TaskTrackers.
int inactiveMapSlots = 0;
int inactiveReduceSlots = 0;
for (MesosTracker tracker : mesosTrackers.values()) {
if (!tracker.active) {
inactiveMapSlots += tracker.mapSlots;
inactiveReduceSlots += tracker.reduceSlots;
}
}
// To ensure Hadoop jobs begin promptly, we can specify a minimum number
// of 'hot slots' to be available for use. This addresses the
// TaskTracker spin up delay that exists with Hadoop on Mesos. This can
// be a nuisance with lower latency applications, such as ad-hoc Hive
// queries.
int minimumMapSlots = conf.getInt("mapred.mesos.total.map.slots.minimum", 0);
int minimumReduceSlots =
conf.getInt("mapred.mesos.total.reduce.slots.minimum", 0);
// Compute how many slots we need to allocate.
neededMapSlots = Math.max(
minimumMapSlots - (idleMapSlots + inactiveMapSlots),
pendingMaps - (idleMapSlots + inactiveMapSlots));
neededReduceSlots = Math.max(
minimumReduceSlots - (idleReduceSlots + inactiveReduceSlots),
pendingReduces - (idleReduceSlots + inactiveReduceSlots));
LOG.info(join("\n", Arrays.asList(
"JobTracker Status",
" Pending Map Tasks: " + pendingMaps,
" Pending Reduce Tasks: " + pendingReduces,
" Running Map Tasks: " + runningMaps,
" Running Reduce Tasks: " + runningReduces,
" Idle Map Slots: " + idleMapSlots,
" Idle Reduce Slots: " + idleReduceSlots,
" Inactive Map Slots: " + inactiveMapSlots
+ " (launched but no hearbeat yet)",
" Inactive Reduce Slots: " + inactiveReduceSlots
+ " (launched but no hearbeat yet)",
" Needed Map Slots: " + neededMapSlots,
" Needed Reduce Slots: " + neededReduceSlots,
" Unhealthy Trackers: " + unhealthyTrackers)));
if (stateFile != null) {
// Update state file
synchronized (this) {
Set<String> hosts = new HashSet<String>();
for (MesosTracker tracker : mesosTrackers.values()) {
hosts.add(tracker.host.getHostName());
}
try {
File tmp = new File(stateFile.getAbsoluteFile() + ".tmp");
FileWriter fstream = new FileWriter(tmp);
fstream.write(join("\n", Arrays.asList(
"time=" + System.currentTimeMillis(),
"pendingMaps=" + pendingMaps,
"pendingReduces=" + pendingReduces,
"runningMaps=" + runningMaps,
"runningReduces=" + runningReduces,
"idleMapSlots=" + idleMapSlots,
"idleReduceSlots=" + idleReduceSlots,
"inactiveMapSlots=" + inactiveMapSlots,
"inactiveReduceSlots=" + inactiveReduceSlots,
"neededMapSlots=" + neededMapSlots,
"neededReduceSlots=" + neededReduceSlots,
"unhealthyTrackers=" + unhealthyTrackers,
"hosts=" + join(",", hosts),
"")));
fstream.close();
tmp.renameTo(stateFile);
} catch (Exception e) {
LOG.error("Can't write state file: " + e.getMessage());
}
}
}
}
// This method computes the number of slots to launch for this offer, and
// returns true if the offer is sufficient.
// Must be overridden.
public boolean computeSlots() {
return false;
}
public void resourceOffers(SchedulerDriver schedulerDriver,
List<Offer> offers) {
// Before synchronizing, we pull all needed information from the JobTracker.
final HttpHost jobTrackerAddress =
new HttpHost(jobTracker.getHostname(), jobTracker.getTrackerPort());
final Collection<TaskTrackerStatus> taskTrackers = jobTracker.taskTrackers();
final List<JobInProgress> jobsInProgress = new ArrayList<JobInProgress>();
for (JobStatus status : jobTracker.jobsToComplete()) {
jobsInProgress.add(jobTracker.getJob(status.getJobID()));
}
computeNeededSlots(jobsInProgress, taskTrackers);
synchronized (scheduler) {
// Launch TaskTrackers to satisfy the slot requirements.
for (Offer offer : offers) {
if (neededMapSlots <= 0 && neededReduceSlots <= 0) {
schedulerDriver.declineOffer(offer.getId());
continue;
}
// Ensure these values aren't < 0.
neededMapSlots = Math.max(0, neededMapSlots);
neededReduceSlots = Math.max(0, neededReduceSlots);
cpus = -1.0;
mem = -1.0;
disk = -1.0;
Set<Integer> ports = new HashSet<Integer>();
String cpuRole = new String("*");
String memRole = cpuRole;
String diskRole = cpuRole;
String portsRole = cpuRole;
// Pull out the cpus, memory, disk, and 2 ports from the offer.
for (Resource resource : offer.getResourcesList()) {
if (resource.getName().equals("cpus")
&& resource.getType() == Value.Type.SCALAR) {
cpus = resource.getScalar().getValue();
cpuRole = resource.getRole();
} else if (resource.getName().equals("mem")
&& resource.getType() == Value.Type.SCALAR) {
mem = resource.getScalar().getValue();
memRole = resource.getRole();
} else if (resource.getName().equals("disk")
&& resource.getType() == Value.Type.SCALAR) {
disk = resource.getScalar().getValue();
diskRole = resource.getRole();
} else if (resource.getName().equals("ports")
&& resource.getType() == Value.Type.RANGES) {
portsRole = resource.getRole();
for (Value.Range range : resource.getRanges().getRangeList()) {
Integer begin = (int)range.getBegin();
Integer end = (int)range.getEnd();
if (end < begin) {
LOG.warn("Ignoring invalid port range: begin=" + begin + " end=" + end);
continue;
}
while (begin <= end && ports.size() < 2) {
ports.add(begin);
begin += 1;
}
}
}
}
final boolean sufficient = computeSlots();
double taskCpus = (mapSlots + reduceSlots) * slotCpus + containerCpus;
double taskMem = (mapSlots + reduceSlots) * slotMem + containerMem;
double taskDisk = (mapSlots + reduceSlots) * slotDisk + containerDisk;
if (!sufficient || ports.size() < 2) {
LOG.info(join("\n", Arrays.asList(
"Declining offer with insufficient resources for a TaskTracker: ",
" cpus: offered " + cpus + " needed at least " + taskCpus,
" mem : offered " + mem + " needed at least " + taskMem,
" disk: offered " + disk + " needed at least " + taskDisk,
" ports: " + (ports.size() < 2
? " less than 2 offered"
: " at least 2 (sufficient)"))));
schedulerDriver.declineOffer(offer.getId());
continue;
}
Iterator<Integer> portIter = ports.iterator();
HttpHost httpAddress = new HttpHost(offer.getHostname(), portIter.next());
HttpHost reportAddress = new HttpHost(offer.getHostname(), portIter.next());
// Check that this tracker is not already launched. This problem was
// observed on a few occasions, but not reliably. The main symptom was
// that entries in `mesosTrackers` were being lost, and task trackers
// would be 'lost' mysteriously (probably because the ports were in
// use). This problem has since gone away with a rewrite of the port
// selection code, but the check + logging is left here.
// TODO(brenden): Diagnose this to determine root cause.
if (mesosTrackers.containsKey(httpAddress)) {
LOG.info(join("\n", Arrays.asList(
"Declining offer because host/port combination is in use: ",
" cpus: offered " + cpus + " needed " + taskCpus,
" mem : offered " + mem + " needed " + taskMem,
" disk: offered " + disk + " needed " + taskDisk,
" ports: " + ports)));
schedulerDriver.declineOffer(offer.getId());
continue;
}
TaskID taskId = TaskID.newBuilder()
.setValue("Task_Tracker_" + launchedTrackers++).build();
LOG.info("Launching task " + taskId.getValue() + " on "
+ httpAddress.toString() + " with mapSlots=" + mapSlots + " reduceSlots=" + reduceSlots);
// Add this tracker to Mesos tasks.
mesosTrackers.put(httpAddress, new MesosTracker(httpAddress, taskId,
mapSlots, reduceSlots, scheduler));
// Set up the environment for running the TaskTracker.
Protos.Environment.Builder envBuilder = Protos.Environment
.newBuilder()
.addVariables(
Protos.Environment.Variable.newBuilder()
.setName("HADOOP_HEAPSIZE")
.setValue("" + tasktrackerJVMHeap));
// Set java specific environment, appropriately.
Map<String, String> env = System.getenv();
if (env.containsKey("JAVA_HOME")) {
envBuilder.addVariables(Protos.Environment.Variable.newBuilder()
.setName("JAVA_HOME")
.setValue(env.get("JAVA_HOME")));
}
if (env.containsKey("JAVA_LIBRARY_PATH")) {
envBuilder.addVariables(Protos.Environment.Variable.newBuilder()
.setName("JAVA_LIBRARY_PATH")
.setValue(env.get("JAVA_LIBRARY_PATH")));
}
// Command info differs when performing a local run.
CommandInfo commandInfo = null;
String master = conf.get("mapred.mesos.master");
if (master == null) {
throw new RuntimeException(
"Expecting configuration property 'mapred.mesos.master'");
} else if (master == "local") {
throw new RuntimeException(
"Can not use 'local' for 'mapred.mesos.executor'");
}
String uri = conf.get("mapred.mesos.executor.uri");
if (uri == null) {
throw new RuntimeException(
"Expecting configuration property 'mapred.mesos.executor'");
}
String directory = conf.get("mapred.mesos.executor.directory");
if (directory == null || directory.equals("")) {
LOG.info("URI: " + uri + ", name: " + new File(uri).getName());
directory = new File(uri).getName().split("\\.")[0] + "*";
}
String command = conf.get("mapred.mesos.executor.command");
if (command == null || command.equals("")) {
command = "echo $(env) ; " +
" ./bin/hadoop org.apache.hadoop.mapred.MesosExecutor";
}
commandInfo = CommandInfo.newBuilder()
.setEnvironment(envBuilder)
.setValue(String.format("cd %s && %s", directory, command))
.addUris(CommandInfo.URI.newBuilder().setValue(uri)).build();
// Create a configuration from the current configuration and
// override properties as appropriate for the TaskTracker.
Configuration overrides = new Configuration(conf);
overrides.set("mapred.job.tracker",
jobTrackerAddress.getHostName() + ':' + jobTrackerAddress.getPort());
overrides.set("mapred.task.tracker.http.address",
httpAddress.getHostName() + ':' + httpAddress.getPort());
overrides.set("mapred.task.tracker.report.address",
reportAddress.getHostName() + ':' + reportAddress.getPort());
overrides.set("mapred.child.java.opts",
conf.get("mapred.child.java.opts") +
" -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m");
overrides.set("mapred.map.child.java.opts",
conf.get("mapred.map.child.java.opts") +
" -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m");
overrides.set("mapred.reduce.child.java.opts",
conf.get("mapred.reduce.child.java.opts") +
" -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m");
overrides.setLong("mapred.tasktracker.map.tasks.maximum",
mapSlots);
overrides.setLong("mapred.tasktracker.reduce.tasks.maximum",
reduceSlots);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
overrides.write(new DataOutputStream(baos));
baos.flush();
} catch (IOException e) {
LOG.warn("Failed to serialize configuration.", e);
System.exit(1);
}
byte[] bytes = baos.toByteArray();
TaskInfo info = TaskInfo
.newBuilder()
.setName(taskId.getValue())
.setTaskId(taskId)
.setSlaveId(offer.getSlaveId())
.addResources(
Resource
.newBuilder()
.setName("cpus")
.setType(Value.Type.SCALAR)
.setRole(cpuRole)
.setScalar(Value.Scalar.newBuilder().setValue(taskCpus - containerCpus)))
.addResources(
Resource
.newBuilder()
.setName("mem")
.setType(Value.Type.SCALAR)
.setRole(memRole)
.setScalar(Value.Scalar.newBuilder().setValue(taskMem - containerMem)))
.addResources(
Resource
.newBuilder()
.setName("disk")
.setType(Value.Type.SCALAR)
.setRole(diskRole)
.setScalar(Value.Scalar.newBuilder().setValue(taskDisk - containerDisk)))
.addResources(
Resource
.newBuilder()
.setName("ports")
.setType(Value.Type.RANGES)
.setRole(portsRole)
.setRanges(
Value.Ranges
.newBuilder()
.addRange(Value.Range.newBuilder()
.setBegin(httpAddress.getPort())
.setEnd(httpAddress.getPort()))
.addRange(Value.Range.newBuilder()
.setBegin(reportAddress.getPort())
.setEnd(reportAddress.getPort()))))
.setExecutor(
ExecutorInfo
.newBuilder()
.setExecutorId(ExecutorID.newBuilder().setValue(
"executor_" + taskId.getValue()))
.setName("Hadoop TaskTracker")
.setSource(taskId.getValue())
.addResources(
Resource
.newBuilder()
.setName("cpus")
.setType(Value.Type.SCALAR)
.setRole(cpuRole)
.setScalar(Value.Scalar.newBuilder().setValue(
(containerCpus))))
.addResources(
Resource
.newBuilder()
.setName("mem")
.setType(Value.Type.SCALAR)
.setRole(memRole)
- .setScalar(Value.Scalar.newBuilder().setValue(containerMem))))
- .setCommand(commandInfo)
+ .setScalar(Value.Scalar.newBuilder().setValue(containerMem)))
+ .setCommand(commandInfo))
.setData(ByteString.copyFrom(bytes))
.build();
schedulerDriver.launchTasks(offer.getId(), Arrays.asList(info));
neededMapSlots -= mapSlots;
neededReduceSlots -= reduceSlots;
}
if (neededMapSlots <= 0 && neededReduceSlots <= 0) {
LOG.info("Satisfied map and reduce slots needed.");
} else {
LOG.info("Unable to fully satisfy needed map/reduce slots: "
+ (neededMapSlots > 0 ? neededMapSlots + " map slots " : "")
+ (neededReduceSlots > 0 ? neededReduceSlots + " reduce slots " : "")
+ "remaining");
}
}
}
}
private class ResourcePolicyFixed extends ResourcePolicy {
public ResourcePolicyFixed(MesosScheduler scheduler) {
super(scheduler);
}
// This method computes the number of slots to launch for this offer, and
// returns true if the offer is sufficient.
@Override
public boolean computeSlots() {
mapSlots = mapSlotsMax;
reduceSlots = reduceSlotsMax;
slots = Integer.MAX_VALUE;
slots = (int) Math.min(slots, (cpus - containerCpus) / slotCpus);
slots = (int) Math.min(slots, (mem - containerMem) / slotMem);
slots = (int) Math.min(slots, (disk - containerDisk) / slotDisk);
// Is this offer too small for even the minimum slots?
if (slots < mapSlots + reduceSlots || slots < 1) {
return false;
}
return true;
}
}
private class ResourcePolicyVariable extends ResourcePolicy {
public ResourcePolicyVariable(MesosScheduler scheduler) {
super(scheduler);
}
// This method computes the number of slots to launch for this offer, and
// returns true if the offer is sufficient.
@Override
public boolean computeSlots() {
// What's the minimum number of map and reduce slots we should try to
// launch?
mapSlots = 0;
reduceSlots = 0;
// Determine how many slots we can allocate.
int slots = mapSlotsMax + reduceSlotsMax;
slots = (int) Math.min(slots, (cpus - containerCpus) / slotCpus);
slots = (int) Math.min(slots, (mem - containerMem) / slotMem);
slots = (int) Math.min(slots, (disk - containerDisk) / slotDisk);
// Is this offer too small for even the minimum slots?
if (slots < 1) {
return false;
}
// Is the number of slots we need sufficiently small? If so, we can
// allocate exactly the number we need.
if (slots >= neededMapSlots + neededReduceSlots && neededMapSlots <
mapSlotsMax && neededReduceSlots < reduceSlotsMax) {
mapSlots = neededMapSlots;
reduceSlots = neededReduceSlots;
} else {
// Allocate slots fairly for this resource offer.
double mapFactor = (double) neededMapSlots / (neededMapSlots + neededReduceSlots);
double reduceFactor = (double) neededReduceSlots / (neededMapSlots + neededReduceSlots);
// To avoid map/reduce slot starvation, don't allow more than 50%
// spread between map/reduce slots when we need both mappers and
// reducers.
if (neededMapSlots > 0 && neededReduceSlots > 0) {
if (mapFactor < 0.25) {
mapFactor = 0.25;
} else if (mapFactor > 0.75) {
mapFactor = 0.75;
}
if (reduceFactor < 0.25) {
reduceFactor = 0.25;
} else if (reduceFactor > 0.75) {
reduceFactor = 0.75;
}
}
mapSlots = Math.min(Math.min((long)Math.round(mapFactor * slots), mapSlotsMax), neededMapSlots);
// The remaining slots are allocated for reduces.
slots -= mapSlots;
reduceSlots = Math.min(Math.min(slots, reduceSlotsMax), neededReduceSlots);
}
return true;
}
}
/**
* Used to track the our launched TaskTrackers.
*/
private class MesosTracker {
public volatile HttpHost host;
public TaskID taskId;
public long mapSlots;
public long reduceSlots;
public volatile boolean active = false; // Set once tracked by the JobTracker.
public Timer timer;
public volatile MesosScheduler scheduler;
// Tracks Hadoop jobs running on the tracker.
public Set<JobID> jobs = new HashSet<JobID>();
public MesosTracker(HttpHost host, TaskID taskId, long mapSlots,
long reduceSlots, MesosScheduler scheduler) {
this.host = host;
this.taskId = taskId;
this.mapSlots = mapSlots;
this.reduceSlots = reduceSlots;
this.scheduler = scheduler;
this.timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
synchronized (MesosTracker.this.scheduler) {
// If the tracker activated while we were awaiting to acquire the
// lock, return.
if (MesosTracker.this.active) return;
// When the scheduler is busy or doesn't receive offers, it may
// fail to mark some TaskTrackers as active even though they are.
// Here we do a final check with the JobTracker to make sure this
// TaskTracker is really not there before we kill it.
final Collection<TaskTrackerStatus> taskTrackers =
MesosTracker.this.scheduler.jobTracker.taskTrackers();
for (TaskTrackerStatus status : taskTrackers) {
HttpHost host = new HttpHost(status.getHost(), status.getHttpPort());
if (MesosTracker.this.host.equals(host)) {
return;
}
}
LOG.warn("Tracker " + MesosTracker.this.host + " failed to launch within " +
LAUNCH_TIMEOUT_MS / 1000 + " seconds, killing it");
MesosTracker.this.scheduler.killTracker(MesosTracker.this);
}
}
}, LAUNCH_TIMEOUT_MS);
}
}
}
| true | true | public void resourceOffers(SchedulerDriver schedulerDriver,
List<Offer> offers) {
// Before synchronizing, we pull all needed information from the JobTracker.
final HttpHost jobTrackerAddress =
new HttpHost(jobTracker.getHostname(), jobTracker.getTrackerPort());
final Collection<TaskTrackerStatus> taskTrackers = jobTracker.taskTrackers();
final List<JobInProgress> jobsInProgress = new ArrayList<JobInProgress>();
for (JobStatus status : jobTracker.jobsToComplete()) {
jobsInProgress.add(jobTracker.getJob(status.getJobID()));
}
computeNeededSlots(jobsInProgress, taskTrackers);
synchronized (scheduler) {
// Launch TaskTrackers to satisfy the slot requirements.
for (Offer offer : offers) {
if (neededMapSlots <= 0 && neededReduceSlots <= 0) {
schedulerDriver.declineOffer(offer.getId());
continue;
}
// Ensure these values aren't < 0.
neededMapSlots = Math.max(0, neededMapSlots);
neededReduceSlots = Math.max(0, neededReduceSlots);
cpus = -1.0;
mem = -1.0;
disk = -1.0;
Set<Integer> ports = new HashSet<Integer>();
String cpuRole = new String("*");
String memRole = cpuRole;
String diskRole = cpuRole;
String portsRole = cpuRole;
// Pull out the cpus, memory, disk, and 2 ports from the offer.
for (Resource resource : offer.getResourcesList()) {
if (resource.getName().equals("cpus")
&& resource.getType() == Value.Type.SCALAR) {
cpus = resource.getScalar().getValue();
cpuRole = resource.getRole();
} else if (resource.getName().equals("mem")
&& resource.getType() == Value.Type.SCALAR) {
mem = resource.getScalar().getValue();
memRole = resource.getRole();
} else if (resource.getName().equals("disk")
&& resource.getType() == Value.Type.SCALAR) {
disk = resource.getScalar().getValue();
diskRole = resource.getRole();
} else if (resource.getName().equals("ports")
&& resource.getType() == Value.Type.RANGES) {
portsRole = resource.getRole();
for (Value.Range range : resource.getRanges().getRangeList()) {
Integer begin = (int)range.getBegin();
Integer end = (int)range.getEnd();
if (end < begin) {
LOG.warn("Ignoring invalid port range: begin=" + begin + " end=" + end);
continue;
}
while (begin <= end && ports.size() < 2) {
ports.add(begin);
begin += 1;
}
}
}
}
final boolean sufficient = computeSlots();
double taskCpus = (mapSlots + reduceSlots) * slotCpus + containerCpus;
double taskMem = (mapSlots + reduceSlots) * slotMem + containerMem;
double taskDisk = (mapSlots + reduceSlots) * slotDisk + containerDisk;
if (!sufficient || ports.size() < 2) {
LOG.info(join("\n", Arrays.asList(
"Declining offer with insufficient resources for a TaskTracker: ",
" cpus: offered " + cpus + " needed at least " + taskCpus,
" mem : offered " + mem + " needed at least " + taskMem,
" disk: offered " + disk + " needed at least " + taskDisk,
" ports: " + (ports.size() < 2
? " less than 2 offered"
: " at least 2 (sufficient)"))));
schedulerDriver.declineOffer(offer.getId());
continue;
}
Iterator<Integer> portIter = ports.iterator();
HttpHost httpAddress = new HttpHost(offer.getHostname(), portIter.next());
HttpHost reportAddress = new HttpHost(offer.getHostname(), portIter.next());
// Check that this tracker is not already launched. This problem was
// observed on a few occasions, but not reliably. The main symptom was
// that entries in `mesosTrackers` were being lost, and task trackers
// would be 'lost' mysteriously (probably because the ports were in
// use). This problem has since gone away with a rewrite of the port
// selection code, but the check + logging is left here.
// TODO(brenden): Diagnose this to determine root cause.
if (mesosTrackers.containsKey(httpAddress)) {
LOG.info(join("\n", Arrays.asList(
"Declining offer because host/port combination is in use: ",
" cpus: offered " + cpus + " needed " + taskCpus,
" mem : offered " + mem + " needed " + taskMem,
" disk: offered " + disk + " needed " + taskDisk,
" ports: " + ports)));
schedulerDriver.declineOffer(offer.getId());
continue;
}
TaskID taskId = TaskID.newBuilder()
.setValue("Task_Tracker_" + launchedTrackers++).build();
LOG.info("Launching task " + taskId.getValue() + " on "
+ httpAddress.toString() + " with mapSlots=" + mapSlots + " reduceSlots=" + reduceSlots);
// Add this tracker to Mesos tasks.
mesosTrackers.put(httpAddress, new MesosTracker(httpAddress, taskId,
mapSlots, reduceSlots, scheduler));
// Set up the environment for running the TaskTracker.
Protos.Environment.Builder envBuilder = Protos.Environment
.newBuilder()
.addVariables(
Protos.Environment.Variable.newBuilder()
.setName("HADOOP_HEAPSIZE")
.setValue("" + tasktrackerJVMHeap));
// Set java specific environment, appropriately.
Map<String, String> env = System.getenv();
if (env.containsKey("JAVA_HOME")) {
envBuilder.addVariables(Protos.Environment.Variable.newBuilder()
.setName("JAVA_HOME")
.setValue(env.get("JAVA_HOME")));
}
if (env.containsKey("JAVA_LIBRARY_PATH")) {
envBuilder.addVariables(Protos.Environment.Variable.newBuilder()
.setName("JAVA_LIBRARY_PATH")
.setValue(env.get("JAVA_LIBRARY_PATH")));
}
// Command info differs when performing a local run.
CommandInfo commandInfo = null;
String master = conf.get("mapred.mesos.master");
if (master == null) {
throw new RuntimeException(
"Expecting configuration property 'mapred.mesos.master'");
} else if (master == "local") {
throw new RuntimeException(
"Can not use 'local' for 'mapred.mesos.executor'");
}
String uri = conf.get("mapred.mesos.executor.uri");
if (uri == null) {
throw new RuntimeException(
"Expecting configuration property 'mapred.mesos.executor'");
}
String directory = conf.get("mapred.mesos.executor.directory");
if (directory == null || directory.equals("")) {
LOG.info("URI: " + uri + ", name: " + new File(uri).getName());
directory = new File(uri).getName().split("\\.")[0] + "*";
}
String command = conf.get("mapred.mesos.executor.command");
if (command == null || command.equals("")) {
command = "echo $(env) ; " +
" ./bin/hadoop org.apache.hadoop.mapred.MesosExecutor";
}
commandInfo = CommandInfo.newBuilder()
.setEnvironment(envBuilder)
.setValue(String.format("cd %s && %s", directory, command))
.addUris(CommandInfo.URI.newBuilder().setValue(uri)).build();
// Create a configuration from the current configuration and
// override properties as appropriate for the TaskTracker.
Configuration overrides = new Configuration(conf);
overrides.set("mapred.job.tracker",
jobTrackerAddress.getHostName() + ':' + jobTrackerAddress.getPort());
overrides.set("mapred.task.tracker.http.address",
httpAddress.getHostName() + ':' + httpAddress.getPort());
overrides.set("mapred.task.tracker.report.address",
reportAddress.getHostName() + ':' + reportAddress.getPort());
overrides.set("mapred.child.java.opts",
conf.get("mapred.child.java.opts") +
" -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m");
overrides.set("mapred.map.child.java.opts",
conf.get("mapred.map.child.java.opts") +
" -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m");
overrides.set("mapred.reduce.child.java.opts",
conf.get("mapred.reduce.child.java.opts") +
" -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m");
overrides.setLong("mapred.tasktracker.map.tasks.maximum",
mapSlots);
overrides.setLong("mapred.tasktracker.reduce.tasks.maximum",
reduceSlots);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
overrides.write(new DataOutputStream(baos));
baos.flush();
} catch (IOException e) {
LOG.warn("Failed to serialize configuration.", e);
System.exit(1);
}
byte[] bytes = baos.toByteArray();
TaskInfo info = TaskInfo
.newBuilder()
.setName(taskId.getValue())
.setTaskId(taskId)
.setSlaveId(offer.getSlaveId())
.addResources(
Resource
.newBuilder()
.setName("cpus")
.setType(Value.Type.SCALAR)
.setRole(cpuRole)
.setScalar(Value.Scalar.newBuilder().setValue(taskCpus - containerCpus)))
.addResources(
Resource
.newBuilder()
.setName("mem")
.setType(Value.Type.SCALAR)
.setRole(memRole)
.setScalar(Value.Scalar.newBuilder().setValue(taskMem - containerMem)))
.addResources(
Resource
.newBuilder()
.setName("disk")
.setType(Value.Type.SCALAR)
.setRole(diskRole)
.setScalar(Value.Scalar.newBuilder().setValue(taskDisk - containerDisk)))
.addResources(
Resource
.newBuilder()
.setName("ports")
.setType(Value.Type.RANGES)
.setRole(portsRole)
.setRanges(
Value.Ranges
.newBuilder()
.addRange(Value.Range.newBuilder()
.setBegin(httpAddress.getPort())
.setEnd(httpAddress.getPort()))
.addRange(Value.Range.newBuilder()
.setBegin(reportAddress.getPort())
.setEnd(reportAddress.getPort()))))
.setExecutor(
ExecutorInfo
.newBuilder()
.setExecutorId(ExecutorID.newBuilder().setValue(
"executor_" + taskId.getValue()))
.setName("Hadoop TaskTracker")
.setSource(taskId.getValue())
.addResources(
Resource
.newBuilder()
.setName("cpus")
.setType(Value.Type.SCALAR)
.setRole(cpuRole)
.setScalar(Value.Scalar.newBuilder().setValue(
(containerCpus))))
.addResources(
Resource
.newBuilder()
.setName("mem")
.setType(Value.Type.SCALAR)
.setRole(memRole)
.setScalar(Value.Scalar.newBuilder().setValue(containerMem))))
.setCommand(commandInfo)
.setData(ByteString.copyFrom(bytes))
.build();
schedulerDriver.launchTasks(offer.getId(), Arrays.asList(info));
neededMapSlots -= mapSlots;
neededReduceSlots -= reduceSlots;
}
if (neededMapSlots <= 0 && neededReduceSlots <= 0) {
LOG.info("Satisfied map and reduce slots needed.");
} else {
LOG.info("Unable to fully satisfy needed map/reduce slots: "
+ (neededMapSlots > 0 ? neededMapSlots + " map slots " : "")
+ (neededReduceSlots > 0 ? neededReduceSlots + " reduce slots " : "")
+ "remaining");
}
}
}
| public void resourceOffers(SchedulerDriver schedulerDriver,
List<Offer> offers) {
// Before synchronizing, we pull all needed information from the JobTracker.
final HttpHost jobTrackerAddress =
new HttpHost(jobTracker.getHostname(), jobTracker.getTrackerPort());
final Collection<TaskTrackerStatus> taskTrackers = jobTracker.taskTrackers();
final List<JobInProgress> jobsInProgress = new ArrayList<JobInProgress>();
for (JobStatus status : jobTracker.jobsToComplete()) {
jobsInProgress.add(jobTracker.getJob(status.getJobID()));
}
computeNeededSlots(jobsInProgress, taskTrackers);
synchronized (scheduler) {
// Launch TaskTrackers to satisfy the slot requirements.
for (Offer offer : offers) {
if (neededMapSlots <= 0 && neededReduceSlots <= 0) {
schedulerDriver.declineOffer(offer.getId());
continue;
}
// Ensure these values aren't < 0.
neededMapSlots = Math.max(0, neededMapSlots);
neededReduceSlots = Math.max(0, neededReduceSlots);
cpus = -1.0;
mem = -1.0;
disk = -1.0;
Set<Integer> ports = new HashSet<Integer>();
String cpuRole = new String("*");
String memRole = cpuRole;
String diskRole = cpuRole;
String portsRole = cpuRole;
// Pull out the cpus, memory, disk, and 2 ports from the offer.
for (Resource resource : offer.getResourcesList()) {
if (resource.getName().equals("cpus")
&& resource.getType() == Value.Type.SCALAR) {
cpus = resource.getScalar().getValue();
cpuRole = resource.getRole();
} else if (resource.getName().equals("mem")
&& resource.getType() == Value.Type.SCALAR) {
mem = resource.getScalar().getValue();
memRole = resource.getRole();
} else if (resource.getName().equals("disk")
&& resource.getType() == Value.Type.SCALAR) {
disk = resource.getScalar().getValue();
diskRole = resource.getRole();
} else if (resource.getName().equals("ports")
&& resource.getType() == Value.Type.RANGES) {
portsRole = resource.getRole();
for (Value.Range range : resource.getRanges().getRangeList()) {
Integer begin = (int)range.getBegin();
Integer end = (int)range.getEnd();
if (end < begin) {
LOG.warn("Ignoring invalid port range: begin=" + begin + " end=" + end);
continue;
}
while (begin <= end && ports.size() < 2) {
ports.add(begin);
begin += 1;
}
}
}
}
final boolean sufficient = computeSlots();
double taskCpus = (mapSlots + reduceSlots) * slotCpus + containerCpus;
double taskMem = (mapSlots + reduceSlots) * slotMem + containerMem;
double taskDisk = (mapSlots + reduceSlots) * slotDisk + containerDisk;
if (!sufficient || ports.size() < 2) {
LOG.info(join("\n", Arrays.asList(
"Declining offer with insufficient resources for a TaskTracker: ",
" cpus: offered " + cpus + " needed at least " + taskCpus,
" mem : offered " + mem + " needed at least " + taskMem,
" disk: offered " + disk + " needed at least " + taskDisk,
" ports: " + (ports.size() < 2
? " less than 2 offered"
: " at least 2 (sufficient)"))));
schedulerDriver.declineOffer(offer.getId());
continue;
}
Iterator<Integer> portIter = ports.iterator();
HttpHost httpAddress = new HttpHost(offer.getHostname(), portIter.next());
HttpHost reportAddress = new HttpHost(offer.getHostname(), portIter.next());
// Check that this tracker is not already launched. This problem was
// observed on a few occasions, but not reliably. The main symptom was
// that entries in `mesosTrackers` were being lost, and task trackers
// would be 'lost' mysteriously (probably because the ports were in
// use). This problem has since gone away with a rewrite of the port
// selection code, but the check + logging is left here.
// TODO(brenden): Diagnose this to determine root cause.
if (mesosTrackers.containsKey(httpAddress)) {
LOG.info(join("\n", Arrays.asList(
"Declining offer because host/port combination is in use: ",
" cpus: offered " + cpus + " needed " + taskCpus,
" mem : offered " + mem + " needed " + taskMem,
" disk: offered " + disk + " needed " + taskDisk,
" ports: " + ports)));
schedulerDriver.declineOffer(offer.getId());
continue;
}
TaskID taskId = TaskID.newBuilder()
.setValue("Task_Tracker_" + launchedTrackers++).build();
LOG.info("Launching task " + taskId.getValue() + " on "
+ httpAddress.toString() + " with mapSlots=" + mapSlots + " reduceSlots=" + reduceSlots);
// Add this tracker to Mesos tasks.
mesosTrackers.put(httpAddress, new MesosTracker(httpAddress, taskId,
mapSlots, reduceSlots, scheduler));
// Set up the environment for running the TaskTracker.
Protos.Environment.Builder envBuilder = Protos.Environment
.newBuilder()
.addVariables(
Protos.Environment.Variable.newBuilder()
.setName("HADOOP_HEAPSIZE")
.setValue("" + tasktrackerJVMHeap));
// Set java specific environment, appropriately.
Map<String, String> env = System.getenv();
if (env.containsKey("JAVA_HOME")) {
envBuilder.addVariables(Protos.Environment.Variable.newBuilder()
.setName("JAVA_HOME")
.setValue(env.get("JAVA_HOME")));
}
if (env.containsKey("JAVA_LIBRARY_PATH")) {
envBuilder.addVariables(Protos.Environment.Variable.newBuilder()
.setName("JAVA_LIBRARY_PATH")
.setValue(env.get("JAVA_LIBRARY_PATH")));
}
// Command info differs when performing a local run.
CommandInfo commandInfo = null;
String master = conf.get("mapred.mesos.master");
if (master == null) {
throw new RuntimeException(
"Expecting configuration property 'mapred.mesos.master'");
} else if (master == "local") {
throw new RuntimeException(
"Can not use 'local' for 'mapred.mesos.executor'");
}
String uri = conf.get("mapred.mesos.executor.uri");
if (uri == null) {
throw new RuntimeException(
"Expecting configuration property 'mapred.mesos.executor'");
}
String directory = conf.get("mapred.mesos.executor.directory");
if (directory == null || directory.equals("")) {
LOG.info("URI: " + uri + ", name: " + new File(uri).getName());
directory = new File(uri).getName().split("\\.")[0] + "*";
}
String command = conf.get("mapred.mesos.executor.command");
if (command == null || command.equals("")) {
command = "echo $(env) ; " +
" ./bin/hadoop org.apache.hadoop.mapred.MesosExecutor";
}
commandInfo = CommandInfo.newBuilder()
.setEnvironment(envBuilder)
.setValue(String.format("cd %s && %s", directory, command))
.addUris(CommandInfo.URI.newBuilder().setValue(uri)).build();
// Create a configuration from the current configuration and
// override properties as appropriate for the TaskTracker.
Configuration overrides = new Configuration(conf);
overrides.set("mapred.job.tracker",
jobTrackerAddress.getHostName() + ':' + jobTrackerAddress.getPort());
overrides.set("mapred.task.tracker.http.address",
httpAddress.getHostName() + ':' + httpAddress.getPort());
overrides.set("mapred.task.tracker.report.address",
reportAddress.getHostName() + ':' + reportAddress.getPort());
overrides.set("mapred.child.java.opts",
conf.get("mapred.child.java.opts") +
" -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m");
overrides.set("mapred.map.child.java.opts",
conf.get("mapred.map.child.java.opts") +
" -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m");
overrides.set("mapred.reduce.child.java.opts",
conf.get("mapred.reduce.child.java.opts") +
" -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m");
overrides.setLong("mapred.tasktracker.map.tasks.maximum",
mapSlots);
overrides.setLong("mapred.tasktracker.reduce.tasks.maximum",
reduceSlots);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
overrides.write(new DataOutputStream(baos));
baos.flush();
} catch (IOException e) {
LOG.warn("Failed to serialize configuration.", e);
System.exit(1);
}
byte[] bytes = baos.toByteArray();
TaskInfo info = TaskInfo
.newBuilder()
.setName(taskId.getValue())
.setTaskId(taskId)
.setSlaveId(offer.getSlaveId())
.addResources(
Resource
.newBuilder()
.setName("cpus")
.setType(Value.Type.SCALAR)
.setRole(cpuRole)
.setScalar(Value.Scalar.newBuilder().setValue(taskCpus - containerCpus)))
.addResources(
Resource
.newBuilder()
.setName("mem")
.setType(Value.Type.SCALAR)
.setRole(memRole)
.setScalar(Value.Scalar.newBuilder().setValue(taskMem - containerMem)))
.addResources(
Resource
.newBuilder()
.setName("disk")
.setType(Value.Type.SCALAR)
.setRole(diskRole)
.setScalar(Value.Scalar.newBuilder().setValue(taskDisk - containerDisk)))
.addResources(
Resource
.newBuilder()
.setName("ports")
.setType(Value.Type.RANGES)
.setRole(portsRole)
.setRanges(
Value.Ranges
.newBuilder()
.addRange(Value.Range.newBuilder()
.setBegin(httpAddress.getPort())
.setEnd(httpAddress.getPort()))
.addRange(Value.Range.newBuilder()
.setBegin(reportAddress.getPort())
.setEnd(reportAddress.getPort()))))
.setExecutor(
ExecutorInfo
.newBuilder()
.setExecutorId(ExecutorID.newBuilder().setValue(
"executor_" + taskId.getValue()))
.setName("Hadoop TaskTracker")
.setSource(taskId.getValue())
.addResources(
Resource
.newBuilder()
.setName("cpus")
.setType(Value.Type.SCALAR)
.setRole(cpuRole)
.setScalar(Value.Scalar.newBuilder().setValue(
(containerCpus))))
.addResources(
Resource
.newBuilder()
.setName("mem")
.setType(Value.Type.SCALAR)
.setRole(memRole)
.setScalar(Value.Scalar.newBuilder().setValue(containerMem)))
.setCommand(commandInfo))
.setData(ByteString.copyFrom(bytes))
.build();
schedulerDriver.launchTasks(offer.getId(), Arrays.asList(info));
neededMapSlots -= mapSlots;
neededReduceSlots -= reduceSlots;
}
if (neededMapSlots <= 0 && neededReduceSlots <= 0) {
LOG.info("Satisfied map and reduce slots needed.");
} else {
LOG.info("Unable to fully satisfy needed map/reduce slots: "
+ (neededMapSlots > 0 ? neededMapSlots + " map slots " : "")
+ (neededReduceSlots > 0 ? neededReduceSlots + " reduce slots " : "")
+ "remaining");
}
}
}
|
diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/TestRecursivePrefixTreeStrategy.java b/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/TestRecursivePrefixTreeStrategy.java
index d5c575f28..995fb96a8 100644
--- a/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/TestRecursivePrefixTreeStrategy.java
+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/TestRecursivePrefixTreeStrategy.java
@@ -1,216 +1,216 @@
package org.apache.lucene.spatial.prefix;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.distance.DistanceUtils;
import com.spatial4j.core.io.GeohashUtils;
import com.spatial4j.core.shape.Point;
import com.spatial4j.core.shape.Rectangle;
import com.spatial4j.core.shape.Shape;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.spatial.SpatialMatchConcern;
import org.apache.lucene.spatial.StrategyTestCase;
import org.apache.lucene.spatial.prefix.tree.GeohashPrefixTree;
import org.apache.lucene.spatial.query.SpatialArgs;
import org.apache.lucene.spatial.query.SpatialOperation;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TestRecursivePrefixTreeStrategy extends StrategyTestCase {
private int maxLength;
//Tests should call this first.
private void init(int maxLength) {
this.maxLength = maxLength;
this.ctx = SpatialContext.GEO;
GeohashPrefixTree grid = new GeohashPrefixTree(ctx, maxLength);
this.strategy = new RecursivePrefixTreeStrategy(grid, getClass().getSimpleName());
}
@Test
public void testFilterWithVariableScanLevel() throws IOException {
init(GeohashPrefixTree.getMaxLevelsPossible());
getAddAndVerifyIndexedDocuments(DATA_WORLD_CITIES_POINTS);
//execute queries for each prefix grid scan level
for(int i = 0; i <= maxLength; i++) {
((RecursivePrefixTreeStrategy)strategy).setPrefixGridScanLevel(i);
executeQueries(SpatialMatchConcern.FILTER, QTEST_Cities_IsWithin_BBox);
}
}
@Test
public void testOneMeterPrecision() {
init(GeohashPrefixTree.getMaxLevelsPossible());
GeohashPrefixTree grid = (GeohashPrefixTree) ((RecursivePrefixTreeStrategy) strategy).getGrid();
//DWS: I know this to be true. 11 is needed for one meter
double degrees = DistanceUtils.dist2Degrees(0.001, DistanceUtils.EARTH_MEAN_RADIUS_KM);
assertEquals(11, grid.getLevelForDistance(degrees));
}
@Test
public void testPrecision() throws IOException{
init(GeohashPrefixTree.getMaxLevelsPossible());
Point iPt = ctx.makePoint(2.8028712999999925, 48.3708044);//lon, lat
addDocument(newDoc("iPt", iPt));
commit();
Point qPt = ctx.makePoint(2.4632387000000335, 48.6003516);
final double KM2DEG = DistanceUtils.dist2Degrees(1, DistanceUtils.EARTH_MEAN_RADIUS_KM);
final double DEG2KM = 1 / KM2DEG;
final double DIST = 35.75;//35.7499...
assertEquals(DIST, ctx.getDistCalc().distance(iPt, qPt) * DEG2KM, 0.001);
//distErrPct will affect the query shape precision. The indexed precision
// was set to nearly zilch via init(GeohashPrefixTree.getMaxLevelsPossible());
final double distErrPct = 0.025; //the suggested default, by the way
final double distMult = 1+distErrPct;
assertTrue(35.74*distMult >= DIST);
checkHits(q(qPt, 35.74 * KM2DEG, distErrPct), 1, null);
assertTrue(30*distMult < DIST);
checkHits(q(qPt, 30 * KM2DEG, distErrPct), 0, null);
assertTrue(33*distMult < DIST);
checkHits(q(qPt, 33 * KM2DEG, distErrPct), 0, null);
assertTrue(34*distMult < DIST);
checkHits(q(qPt, 34 * KM2DEG, distErrPct), 0, null);
}
@Test
public void geohashRecursiveRandom() throws IOException {
init(12);
//1. Iterate test with the cluster at some worldly point of interest
Point[] clusterCenters = new Point[]{ctx.makePoint(-180,0), ctx.makePoint(0,90), ctx.makePoint(0,-90)};
for (Point clusterCenter : clusterCenters) {
//2. Iterate on size of cluster (a really small one and a large one)
String hashCenter = GeohashUtils.encodeLatLon(clusterCenter.getY(), clusterCenter.getX(), maxLength);
//calculate the number of degrees in the smallest grid box size (use for both lat & lon)
String smallBox = hashCenter.substring(0,hashCenter.length()-1);//chop off leaf precision
Rectangle clusterDims = GeohashUtils.decodeBoundary(smallBox,ctx);
double smallRadius = Math.max(clusterDims.getMaxX()-clusterDims.getMinX(),clusterDims.getMaxY()-clusterDims.getMinY());
assert smallRadius < 1;
double largeRadius = 20d;//good large size; don't use >=45 for this test code to work
double[] radiusDegs = {largeRadius,smallRadius};
for (double radiusDeg : radiusDegs) {
//3. Index random points in this cluster circle
deleteAll();
List<Point> points = new ArrayList<Point>();
for(int i = 0; i < 20; i++) {
//Note that this will not result in randomly distributed points in the
// circle, they will be concentrated towards the center a little. But
// it's good enough.
Point pt = ctx.getDistCalc().pointOnBearing(clusterCenter,
random().nextDouble() * radiusDeg, random().nextInt() * 360, ctx, null);
pt = alignGeohash(pt);
points.add(pt);
addDocument(newDoc("" + i, pt));
}
commit();
//3. Use some query centers. Each is twice the cluster's radius away.
for(int ri = 0; ri < 4; ri++) {
Point queryCenter = ctx.getDistCalc().pointOnBearing(clusterCenter,
radiusDeg*2, random().nextInt(360), ctx, null);
queryCenter = alignGeohash(queryCenter);
//4.1 Query a small box getting nothing
checkHits(q(queryCenter, radiusDeg - smallRadius/2), 0, null);
//4.2 Query a large box enclosing the cluster, getting everything
- checkHits(q(queryCenter, radiusDeg*3*1.01), points.size(), null);
+ checkHits(q(queryCenter, radiusDeg*3 + smallRadius/2), points.size(), null);
//4.3 Query a medium box getting some (calculate the correct solution and verify)
double queryDist = radiusDeg * 2;
//Find matching points. Put into int[] of doc ids which is the same thing as the index into points list.
int[] ids = new int[points.size()];
int ids_sz = 0;
for (int i = 0; i < points.size(); i++) {
Point point = points.get(i);
if (ctx.getDistCalc().distance(queryCenter, point) <= queryDist)
ids[ids_sz++] = i;
}
ids = Arrays.copyOf(ids, ids_sz);
//assert ids_sz > 0 (can't because randomness keeps us from being able to)
checkHits(q(queryCenter, queryDist), ids.length, ids);
}
}//for radiusDeg
}//for clusterCenter
}//randomTest()
/** Query point-distance (in degrees) with zero error percent. */
private SpatialArgs q(Point pt, double distDEG) {
return q(pt, distDEG, 0.0);
}
private SpatialArgs q(Point pt, double distDEG, double distErrPct) {
Shape shape = ctx.makeCircle(pt, distDEG);
SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects,shape);
args.setDistErrPct(distErrPct);
return args;
}
private void checkHits(SpatialArgs args, int assertNumFound, int[] assertIds) {
SearchResults got = executeQuery(strategy.makeQuery(args), 100);
assertEquals("" + args, assertNumFound, got.numFound);
if (assertIds != null) {
Set<Integer> gotIds = new HashSet<Integer>();
for (SearchResult result : got.results) {
gotIds.add(Integer.valueOf(result.document.get("id")));
}
for (int assertId : assertIds) {
assertTrue("has "+assertId,gotIds.contains(assertId));
}
}
}
private Document newDoc(String id, Shape shape) {
Document doc = new Document();
doc.add(new StringField("id", id, Field.Store.YES));
for (Field f : strategy.createIndexableFields(shape)) {
doc.add(f);
}
if (storeShape)
doc.add(new StoredField(strategy.getFieldName(), ctx.toString(shape)));
return doc;
}
/** NGeohash round-trip for given precision. */
private Point alignGeohash(Point p) {
return GeohashUtils.decode(GeohashUtils.encodeLatLon(p.getY(), p.getX(), maxLength), ctx);
}
}
| true | true | public void geohashRecursiveRandom() throws IOException {
init(12);
//1. Iterate test with the cluster at some worldly point of interest
Point[] clusterCenters = new Point[]{ctx.makePoint(-180,0), ctx.makePoint(0,90), ctx.makePoint(0,-90)};
for (Point clusterCenter : clusterCenters) {
//2. Iterate on size of cluster (a really small one and a large one)
String hashCenter = GeohashUtils.encodeLatLon(clusterCenter.getY(), clusterCenter.getX(), maxLength);
//calculate the number of degrees in the smallest grid box size (use for both lat & lon)
String smallBox = hashCenter.substring(0,hashCenter.length()-1);//chop off leaf precision
Rectangle clusterDims = GeohashUtils.decodeBoundary(smallBox,ctx);
double smallRadius = Math.max(clusterDims.getMaxX()-clusterDims.getMinX(),clusterDims.getMaxY()-clusterDims.getMinY());
assert smallRadius < 1;
double largeRadius = 20d;//good large size; don't use >=45 for this test code to work
double[] radiusDegs = {largeRadius,smallRadius};
for (double radiusDeg : radiusDegs) {
//3. Index random points in this cluster circle
deleteAll();
List<Point> points = new ArrayList<Point>();
for(int i = 0; i < 20; i++) {
//Note that this will not result in randomly distributed points in the
// circle, they will be concentrated towards the center a little. But
// it's good enough.
Point pt = ctx.getDistCalc().pointOnBearing(clusterCenter,
random().nextDouble() * radiusDeg, random().nextInt() * 360, ctx, null);
pt = alignGeohash(pt);
points.add(pt);
addDocument(newDoc("" + i, pt));
}
commit();
//3. Use some query centers. Each is twice the cluster's radius away.
for(int ri = 0; ri < 4; ri++) {
Point queryCenter = ctx.getDistCalc().pointOnBearing(clusterCenter,
radiusDeg*2, random().nextInt(360), ctx, null);
queryCenter = alignGeohash(queryCenter);
//4.1 Query a small box getting nothing
checkHits(q(queryCenter, radiusDeg - smallRadius/2), 0, null);
//4.2 Query a large box enclosing the cluster, getting everything
checkHits(q(queryCenter, radiusDeg*3*1.01), points.size(), null);
//4.3 Query a medium box getting some (calculate the correct solution and verify)
double queryDist = radiusDeg * 2;
//Find matching points. Put into int[] of doc ids which is the same thing as the index into points list.
int[] ids = new int[points.size()];
int ids_sz = 0;
for (int i = 0; i < points.size(); i++) {
Point point = points.get(i);
if (ctx.getDistCalc().distance(queryCenter, point) <= queryDist)
ids[ids_sz++] = i;
}
ids = Arrays.copyOf(ids, ids_sz);
//assert ids_sz > 0 (can't because randomness keeps us from being able to)
checkHits(q(queryCenter, queryDist), ids.length, ids);
}
}//for radiusDeg
}//for clusterCenter
}//randomTest()
| public void geohashRecursiveRandom() throws IOException {
init(12);
//1. Iterate test with the cluster at some worldly point of interest
Point[] clusterCenters = new Point[]{ctx.makePoint(-180,0), ctx.makePoint(0,90), ctx.makePoint(0,-90)};
for (Point clusterCenter : clusterCenters) {
//2. Iterate on size of cluster (a really small one and a large one)
String hashCenter = GeohashUtils.encodeLatLon(clusterCenter.getY(), clusterCenter.getX(), maxLength);
//calculate the number of degrees in the smallest grid box size (use for both lat & lon)
String smallBox = hashCenter.substring(0,hashCenter.length()-1);//chop off leaf precision
Rectangle clusterDims = GeohashUtils.decodeBoundary(smallBox,ctx);
double smallRadius = Math.max(clusterDims.getMaxX()-clusterDims.getMinX(),clusterDims.getMaxY()-clusterDims.getMinY());
assert smallRadius < 1;
double largeRadius = 20d;//good large size; don't use >=45 for this test code to work
double[] radiusDegs = {largeRadius,smallRadius};
for (double radiusDeg : radiusDegs) {
//3. Index random points in this cluster circle
deleteAll();
List<Point> points = new ArrayList<Point>();
for(int i = 0; i < 20; i++) {
//Note that this will not result in randomly distributed points in the
// circle, they will be concentrated towards the center a little. But
// it's good enough.
Point pt = ctx.getDistCalc().pointOnBearing(clusterCenter,
random().nextDouble() * radiusDeg, random().nextInt() * 360, ctx, null);
pt = alignGeohash(pt);
points.add(pt);
addDocument(newDoc("" + i, pt));
}
commit();
//3. Use some query centers. Each is twice the cluster's radius away.
for(int ri = 0; ri < 4; ri++) {
Point queryCenter = ctx.getDistCalc().pointOnBearing(clusterCenter,
radiusDeg*2, random().nextInt(360), ctx, null);
queryCenter = alignGeohash(queryCenter);
//4.1 Query a small box getting nothing
checkHits(q(queryCenter, radiusDeg - smallRadius/2), 0, null);
//4.2 Query a large box enclosing the cluster, getting everything
checkHits(q(queryCenter, radiusDeg*3 + smallRadius/2), points.size(), null);
//4.3 Query a medium box getting some (calculate the correct solution and verify)
double queryDist = radiusDeg * 2;
//Find matching points. Put into int[] of doc ids which is the same thing as the index into points list.
int[] ids = new int[points.size()];
int ids_sz = 0;
for (int i = 0; i < points.size(); i++) {
Point point = points.get(i);
if (ctx.getDistCalc().distance(queryCenter, point) <= queryDist)
ids[ids_sz++] = i;
}
ids = Arrays.copyOf(ids, ids_sz);
//assert ids_sz > 0 (can't because randomness keeps us from being able to)
checkHits(q(queryCenter, queryDist), ids.length, ids);
}
}//for radiusDeg
}//for clusterCenter
}//randomTest()
|
diff --git a/bindings/java/src/org/hyperic/sigar/test/TestTcpStat.java b/bindings/java/src/org/hyperic/sigar/test/TestTcpStat.java
index 29e52ff0..3a20d6e7 100644
--- a/bindings/java/src/org/hyperic/sigar/test/TestTcpStat.java
+++ b/bindings/java/src/org/hyperic/sigar/test/TestTcpStat.java
@@ -1,52 +1,54 @@
/*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of SIGAR.
*
* SIGAR is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.sigar.test;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarNotImplementedException;
import org.hyperic.sigar.TcpStat;
public class TestTcpStat extends SigarTestCase {
public TestTcpStat(String name) {
super(name);
}
public void testCreate() throws Exception {
Sigar sigar = getSigar();
TcpStat tcp;
try {
tcp = sigar.getTcpStat();
} catch (SigarNotImplementedException e) {
return;
}
traceln("");
- assertGtZeroTrace("MaxConn", tcp.getMaxConn());
+ //assertGtZeroTrace("MaxConn", tcp.getMaxConn()); //XXX -1 on linux
+ traceln("MaxConn=" + tcp.getMaxConn());
assertGtEqZeroTrace("ActiveOpens", tcp.getActiveOpens());
assertGtEqZeroTrace("PassiveOpens", tcp.getPassiveOpens());
assertGtEqZeroTrace("AttemptFails", tcp.getAttemptFails());
+ assertGtEqZeroTrace("EstabResets", tcp.getEstabResets());
assertGtEqZeroTrace("CurrEstab", tcp.getCurrEstab());
assertGtEqZeroTrace("InSegs", tcp.getInSegs());
assertGtEqZeroTrace("OutSegs", tcp.getOutSegs());
assertGtEqZeroTrace("RetransSegs", tcp.getRetransSegs());
assertGtEqZeroTrace("OutRsts", tcp.getOutRsts());
}
}
| false | true | public void testCreate() throws Exception {
Sigar sigar = getSigar();
TcpStat tcp;
try {
tcp = sigar.getTcpStat();
} catch (SigarNotImplementedException e) {
return;
}
traceln("");
assertGtZeroTrace("MaxConn", tcp.getMaxConn());
assertGtEqZeroTrace("ActiveOpens", tcp.getActiveOpens());
assertGtEqZeroTrace("PassiveOpens", tcp.getPassiveOpens());
assertGtEqZeroTrace("AttemptFails", tcp.getAttemptFails());
assertGtEqZeroTrace("CurrEstab", tcp.getCurrEstab());
assertGtEqZeroTrace("InSegs", tcp.getInSegs());
assertGtEqZeroTrace("OutSegs", tcp.getOutSegs());
assertGtEqZeroTrace("RetransSegs", tcp.getRetransSegs());
assertGtEqZeroTrace("OutRsts", tcp.getOutRsts());
}
| public void testCreate() throws Exception {
Sigar sigar = getSigar();
TcpStat tcp;
try {
tcp = sigar.getTcpStat();
} catch (SigarNotImplementedException e) {
return;
}
traceln("");
//assertGtZeroTrace("MaxConn", tcp.getMaxConn()); //XXX -1 on linux
traceln("MaxConn=" + tcp.getMaxConn());
assertGtEqZeroTrace("ActiveOpens", tcp.getActiveOpens());
assertGtEqZeroTrace("PassiveOpens", tcp.getPassiveOpens());
assertGtEqZeroTrace("AttemptFails", tcp.getAttemptFails());
assertGtEqZeroTrace("EstabResets", tcp.getEstabResets());
assertGtEqZeroTrace("CurrEstab", tcp.getCurrEstab());
assertGtEqZeroTrace("InSegs", tcp.getInSegs());
assertGtEqZeroTrace("OutSegs", tcp.getOutSegs());
assertGtEqZeroTrace("RetransSegs", tcp.getRetransSegs());
assertGtEqZeroTrace("OutRsts", tcp.getOutRsts());
}
|
diff --git a/src/com/modcrafting/diablodrops/listeners/TomeListener.java b/src/com/modcrafting/diablodrops/listeners/TomeListener.java
index c148d84..85c737b 100644
--- a/src/com/modcrafting/diablodrops/listeners/TomeListener.java
+++ b/src/com/modcrafting/diablodrops/listeners/TomeListener.java
@@ -1,145 +1,147 @@
package com.modcrafting.diablodrops.listeners;
import java.util.Iterator;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;
import com.modcrafting.diablodrops.DiabloDrops;
import com.modcrafting.diablodrops.events.IdentifyItemEvent;
import com.modcrafting.diablodrops.items.IdentifyTome;
public class TomeListener implements Listener
{
private final DiabloDrops plugin;
public TomeListener(final DiabloDrops plugin)
{
this.plugin = plugin;
}
public ChatColor findColor(final String s)
{
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++)
if ((c[i] == new Character((char) 167)) && ((i + 1) < c.length))
return ChatColor.getByChar(c[i + 1]);
return null;
}
@EventHandler
public void onCraftItem(final CraftItemEvent e)
{
ItemStack item = e.getCurrentItem();
if (item.getType().equals(Material.WRITTEN_BOOK))
{
if (e.isShiftClick())
{
e.setCancelled(true);
}
e.setCurrentItem(new IdentifyTome());
}
}
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.LOWEST)
public void onRightClick(final PlayerInteractEvent e)
{
if ((e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction()
.equals(Action.RIGHT_CLICK_BLOCK))
&& e.getPlayer().getItemInHand().getType()
.equals(Material.WRITTEN_BOOK))
{
ItemStack inh = e.getPlayer().getItemInHand();
BookMeta b = (BookMeta) inh.getItemMeta();
if (b == null)
return;
- if (b.getTitle().contains("Identity Tome")
- && b.getAuthor().endsWith("AAAA"))
+ if (!b.hasTitle() || !b.hasAuthor())
+ return;
+ if (b.getTitle().equalsIgnoreCase(
+ ChatColor.DARK_AQUA + "Identity Tome"))
{
Player p = e.getPlayer();
PlayerInventory pi = p.getInventory();
p.updateInventory();
Iterator<ItemStack> itis = pi.iterator();
while (itis.hasNext())
{
ItemStack tool = itis.next();
if ((tool == null)
|| !plugin.getDropAPI().canBeItem(tool.getType()))
{
continue;
}
ItemMeta meta;
if (tool.hasItemMeta())
meta = tool.getItemMeta();
else
meta = plugin.getServer().getItemFactory()
.getItemMeta(tool.getType());
String name;
if (meta.hasDisplayName())
name = meta.getDisplayName();
else
name = tool.getType().name();
if ((ChatColor.getLastColors(name) == null || (!ChatColor
.getLastColors(name).equalsIgnoreCase(
ChatColor.MAGIC.name()) && !ChatColor
.getLastColors(name).equalsIgnoreCase(
ChatColor.MAGIC.toString()))
&& (!name.contains(ChatColor.MAGIC.name()) && !name
.contains(ChatColor.MAGIC.toString()))))
{
continue;
}
IdentifyItemEvent iie = new IdentifyItemEvent(tool);
plugin.getServer().getPluginManager().callEvent(iie);
if (iie.isCancelled())
{
p.sendMessage(ChatColor.RED
+ "You are unable to identify right now.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
pi.setItemInHand(null);
ItemStack item = plugin.getDropAPI().getItem(tool);
while ((item == null)
|| !item.hasItemMeta()
|| !item.getItemMeta().hasDisplayName()
|| item.getItemMeta().getDisplayName()
.contains(ChatColor.MAGIC.toString()))
{
item = plugin.getDropAPI().getItem(tool);
}
pi.removeItem(tool);
pi.addItem(item);
p.sendMessage(ChatColor.GREEN
+ "You have identified an item!");
p.updateInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
p.closeInventory();
return;
}
p.sendMessage(ChatColor.RED + "You have no items to identify.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
}
}
}
| true | true | public void onRightClick(final PlayerInteractEvent e)
{
if ((e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction()
.equals(Action.RIGHT_CLICK_BLOCK))
&& e.getPlayer().getItemInHand().getType()
.equals(Material.WRITTEN_BOOK))
{
ItemStack inh = e.getPlayer().getItemInHand();
BookMeta b = (BookMeta) inh.getItemMeta();
if (b == null)
return;
if (b.getTitle().contains("Identity Tome")
&& b.getAuthor().endsWith("AAAA"))
{
Player p = e.getPlayer();
PlayerInventory pi = p.getInventory();
p.updateInventory();
Iterator<ItemStack> itis = pi.iterator();
while (itis.hasNext())
{
ItemStack tool = itis.next();
if ((tool == null)
|| !plugin.getDropAPI().canBeItem(tool.getType()))
{
continue;
}
ItemMeta meta;
if (tool.hasItemMeta())
meta = tool.getItemMeta();
else
meta = plugin.getServer().getItemFactory()
.getItemMeta(tool.getType());
String name;
if (meta.hasDisplayName())
name = meta.getDisplayName();
else
name = tool.getType().name();
if ((ChatColor.getLastColors(name) == null || (!ChatColor
.getLastColors(name).equalsIgnoreCase(
ChatColor.MAGIC.name()) && !ChatColor
.getLastColors(name).equalsIgnoreCase(
ChatColor.MAGIC.toString()))
&& (!name.contains(ChatColor.MAGIC.name()) && !name
.contains(ChatColor.MAGIC.toString()))))
{
continue;
}
IdentifyItemEvent iie = new IdentifyItemEvent(tool);
plugin.getServer().getPluginManager().callEvent(iie);
if (iie.isCancelled())
{
p.sendMessage(ChatColor.RED
+ "You are unable to identify right now.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
pi.setItemInHand(null);
ItemStack item = plugin.getDropAPI().getItem(tool);
while ((item == null)
|| !item.hasItemMeta()
|| !item.getItemMeta().hasDisplayName()
|| item.getItemMeta().getDisplayName()
.contains(ChatColor.MAGIC.toString()))
{
item = plugin.getDropAPI().getItem(tool);
}
pi.removeItem(tool);
pi.addItem(item);
p.sendMessage(ChatColor.GREEN
+ "You have identified an item!");
p.updateInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
p.closeInventory();
return;
}
p.sendMessage(ChatColor.RED + "You have no items to identify.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
}
}
| public void onRightClick(final PlayerInteractEvent e)
{
if ((e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction()
.equals(Action.RIGHT_CLICK_BLOCK))
&& e.getPlayer().getItemInHand().getType()
.equals(Material.WRITTEN_BOOK))
{
ItemStack inh = e.getPlayer().getItemInHand();
BookMeta b = (BookMeta) inh.getItemMeta();
if (b == null)
return;
if (!b.hasTitle() || !b.hasAuthor())
return;
if (b.getTitle().equalsIgnoreCase(
ChatColor.DARK_AQUA + "Identity Tome"))
{
Player p = e.getPlayer();
PlayerInventory pi = p.getInventory();
p.updateInventory();
Iterator<ItemStack> itis = pi.iterator();
while (itis.hasNext())
{
ItemStack tool = itis.next();
if ((tool == null)
|| !plugin.getDropAPI().canBeItem(tool.getType()))
{
continue;
}
ItemMeta meta;
if (tool.hasItemMeta())
meta = tool.getItemMeta();
else
meta = plugin.getServer().getItemFactory()
.getItemMeta(tool.getType());
String name;
if (meta.hasDisplayName())
name = meta.getDisplayName();
else
name = tool.getType().name();
if ((ChatColor.getLastColors(name) == null || (!ChatColor
.getLastColors(name).equalsIgnoreCase(
ChatColor.MAGIC.name()) && !ChatColor
.getLastColors(name).equalsIgnoreCase(
ChatColor.MAGIC.toString()))
&& (!name.contains(ChatColor.MAGIC.name()) && !name
.contains(ChatColor.MAGIC.toString()))))
{
continue;
}
IdentifyItemEvent iie = new IdentifyItemEvent(tool);
plugin.getServer().getPluginManager().callEvent(iie);
if (iie.isCancelled())
{
p.sendMessage(ChatColor.RED
+ "You are unable to identify right now.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
pi.setItemInHand(null);
ItemStack item = plugin.getDropAPI().getItem(tool);
while ((item == null)
|| !item.hasItemMeta()
|| !item.getItemMeta().hasDisplayName()
|| item.getItemMeta().getDisplayName()
.contains(ChatColor.MAGIC.toString()))
{
item = plugin.getDropAPI().getItem(tool);
}
pi.removeItem(tool);
pi.addItem(item);
p.sendMessage(ChatColor.GREEN
+ "You have identified an item!");
p.updateInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
p.closeInventory();
return;
}
p.sendMessage(ChatColor.RED + "You have no items to identify.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
}
}
|
diff --git a/web/src/org/openmrs/module/sdmxhdintegration/web/controller/MessageUploadFormController.java b/web/src/org/openmrs/module/sdmxhdintegration/web/controller/MessageUploadFormController.java
index 3d6088f..88a8523 100644
--- a/web/src/org/openmrs/module/sdmxhdintegration/web/controller/MessageUploadFormController.java
+++ b/web/src/org/openmrs/module/sdmxhdintegration/web/controller/MessageUploadFormController.java
@@ -1,152 +1,152 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.sdmxhdintegration.web.controller;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jembi.sdmxhd.dsd.DSD;
import org.jembi.sdmxhd.dsd.KeyFamily;
import org.openmrs.api.AdministrationService;
import org.openmrs.api.context.Context;
import org.openmrs.module.reporting.report.definition.service.ReportDefinitionService;
import org.openmrs.module.sdmxhdintegration.KeyFamilyMapping;
import org.openmrs.module.sdmxhdintegration.SDMXHDMessage;
import org.openmrs.module.sdmxhdintegration.SDMXHDMessageValidator;
import org.openmrs.module.sdmxhdintegration.SDMXHDService;
import org.openmrs.web.WebConstants;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
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.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
@Controller
@SessionAttributes("sdmxhdMessage")
@RequestMapping("/module/sdmxhdintegration/messageUpload")
public class MessageUploadFormController {
private static Log log = LogFactory.getLog(MessageUploadFormController.class);
@RequestMapping(method=RequestMethod.GET)
public void showForm(@RequestParam(value = "sdmxhdmessageid", required = false) Integer sdmxMessageId, ModelMap model) {
if (sdmxMessageId != null) {
SDMXHDService sdmxhdService = (SDMXHDService) Context.getService(SDMXHDService.class);
SDMXHDMessage sdmxhdMessage = sdmxhdService.getSDMXHDMessage(sdmxMessageId);
model.addAttribute("sdmxhdMessage", sdmxhdMessage);
} else {
model.addAttribute("sdmxhdMessage", new SDMXHDMessage());
}
}
@RequestMapping(method=RequestMethod.POST)
public String handleSubmission(HttpServletRequest request,
@ModelAttribute("sdmxhdMessage") SDMXHDMessage sdmxhdMessage,
BindingResult result,
SessionStatus status) throws IllegalStateException {
DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request;
MultipartFile file = req.getFile("sdmxhdMessage");
File destFile = null;
if (!(file.getSize() <= 0)) {
AdministrationService as = Context.getAdministrationService();
String dir = as.getGlobalProperty("sdmxhdintegration.messageUploadDir");
String filename = file.getOriginalFilename();
- filename = "[" + (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")).format(new Date()) + "]" + filename;
+ filename = "_" + (new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss")).format(new Date()) + "_" + filename;
destFile = new File(dir + File.separator + filename);
destFile.mkdirs();
try {
file.transferTo(destFile);
}
catch (IOException e) {
HttpSession session = request.getSession();
session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Could not save file. Make sure you have setup the upload directory using the configuration page and that the directory is readable by the tomcat user.");
return "/module/sdmxhdintegration/messageUpload";
}
sdmxhdMessage.setSdmxhdZipFileName(filename);
}
new SDMXHDMessageValidator().validate(sdmxhdMessage, result);
if (result.hasErrors()) {
log.error("SDMXHDMessage object failed validation");
if (destFile != null) {
destFile.delete();
}
return "/module/sdmxhdintegration/messageUpload";
}
SDMXHDService sdmxhdService = Context.getService(SDMXHDService.class);
ReportDefinitionService rds = Context.getService(ReportDefinitionService.class);
sdmxhdService.saveSDMXHDMessage(sdmxhdMessage);
// delete all existing mappings and reports
List<KeyFamilyMapping> allKeyFamilyMappingsForMsg = sdmxhdService.getKeyFamilyMappingBySDMXHDMessage(sdmxhdMessage);
for (Iterator<KeyFamilyMapping> iterator = allKeyFamilyMappingsForMsg.iterator(); iterator.hasNext();) {
KeyFamilyMapping kfm = iterator.next();
Integer reportDefinitionId = kfm.getReportDefinitionId();
sdmxhdService.purgeKeyFamilyMapping(kfm);
if (reportDefinitionId != null) {
rds.purgeDefinition(rds.getDefinition(reportDefinitionId));
}
}
// create initial keyFamilyMappings
try {
DSD dsd = sdmxhdService.getSDMXHDDataSetDefinition(sdmxhdMessage);
List<KeyFamily> keyFamilies = dsd.getKeyFamilies();
for (Iterator<KeyFamily> iterator = keyFamilies.iterator(); iterator.hasNext();) {
KeyFamily keyFamily = iterator.next();
KeyFamilyMapping kfm = new KeyFamilyMapping();
kfm.setKeyFamilyId(keyFamily.getId());
kfm.setSdmxhdMessage(sdmxhdMessage);
sdmxhdService.saveKeyFamilyMapping(kfm);
}
}
catch (Exception e) {
log.error("Error parsing SDMX-HD Message: " + e, e);
if (destFile != null) {
destFile.delete();
}
sdmxhdService.purgeSDMXHDMessage(sdmxhdMessage);
result.rejectValue("sdmxhdZipFileName", "upload.file.rejected", "This file is not a valid zip file or it does not contain a valid SDMX-HD DataSetDefinition");
return "/module/sdmxhdintegration/messageUpload";
}
return "redirect:viewSDMXHDMessages.list";
}
}
| true | true | public String handleSubmission(HttpServletRequest request,
@ModelAttribute("sdmxhdMessage") SDMXHDMessage sdmxhdMessage,
BindingResult result,
SessionStatus status) throws IllegalStateException {
DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request;
MultipartFile file = req.getFile("sdmxhdMessage");
File destFile = null;
if (!(file.getSize() <= 0)) {
AdministrationService as = Context.getAdministrationService();
String dir = as.getGlobalProperty("sdmxhdintegration.messageUploadDir");
String filename = file.getOriginalFilename();
filename = "[" + (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")).format(new Date()) + "]" + filename;
destFile = new File(dir + File.separator + filename);
destFile.mkdirs();
try {
file.transferTo(destFile);
}
catch (IOException e) {
HttpSession session = request.getSession();
session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Could not save file. Make sure you have setup the upload directory using the configuration page and that the directory is readable by the tomcat user.");
return "/module/sdmxhdintegration/messageUpload";
}
sdmxhdMessage.setSdmxhdZipFileName(filename);
}
new SDMXHDMessageValidator().validate(sdmxhdMessage, result);
if (result.hasErrors()) {
log.error("SDMXHDMessage object failed validation");
if (destFile != null) {
destFile.delete();
}
return "/module/sdmxhdintegration/messageUpload";
}
SDMXHDService sdmxhdService = Context.getService(SDMXHDService.class);
ReportDefinitionService rds = Context.getService(ReportDefinitionService.class);
sdmxhdService.saveSDMXHDMessage(sdmxhdMessage);
// delete all existing mappings and reports
List<KeyFamilyMapping> allKeyFamilyMappingsForMsg = sdmxhdService.getKeyFamilyMappingBySDMXHDMessage(sdmxhdMessage);
for (Iterator<KeyFamilyMapping> iterator = allKeyFamilyMappingsForMsg.iterator(); iterator.hasNext();) {
KeyFamilyMapping kfm = iterator.next();
Integer reportDefinitionId = kfm.getReportDefinitionId();
sdmxhdService.purgeKeyFamilyMapping(kfm);
if (reportDefinitionId != null) {
rds.purgeDefinition(rds.getDefinition(reportDefinitionId));
}
}
// create initial keyFamilyMappings
try {
DSD dsd = sdmxhdService.getSDMXHDDataSetDefinition(sdmxhdMessage);
List<KeyFamily> keyFamilies = dsd.getKeyFamilies();
for (Iterator<KeyFamily> iterator = keyFamilies.iterator(); iterator.hasNext();) {
KeyFamily keyFamily = iterator.next();
KeyFamilyMapping kfm = new KeyFamilyMapping();
kfm.setKeyFamilyId(keyFamily.getId());
kfm.setSdmxhdMessage(sdmxhdMessage);
sdmxhdService.saveKeyFamilyMapping(kfm);
}
}
catch (Exception e) {
log.error("Error parsing SDMX-HD Message: " + e, e);
if (destFile != null) {
destFile.delete();
}
sdmxhdService.purgeSDMXHDMessage(sdmxhdMessage);
result.rejectValue("sdmxhdZipFileName", "upload.file.rejected", "This file is not a valid zip file or it does not contain a valid SDMX-HD DataSetDefinition");
return "/module/sdmxhdintegration/messageUpload";
}
return "redirect:viewSDMXHDMessages.list";
}
| public String handleSubmission(HttpServletRequest request,
@ModelAttribute("sdmxhdMessage") SDMXHDMessage sdmxhdMessage,
BindingResult result,
SessionStatus status) throws IllegalStateException {
DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request;
MultipartFile file = req.getFile("sdmxhdMessage");
File destFile = null;
if (!(file.getSize() <= 0)) {
AdministrationService as = Context.getAdministrationService();
String dir = as.getGlobalProperty("sdmxhdintegration.messageUploadDir");
String filename = file.getOriginalFilename();
filename = "_" + (new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss")).format(new Date()) + "_" + filename;
destFile = new File(dir + File.separator + filename);
destFile.mkdirs();
try {
file.transferTo(destFile);
}
catch (IOException e) {
HttpSession session = request.getSession();
session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Could not save file. Make sure you have setup the upload directory using the configuration page and that the directory is readable by the tomcat user.");
return "/module/sdmxhdintegration/messageUpload";
}
sdmxhdMessage.setSdmxhdZipFileName(filename);
}
new SDMXHDMessageValidator().validate(sdmxhdMessage, result);
if (result.hasErrors()) {
log.error("SDMXHDMessage object failed validation");
if (destFile != null) {
destFile.delete();
}
return "/module/sdmxhdintegration/messageUpload";
}
SDMXHDService sdmxhdService = Context.getService(SDMXHDService.class);
ReportDefinitionService rds = Context.getService(ReportDefinitionService.class);
sdmxhdService.saveSDMXHDMessage(sdmxhdMessage);
// delete all existing mappings and reports
List<KeyFamilyMapping> allKeyFamilyMappingsForMsg = sdmxhdService.getKeyFamilyMappingBySDMXHDMessage(sdmxhdMessage);
for (Iterator<KeyFamilyMapping> iterator = allKeyFamilyMappingsForMsg.iterator(); iterator.hasNext();) {
KeyFamilyMapping kfm = iterator.next();
Integer reportDefinitionId = kfm.getReportDefinitionId();
sdmxhdService.purgeKeyFamilyMapping(kfm);
if (reportDefinitionId != null) {
rds.purgeDefinition(rds.getDefinition(reportDefinitionId));
}
}
// create initial keyFamilyMappings
try {
DSD dsd = sdmxhdService.getSDMXHDDataSetDefinition(sdmxhdMessage);
List<KeyFamily> keyFamilies = dsd.getKeyFamilies();
for (Iterator<KeyFamily> iterator = keyFamilies.iterator(); iterator.hasNext();) {
KeyFamily keyFamily = iterator.next();
KeyFamilyMapping kfm = new KeyFamilyMapping();
kfm.setKeyFamilyId(keyFamily.getId());
kfm.setSdmxhdMessage(sdmxhdMessage);
sdmxhdService.saveKeyFamilyMapping(kfm);
}
}
catch (Exception e) {
log.error("Error parsing SDMX-HD Message: " + e, e);
if (destFile != null) {
destFile.delete();
}
sdmxhdService.purgeSDMXHDMessage(sdmxhdMessage);
result.rejectValue("sdmxhdZipFileName", "upload.file.rejected", "This file is not a valid zip file or it does not contain a valid SDMX-HD DataSetDefinition");
return "/module/sdmxhdintegration/messageUpload";
}
return "redirect:viewSDMXHDMessages.list";
}
|
diff --git a/databus-core/src/main/java/com/inmobi/databus/utils/CalendarHelper.java b/databus-core/src/main/java/com/inmobi/databus/utils/CalendarHelper.java
index d6afefdd..2ab4a042 100644
--- a/databus-core/src/main/java/com/inmobi/databus/utils/CalendarHelper.java
+++ b/databus-core/src/main/java/com/inmobi/databus/utils/CalendarHelper.java
@@ -1,166 +1,166 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.inmobi.databus.utils;
import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.Logger;
public class CalendarHelper {
static Logger logger = Logger.getLogger(CalendarHelper.class);
static String minDirFormatStr = "yyyy" + File.separator + "MM" +
File.separator + "dd" + File.separator + "HH" + File.separator +"mm";
static final ThreadLocal<DateFormat> minDirFormat =
new ThreadLocal<DateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(minDirFormatStr);
}
};
// TODO - all date/time should be returned in a common time zone GMT
public static Date getDateFromStreamDir(Path streamDirPrefix, Path dir) {
String pathStr = dir.toString();
int startIndex = streamDirPrefix.toString().length() + 1;
/* logger.debug("StartIndex [" + startIndex + "] PathStr [" + pathStr
+"] endIndex [" + (startIndex + minDirFormatStr.length()) + "] length ["
+ pathStr.length() +"]");
*/
String dirString = pathStr.substring(startIndex,
startIndex + minDirFormatStr.length());
try {
return minDirFormat.get().parse(dirString);
} catch (ParseException e) {
logger.warn("Could not get date from directory passed", e);
}
return null;
}
public static Calendar getDate(String year, String month, String day) {
return new GregorianCalendar(new Integer(year).intValue(), new Integer(
month).intValue() - 1, new Integer(day).intValue());
}
public static Calendar getDate(Integer year, Integer month, Integer day) {
return new GregorianCalendar(year.intValue(), month.intValue() - 1,
day.intValue());
}
public static Calendar getDateHour(String year, String month, String day,
String hour) {
return new GregorianCalendar(new Integer(year).intValue(), new Integer(
month).intValue() - 1, new Integer(day).intValue(),
new Integer(hour).intValue(), new Integer(0));
}
public static Calendar getDateHourMinute(Integer year, Integer month,
Integer day, Integer hour, Integer minute) {
return new GregorianCalendar(year.intValue(), month.intValue() - 1,
day.intValue(), hour.intValue(), minute.intValue());
}
public static String getCurrentMinute() {
Calendar calendar;
calendar = new GregorianCalendar();
String minute = Integer.toString(calendar.get(Calendar.MINUTE));
return minute;
}
public static String getCurrentHour() {
Calendar calendar;
calendar = new GregorianCalendar();
String hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY));
return hour;
}
public static Calendar getNowTime() {
return new GregorianCalendar();
}
private static String getCurrentDayTimeAsString(boolean includeMinute) {
return getDayTimeAsString(new GregorianCalendar(), includeMinute,
includeMinute);
}
private static String getDayTimeAsString(Calendar calendar,
boolean includeHour,
boolean includeMinute) {
String minute = null;
String hour = null;
String fileNameInnYYMMDDHRMNFormat = null;
String year = Integer.toString(calendar.get(Calendar.YEAR));
String month = Integer.toString(calendar.get(Calendar.MONTH) + 1);
String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));
if (includeHour || includeMinute) {
hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY));
}
if (includeMinute) {
minute = Integer.toString(calendar.get(Calendar.MINUTE));
}
- if (includeHour) {
- fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour;
- } else if (includeMinute) {
+ if (includeMinute) {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour
+ "-" + minute;
+ } else if (includeHour) {
+ fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour;
} else {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day;
}
logger.debug("getCurrentDayTimeAsString :: ["
+ fileNameInnYYMMDDHRMNFormat + "]");
return fileNameInnYYMMDDHRMNFormat;
}
public static String getCurrentDayTimeAsString() {
return getCurrentDayTimeAsString(true);
}
public static String getCurrentDayHourAsString() {
return getDayTimeAsString(new GregorianCalendar(), true, false);
}
public static String getCurrentDateAsString() {
return getCurrentDayTimeAsString(false);
}
public static String getDateAsString(Calendar calendar) {
return getDayTimeAsString(calendar, false, false);
}
public static String getDateTimeAsString(Calendar calendar) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
return format.format(calendar.getTime());
}
public static Calendar getDateTime(String dateTime) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
Calendar calendar = new GregorianCalendar();
try {
calendar.setTime(format.parse(dateTime));
} catch(Exception e){
}
return calendar;
}
}
| false | true | private static String getDayTimeAsString(Calendar calendar,
boolean includeHour,
boolean includeMinute) {
String minute = null;
String hour = null;
String fileNameInnYYMMDDHRMNFormat = null;
String year = Integer.toString(calendar.get(Calendar.YEAR));
String month = Integer.toString(calendar.get(Calendar.MONTH) + 1);
String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));
if (includeHour || includeMinute) {
hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY));
}
if (includeMinute) {
minute = Integer.toString(calendar.get(Calendar.MINUTE));
}
if (includeHour) {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour;
} else if (includeMinute) {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour
+ "-" + minute;
} else {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day;
}
logger.debug("getCurrentDayTimeAsString :: ["
+ fileNameInnYYMMDDHRMNFormat + "]");
return fileNameInnYYMMDDHRMNFormat;
}
| private static String getDayTimeAsString(Calendar calendar,
boolean includeHour,
boolean includeMinute) {
String minute = null;
String hour = null;
String fileNameInnYYMMDDHRMNFormat = null;
String year = Integer.toString(calendar.get(Calendar.YEAR));
String month = Integer.toString(calendar.get(Calendar.MONTH) + 1);
String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));
if (includeHour || includeMinute) {
hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY));
}
if (includeMinute) {
minute = Integer.toString(calendar.get(Calendar.MINUTE));
}
if (includeMinute) {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour
+ "-" + minute;
} else if (includeHour) {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour;
} else {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day;
}
logger.debug("getCurrentDayTimeAsString :: ["
+ fileNameInnYYMMDDHRMNFormat + "]");
return fileNameInnYYMMDDHRMNFormat;
}
|
diff --git a/nexus/nexus-test-harness/nexus-simple-memory-realm/src/test/java/org/sonatype/jsecurity/realms/simple/SimpleRealmTest.java b/nexus/nexus-test-harness/nexus-simple-memory-realm/src/test/java/org/sonatype/jsecurity/realms/simple/SimpleRealmTest.java
index 143ad31f6..75789b7db 100644
--- a/nexus/nexus-test-harness/nexus-simple-memory-realm/src/test/java/org/sonatype/jsecurity/realms/simple/SimpleRealmTest.java
+++ b/nexus/nexus-test-harness/nexus-simple-memory-realm/src/test/java/org/sonatype/jsecurity/realms/simple/SimpleRealmTest.java
@@ -1,173 +1,175 @@
/**
* Sonatype Nexus (TM) Open Source Version.
* Copyright (c) 2008 Sonatype, Inc. All rights reserved.
* Includes the third-party code listed at http://nexus.sonatype.org/dev/attributions.html
* This program is licensed to you under Version 3 only of the GNU General Public License as published by the Free Software Foundation.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License Version 3 for more details.
* You should have received a copy of the GNU General Public License Version 3 along with this program.
* If not, see http://www.gnu.org/licenses/.
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc.
* "Sonatype" and "Sonatype Nexus" are trademarks of Sonatype, Inc.
*/
package org.sonatype.jsecurity.realms.simple;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import junit.framework.Assert;
import org.codehaus.plexus.util.IOUtil;
import org.jsecurity.authc.AuthenticationException;
import org.jsecurity.authc.AuthenticationInfo;
import org.jsecurity.authc.AuthenticationToken;
import org.jsecurity.authc.UsernamePasswordToken;
import org.jsecurity.subject.PrincipalCollection;
import org.jsecurity.subject.SimplePrincipalCollection;
import org.sonatype.jsecurity.realms.PlexusSecurity;
import org.sonatype.nexus.AbstractNexusTestCase;
public class SimpleRealmTest
extends AbstractNexusTestCase
{
// Realm Tests
/**
* Test authentication with a valid user and password.
*
* @throws Exception
*/
public void testValidAuthentication()
throws Exception
{
PlexusSecurity plexusSecurity = this.lookup( PlexusSecurity.class, "web" );
AuthenticationToken token = new UsernamePasswordToken( "admin-simple", "admin123" );
AuthenticationInfo authInfo = plexusSecurity.authenticate( token );
// check
Assert.assertNotNull( authInfo );
}
/**
* Test authentication with a valid user and invalid password.
*
* @throws Exception
*/
public void testInvalidPasswordAuthentication()
throws Exception
{
PlexusSecurity plexusSecurity = this.lookup( PlexusSecurity.class, "web" );
AuthenticationToken token = new UsernamePasswordToken( "admin-simple", "INVALID" );
try
{
AuthenticationInfo authInfo = plexusSecurity.authenticate( token );
}
catch ( AuthenticationException e )
{
// expected
}
}
/**
* Test authentication with a invalid user and password.
*
* @throws Exception
*/
public void testInvalidUserAuthentication()
throws Exception
{
PlexusSecurity plexusSecurity = this.lookup( PlexusSecurity.class, "web" );
AuthenticationToken token = new UsernamePasswordToken( "INVALID", "INVALID" );
try
{
AuthenticationInfo authInfo = plexusSecurity.authenticate( token );
}
catch ( AuthenticationException e )
{
// expected
}
}
//
/**
* Test authorization using the NexusMethodAuthorizingRealm. <BR/> Take a look a the security.xml in
* src/test/resources this maps the users in the UserStore to nexus roles/privileges
*
* @throws Exception
*/
public void testPrivileges()
throws Exception
{
PlexusSecurity plexusSecurity = this.lookup( PlexusSecurity.class, "web" );
PrincipalCollection principal = new SimplePrincipalCollection( "admin-simple", PlexusSecurity.class
.getSimpleName() );
// test one of the privleges that the admin user has
Assert.assertTrue( plexusSecurity.isPermitted( principal, "nexus:repositories:create" ) );// Repositories -
// (create,read)
}
/**
* Tests a valid privilege for an invalid user
* @throws Exception
*/
public void testPrivilegesInvalidUser()
throws Exception
{
PlexusSecurity plexusSecurity = this.lookup( PlexusSecurity.class, "web" );
PrincipalCollection principal = new SimplePrincipalCollection( "INVALID", PlexusSecurity.class
.getSimpleName() );
// test one of the privleges
Assert.assertFalse( plexusSecurity.isPermitted( principal, "nexus:repositories:create" ) );// Repositories -
// (create,read)
}
@Override
protected void setUp()
throws Exception
{
// call super
super.setUp();
// copy the tests nexus.xml and security.xml to the correct location
this.copyTestConfigToPlace();
}
private void copyTestConfigToPlace()
throws FileNotFoundException,
IOException
{
InputStream nexusConf = null;
InputStream securityConf = null;
OutputStream nexusOut = null;
OutputStream securityOut = null;
try
{
nexusConf = Thread.currentThread().getContextClassLoader().getResourceAsStream( "nexus.xml" );
nexusOut = new FileOutputStream( getNexusConfiguration() );
IOUtil.copy( nexusConf, nexusOut );
securityConf = Thread.currentThread().getContextClassLoader().getResourceAsStream( "security.xml" );
securityOut = new FileOutputStream( getNexusSecurityConfiguration() );
IOUtil.copy( securityConf, securityOut);
}
finally
{
IOUtil.close( nexusConf );
IOUtil.close( securityConf );
+ IOUtil.close( nexusOut );
+ IOUtil.close( securityOut );
}
}
}
| true | true | private void copyTestConfigToPlace()
throws FileNotFoundException,
IOException
{
InputStream nexusConf = null;
InputStream securityConf = null;
OutputStream nexusOut = null;
OutputStream securityOut = null;
try
{
nexusConf = Thread.currentThread().getContextClassLoader().getResourceAsStream( "nexus.xml" );
nexusOut = new FileOutputStream( getNexusConfiguration() );
IOUtil.copy( nexusConf, nexusOut );
securityConf = Thread.currentThread().getContextClassLoader().getResourceAsStream( "security.xml" );
securityOut = new FileOutputStream( getNexusSecurityConfiguration() );
IOUtil.copy( securityConf, securityOut);
}
finally
{
IOUtil.close( nexusConf );
IOUtil.close( securityConf );
}
}
| private void copyTestConfigToPlace()
throws FileNotFoundException,
IOException
{
InputStream nexusConf = null;
InputStream securityConf = null;
OutputStream nexusOut = null;
OutputStream securityOut = null;
try
{
nexusConf = Thread.currentThread().getContextClassLoader().getResourceAsStream( "nexus.xml" );
nexusOut = new FileOutputStream( getNexusConfiguration() );
IOUtil.copy( nexusConf, nexusOut );
securityConf = Thread.currentThread().getContextClassLoader().getResourceAsStream( "security.xml" );
securityOut = new FileOutputStream( getNexusSecurityConfiguration() );
IOUtil.copy( securityConf, securityOut);
}
finally
{
IOUtil.close( nexusConf );
IOUtil.close( securityConf );
IOUtil.close( nexusOut );
IOUtil.close( securityOut );
}
}
|
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.java
index fe328612d..5c5ed4061 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.java
@@ -1,696 +1,700 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.client.solrj.impl;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.ClientParamBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.solr.client.solrj.ResponseParser;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.RequestWriter;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.ContentStream;
import org.apache.solr.common.util.NamedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpSolrServer extends SolrServer {
private static final String UTF_8 = "UTF-8";
private static final String DEFAULT_PATH = "/select";
private static final long serialVersionUID = -946812319974801896L;
/**
* User-Agent String.
*/
public static final String AGENT = "Solr[" + HttpSolrServer.class.getName()
+ "] 1.0";
private static Logger log = LoggerFactory.getLogger(HttpSolrServer.class);
/**
* The URL of the Solr server.
*/
protected String baseUrl;
/**
* Default value: null / empty.
* <p/>
* Parameters that are added to every request regardless. This may be a place
* to add something like an authentication token.
*/
protected ModifiableSolrParams invariantParams;
/**
* Default response parser is BinaryResponseParser
* <p/>
* This parser represents the default Response Parser chosen to parse the
* response if the parser were not specified as part of the request.
*
* @see org.apache.solr.client.solrj.impl.BinaryResponseParser
*/
protected ResponseParser parser;
/**
* The RequestWriter used to write all requests to Solr
*
* @see org.apache.solr.client.solrj.request.RequestWriter
*/
protected RequestWriter requestWriter = new RequestWriter();
private final HttpClient httpClient;
/**
* This defaults to false under the assumption that if you are following a
* redirect to get to a Solr installation, something is misconfigured
* somewhere.
*/
private boolean followRedirects = false;
/**
* Maximum number of retries to attempt in the event of transient errors.
* Default: 0 (no) retries. No more than 1 recommended.
*/
private int maxRetries = 0;
private ThreadSafeClientConnManager ccm;
private boolean useMultiPartPost;
/**
* @param baseURL
* The URL of the Solr server. For example, "
* <code>http://localhost:8983/solr/</code>" if you are using the
* standard distribution Solr webapp on your local machine.
*/
public HttpSolrServer(String baseURL) {
this(baseURL, null, new BinaryResponseParser());
}
public HttpSolrServer(String baseURL, HttpClient client) {
this(baseURL, client, new BinaryResponseParser());
}
public HttpSolrServer(String baseURL, HttpClient client, ResponseParser parser) {
this.baseUrl = baseURL;
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
}
if (baseUrl.indexOf('?') >= 0) {
throw new RuntimeException(
"Invalid base url for solrj. The base URL must not contain parameters: "
+ baseUrl);
}
if (client != null) {
httpClient = client;
} else {
httpClient = createClient();
}
this.parser = parser;
}
private DefaultHttpClient createClient() {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
.getSocketFactory()));
schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory
.getSocketFactory()));
ccm = new ThreadSafeClientConnManager(schemeRegistry);
// Increase default max connection per route to 32
ccm.setDefaultMaxPerRoute(32);
// Increase max total connection to 128
ccm.setMaxTotal(128);
DefaultHttpClient httpClient = new DefaultHttpClient(ccm);
httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
followRedirects);
return httpClient;
}
/**
* Process the request. If
* {@link org.apache.solr.client.solrj.SolrRequest#getResponseParser()} is
* null, then use {@link #getParser()}
*
* @param request
* The {@link org.apache.solr.client.solrj.SolrRequest} to process
* @return The {@link org.apache.solr.common.util.NamedList} result
* @throws SolrServerException
* @throws IOException
*
* @see #request(org.apache.solr.client.solrj.SolrRequest,
* org.apache.solr.client.solrj.ResponseParser)
*/
@Override
public NamedList<Object> request(final SolrRequest request)
throws SolrServerException, IOException {
ResponseParser responseParser = request.getResponseParser();
if (responseParser == null) {
responseParser = parser;
}
return request(request, responseParser);
}
public NamedList<Object> request(final SolrRequest request,
final ResponseParser processor) throws SolrServerException, IOException {
HttpRequestBase method = null;
InputStream is = null;
SolrParams params = request.getParams();
Collection<ContentStream> streams = requestWriter.getContentStreams(request);
String path = requestWriter.getPath(request);
if (path == null || !path.startsWith("/")) {
path = DEFAULT_PATH;
}
ResponseParser parser = request.getResponseParser();
if (parser == null) {
parser = this.parser;
}
// The parser 'wt=' and 'version=' params are used instead of the original
// params
ModifiableSolrParams wparams = new ModifiableSolrParams(params);
wparams.set(CommonParams.WT, parser.getWriterType());
wparams.set(CommonParams.VERSION, parser.getVersion());
if (invariantParams != null) {
wparams.add(invariantParams);
}
params = wparams;
int tries = maxRetries + 1;
try {
while( tries-- > 0 ) {
// Note: since we aren't do intermittent time keeping
// ourselves, the potential non-timeout latency could be as
// much as tries-times (plus scheduling effects) the given
// timeAllowed.
try {
if( SolrRequest.METHOD.GET == request.getMethod() ) {
if( streams != null ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!" );
}
method = new HttpGet( baseUrl + path + ClientUtils.toQueryString( params, false ) );
}
else if( SolrRequest.METHOD.POST == request.getMethod() ) {
String url = baseUrl + path;
boolean isMultipart = ( streams != null && streams.size() > 1 );
LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>();
if (streams == null || isMultipart) {
HttpPost post = new HttpPost(url);
post.setHeader("Content-Charset", "UTF-8");
if (!this.useMultiPartPost && !isMultipart) {
post.addHeader("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
}
List<FormBodyPart> parts = new LinkedList<FormBodyPart>();
Iterator<String> iter = params.getParameterNamesIterator();
while (iter.hasNext()) {
String p = iter.next();
String[] vals = params.getParams(p);
if (vals != null) {
for (String v : vals) {
if (this.useMultiPartPost || isMultipart) {
parts.add(new FormBodyPart(p, new StringBody(v, Charset.forName("UTF-8"))));
} else {
postParams.add(new BasicNameValuePair(p, v));
}
}
}
}
if (isMultipart) {
for (ContentStream content : streams) {
- parts.add(new FormBodyPart(content.getName(), new InputStreamBody(content.getStream(), content.getName())));
+ parts.add(new FormBodyPart(content.getName(),
+ new InputStreamBody(
+ content.getStream(),
+ content.getContentType(),
+ content.getName())));
}
}
if (parts.size() > 0) {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(FormBodyPart p: parts) {
entity.addPart(p);
}
post.setEntity(entity);
} else {
//not using multipart
HttpEntity e;
post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
}
method = post;
}
// It is has one stream, it is the post body, put the params in the URL
else {
String pstr = ClientUtils.toQueryString(params, false);
HttpPost post = new HttpPost(url + pstr);
// Single stream as body
// Using a loop just to get the first one
final ContentStream[] contentStream = new ContentStream[1];
for (ContentStream content : streams) {
contentStream[0] = content;
break;
}
if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
} else {
post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
}
method = post;
}
}
else {
throw new SolrServerException("Unsupported method: "+request.getMethod() );
}
}
catch( NoHttpResponseException r ) {
method = null;
if(is != null) {
is.close();
}
// If out of tries then just rethrow (as normal error).
if (tries < 1) {
throw r;
}
}
}
} catch (IOException ex) {
throw new SolrServerException("error reading streams", ex);
}
// TODO: move to a interceptor?
method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
followRedirects);
method.addHeader("User-Agent", AGENT);
InputStream respBody = null;
try {
// Execute the method.
final HttpResponse response = httpClient.execute(method);
int httpStatus = response.getStatusLine().getStatusCode();
// Read the contents
String charset = EntityUtils.getContentCharSet(response.getEntity());
respBody = response.getEntity().getContent();
// handle some http level checks before trying to parse the response
switch (httpStatus) {
case HttpStatus.SC_OK:
case HttpStatus.SC_BAD_REQUEST:
break;
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_MOVED_TEMPORARILY:
if (!followRedirects) {
throw new SolrServerException("Server at " + getBaseURL()
+ " sent back a redirect (" + httpStatus + ").");
}
break;
case HttpStatus.SC_NOT_FOUND:
throw new SolrServerException("Server at " + getBaseURL()
+ " was not found (404).");
default:
throw new SolrException(SolrException.ErrorCode.getErrorCode(httpStatus), "Server at " + getBaseURL()
+ " returned non ok status:" + httpStatus + ", message:"
+ response.getStatusLine().getReasonPhrase());
}
NamedList<Object> rsp = processor.processResponse(respBody, charset);
if (httpStatus != HttpStatus.SC_OK) {
String reason = null;
try {
NamedList err = (NamedList) rsp.get("error");
if (err != null) {
reason = (String) err.get("msg");
// TODO? get the trace?
}
} catch (Exception ex) {}
if (reason == null) {
StringBuilder msg = new StringBuilder();
msg.append(response.getStatusLine().getReasonPhrase());
msg.append("\n\n");
msg.append("request: " + method.getURI());
reason = java.net.URLDecoder.decode(msg.toString(), UTF_8);
}
throw new SolrException(
SolrException.ErrorCode.getErrorCode(httpStatus), reason);
}
return rsp;
} catch (ConnectException e) {
throw new SolrServerException("Server refused connection at: "
+ getBaseURL(), e);
} catch (SocketTimeoutException e) {
throw new SolrServerException(
"Timeout occured while waiting response from server at: "
+ getBaseURL(), e);
} catch (IOException e) {
throw new SolrServerException(
"IOException occured when talking to server at: " + getBaseURL(), e);
} finally {
if (respBody != null) {
try {
respBody.close();
} catch (Throwable t) {} // ignore
}
}
}
// -------------------------------------------------------------------
// -------------------------------------------------------------------
/**
* Retrieve the default list of parameters are added to every request
* regardless.
*
* @see #invariantParams
*/
public ModifiableSolrParams getInvariantParams() {
return invariantParams;
}
public String getBaseURL() {
return baseUrl;
}
public void setBaseURL(String baseURL) {
this.baseUrl = baseURL;
}
public ResponseParser getParser() {
return parser;
}
/**
* Note: This setter method is <b>not thread-safe</b>.
*
* @param processor
* Default Response Parser chosen to parse the response if the parser
* were not specified as part of the request.
* @see org.apache.solr.client.solrj.SolrRequest#getResponseParser()
*/
public void setParser(ResponseParser processor) {
parser = processor;
}
public HttpClient getHttpClient() {
return httpClient;
}
/**
* HttpConnectionParams.setConnectionTimeout
*
* @param timeout
* Timeout in milliseconds
**/
public void setConnectionTimeout(int timeout) {
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), timeout);
}
/**
* Sets HttpConnectionParams.setSoTimeout (read timeout). This is desirable
* for queries, but probably not for indexing.
*
* @param timeout
* Timeout in milliseconds
**/
public void setSoTimeout(int timeout) {
HttpConnectionParams.setSoTimeout(httpClient.getParams(), timeout);
}
/**
* HttpClientParams.setRedirecting
*
* @see #followRedirects
*/
public void setFollowRedirects(boolean followRedirects) {
this.followRedirects = followRedirects;
new ClientParamBean(httpClient.getParams())
.setHandleRedirects(followRedirects);
}
private static class UseCompressionRequestInterceptor implements
HttpRequestInterceptor {
@Override
public void process(HttpRequest request, HttpContext context)
throws HttpException, IOException {
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip, deflate");
}
}
}
private static class UseCompressionResponseInterceptor implements
HttpResponseInterceptor {
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
HttpEntity entity = response.getEntity();
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response
.setEntity(new GzipDecompressingEntity(response.getEntity()));
return;
}
if (codecs[i].getName().equalsIgnoreCase("deflate")) {
response.setEntity(new DeflateDecompressingEntity(response
.getEntity()));
return;
}
}
}
}
}
private static class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
public InputStream getContent() throws IOException, IllegalStateException {
return new GZIPInputStream(wrappedEntity.getContent());
}
public long getContentLength() {
return -1;
}
}
private static class DeflateDecompressingEntity extends
GzipDecompressingEntity {
public DeflateDecompressingEntity(final HttpEntity entity) {
super(entity);
}
public InputStream getContent() throws IOException, IllegalStateException {
return new InflaterInputStream(wrappedEntity.getContent());
}
}
/**
* Allow server->client communication to be compressed. Currently gzip and
* deflate are supported. If the server supports compression the response will
* be compressed.
*/
public void setAllowCompression(boolean allowCompression) {
if (httpClient instanceof DefaultHttpClient) {
final DefaultHttpClient client = (DefaultHttpClient) httpClient;
client
.removeRequestInterceptorByClass(UseCompressionRequestInterceptor.class);
client
.removeResponseInterceptorByClass(UseCompressionResponseInterceptor.class);
if (allowCompression) {
client.addRequestInterceptor(new UseCompressionRequestInterceptor());
client.addResponseInterceptor(new UseCompressionResponseInterceptor());
}
} else {
throw new UnsupportedOperationException(
"HttpClient instance was not of type DefaultHttpClient");
}
}
/**
* Set maximum number of retries to attempt in the event of transient errors.
*
* @param maxRetries
* No more than 1 recommended
* @see #maxRetries
*/
public void setMaxRetries(int maxRetries) {
if (maxRetries > 1) {
log.warn("CommonsHttpSolrServer: maximum Retries " + maxRetries
+ " > 1. Maximum recommended retries is 1.");
}
this.maxRetries = maxRetries;
}
public void setRequestWriter(RequestWriter requestWriter) {
this.requestWriter = requestWriter;
}
/**
* Adds the documents supplied by the given iterator.
*
* @param docIterator
* the iterator which returns SolrInputDocument instances
*
* @return the response from the SolrServer
*/
public UpdateResponse add(Iterator<SolrInputDocument> docIterator)
throws SolrServerException, IOException {
UpdateRequest req = new UpdateRequest();
req.setDocIterator(docIterator);
return req.process(this);
}
/**
* Adds the beans supplied by the given iterator.
*
* @param beanIterator
* the iterator which returns Beans
*
* @return the response from the SolrServer
*/
public UpdateResponse addBeans(final Iterator<?> beanIterator)
throws SolrServerException, IOException {
UpdateRequest req = new UpdateRequest();
req.setDocIterator(new Iterator<SolrInputDocument>() {
public boolean hasNext() {
return beanIterator.hasNext();
}
public SolrInputDocument next() {
Object o = beanIterator.next();
if (o == null) return null;
return getBinder().toSolrInputDocument(o);
}
public void remove() {
beanIterator.remove();
}
});
return req.process(this);
}
public void shutdown() {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
}
public void setDefaultMaxConnectionsPerHost(int max) {
if (ccm != null) {
ccm.setDefaultMaxPerRoute(max);
} else {
throw new UnsupportedOperationException(
"Client was created outside of HttpSolrServer");
}
}
/**
* Set the maximum number of connections that can be open at any given time.
*/
public void setMaxTotalConnections(int max) {
if (ccm != null) {
ccm.setMaxTotal(max);
} else {
throw new UnsupportedOperationException(
"Client was created outside of HttpSolrServer");
}
}
}
| true | true | public NamedList<Object> request(final SolrRequest request,
final ResponseParser processor) throws SolrServerException, IOException {
HttpRequestBase method = null;
InputStream is = null;
SolrParams params = request.getParams();
Collection<ContentStream> streams = requestWriter.getContentStreams(request);
String path = requestWriter.getPath(request);
if (path == null || !path.startsWith("/")) {
path = DEFAULT_PATH;
}
ResponseParser parser = request.getResponseParser();
if (parser == null) {
parser = this.parser;
}
// The parser 'wt=' and 'version=' params are used instead of the original
// params
ModifiableSolrParams wparams = new ModifiableSolrParams(params);
wparams.set(CommonParams.WT, parser.getWriterType());
wparams.set(CommonParams.VERSION, parser.getVersion());
if (invariantParams != null) {
wparams.add(invariantParams);
}
params = wparams;
int tries = maxRetries + 1;
try {
while( tries-- > 0 ) {
// Note: since we aren't do intermittent time keeping
// ourselves, the potential non-timeout latency could be as
// much as tries-times (plus scheduling effects) the given
// timeAllowed.
try {
if( SolrRequest.METHOD.GET == request.getMethod() ) {
if( streams != null ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!" );
}
method = new HttpGet( baseUrl + path + ClientUtils.toQueryString( params, false ) );
}
else if( SolrRequest.METHOD.POST == request.getMethod() ) {
String url = baseUrl + path;
boolean isMultipart = ( streams != null && streams.size() > 1 );
LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>();
if (streams == null || isMultipart) {
HttpPost post = new HttpPost(url);
post.setHeader("Content-Charset", "UTF-8");
if (!this.useMultiPartPost && !isMultipart) {
post.addHeader("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
}
List<FormBodyPart> parts = new LinkedList<FormBodyPart>();
Iterator<String> iter = params.getParameterNamesIterator();
while (iter.hasNext()) {
String p = iter.next();
String[] vals = params.getParams(p);
if (vals != null) {
for (String v : vals) {
if (this.useMultiPartPost || isMultipart) {
parts.add(new FormBodyPart(p, new StringBody(v, Charset.forName("UTF-8"))));
} else {
postParams.add(new BasicNameValuePair(p, v));
}
}
}
}
if (isMultipart) {
for (ContentStream content : streams) {
parts.add(new FormBodyPart(content.getName(), new InputStreamBody(content.getStream(), content.getName())));
}
}
if (parts.size() > 0) {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(FormBodyPart p: parts) {
entity.addPart(p);
}
post.setEntity(entity);
} else {
//not using multipart
HttpEntity e;
post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
}
method = post;
}
// It is has one stream, it is the post body, put the params in the URL
else {
String pstr = ClientUtils.toQueryString(params, false);
HttpPost post = new HttpPost(url + pstr);
// Single stream as body
// Using a loop just to get the first one
final ContentStream[] contentStream = new ContentStream[1];
for (ContentStream content : streams) {
contentStream[0] = content;
break;
}
if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
} else {
post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
}
method = post;
}
}
else {
throw new SolrServerException("Unsupported method: "+request.getMethod() );
}
}
catch( NoHttpResponseException r ) {
method = null;
if(is != null) {
is.close();
}
// If out of tries then just rethrow (as normal error).
if (tries < 1) {
throw r;
}
}
}
} catch (IOException ex) {
throw new SolrServerException("error reading streams", ex);
}
// TODO: move to a interceptor?
method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
followRedirects);
method.addHeader("User-Agent", AGENT);
InputStream respBody = null;
try {
// Execute the method.
final HttpResponse response = httpClient.execute(method);
int httpStatus = response.getStatusLine().getStatusCode();
// Read the contents
String charset = EntityUtils.getContentCharSet(response.getEntity());
respBody = response.getEntity().getContent();
// handle some http level checks before trying to parse the response
switch (httpStatus) {
case HttpStatus.SC_OK:
case HttpStatus.SC_BAD_REQUEST:
break;
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_MOVED_TEMPORARILY:
if (!followRedirects) {
throw new SolrServerException("Server at " + getBaseURL()
+ " sent back a redirect (" + httpStatus + ").");
}
break;
case HttpStatus.SC_NOT_FOUND:
throw new SolrServerException("Server at " + getBaseURL()
+ " was not found (404).");
default:
throw new SolrException(SolrException.ErrorCode.getErrorCode(httpStatus), "Server at " + getBaseURL()
+ " returned non ok status:" + httpStatus + ", message:"
+ response.getStatusLine().getReasonPhrase());
}
NamedList<Object> rsp = processor.processResponse(respBody, charset);
if (httpStatus != HttpStatus.SC_OK) {
String reason = null;
try {
NamedList err = (NamedList) rsp.get("error");
if (err != null) {
reason = (String) err.get("msg");
// TODO? get the trace?
}
} catch (Exception ex) {}
if (reason == null) {
StringBuilder msg = new StringBuilder();
msg.append(response.getStatusLine().getReasonPhrase());
msg.append("\n\n");
msg.append("request: " + method.getURI());
reason = java.net.URLDecoder.decode(msg.toString(), UTF_8);
}
throw new SolrException(
SolrException.ErrorCode.getErrorCode(httpStatus), reason);
}
return rsp;
} catch (ConnectException e) {
throw new SolrServerException("Server refused connection at: "
+ getBaseURL(), e);
} catch (SocketTimeoutException e) {
throw new SolrServerException(
"Timeout occured while waiting response from server at: "
+ getBaseURL(), e);
} catch (IOException e) {
throw new SolrServerException(
"IOException occured when talking to server at: " + getBaseURL(), e);
} finally {
if (respBody != null) {
try {
respBody.close();
} catch (Throwable t) {} // ignore
}
}
}
| public NamedList<Object> request(final SolrRequest request,
final ResponseParser processor) throws SolrServerException, IOException {
HttpRequestBase method = null;
InputStream is = null;
SolrParams params = request.getParams();
Collection<ContentStream> streams = requestWriter.getContentStreams(request);
String path = requestWriter.getPath(request);
if (path == null || !path.startsWith("/")) {
path = DEFAULT_PATH;
}
ResponseParser parser = request.getResponseParser();
if (parser == null) {
parser = this.parser;
}
// The parser 'wt=' and 'version=' params are used instead of the original
// params
ModifiableSolrParams wparams = new ModifiableSolrParams(params);
wparams.set(CommonParams.WT, parser.getWriterType());
wparams.set(CommonParams.VERSION, parser.getVersion());
if (invariantParams != null) {
wparams.add(invariantParams);
}
params = wparams;
int tries = maxRetries + 1;
try {
while( tries-- > 0 ) {
// Note: since we aren't do intermittent time keeping
// ourselves, the potential non-timeout latency could be as
// much as tries-times (plus scheduling effects) the given
// timeAllowed.
try {
if( SolrRequest.METHOD.GET == request.getMethod() ) {
if( streams != null ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!" );
}
method = new HttpGet( baseUrl + path + ClientUtils.toQueryString( params, false ) );
}
else if( SolrRequest.METHOD.POST == request.getMethod() ) {
String url = baseUrl + path;
boolean isMultipart = ( streams != null && streams.size() > 1 );
LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>();
if (streams == null || isMultipart) {
HttpPost post = new HttpPost(url);
post.setHeader("Content-Charset", "UTF-8");
if (!this.useMultiPartPost && !isMultipart) {
post.addHeader("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
}
List<FormBodyPart> parts = new LinkedList<FormBodyPart>();
Iterator<String> iter = params.getParameterNamesIterator();
while (iter.hasNext()) {
String p = iter.next();
String[] vals = params.getParams(p);
if (vals != null) {
for (String v : vals) {
if (this.useMultiPartPost || isMultipart) {
parts.add(new FormBodyPart(p, new StringBody(v, Charset.forName("UTF-8"))));
} else {
postParams.add(new BasicNameValuePair(p, v));
}
}
}
}
if (isMultipart) {
for (ContentStream content : streams) {
parts.add(new FormBodyPart(content.getName(),
new InputStreamBody(
content.getStream(),
content.getContentType(),
content.getName())));
}
}
if (parts.size() > 0) {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(FormBodyPart p: parts) {
entity.addPart(p);
}
post.setEntity(entity);
} else {
//not using multipart
HttpEntity e;
post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
}
method = post;
}
// It is has one stream, it is the post body, put the params in the URL
else {
String pstr = ClientUtils.toQueryString(params, false);
HttpPost post = new HttpPost(url + pstr);
// Single stream as body
// Using a loop just to get the first one
final ContentStream[] contentStream = new ContentStream[1];
for (ContentStream content : streams) {
contentStream[0] = content;
break;
}
if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
} else {
post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
}
method = post;
}
}
else {
throw new SolrServerException("Unsupported method: "+request.getMethod() );
}
}
catch( NoHttpResponseException r ) {
method = null;
if(is != null) {
is.close();
}
// If out of tries then just rethrow (as normal error).
if (tries < 1) {
throw r;
}
}
}
} catch (IOException ex) {
throw new SolrServerException("error reading streams", ex);
}
// TODO: move to a interceptor?
method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
followRedirects);
method.addHeader("User-Agent", AGENT);
InputStream respBody = null;
try {
// Execute the method.
final HttpResponse response = httpClient.execute(method);
int httpStatus = response.getStatusLine().getStatusCode();
// Read the contents
String charset = EntityUtils.getContentCharSet(response.getEntity());
respBody = response.getEntity().getContent();
// handle some http level checks before trying to parse the response
switch (httpStatus) {
case HttpStatus.SC_OK:
case HttpStatus.SC_BAD_REQUEST:
break;
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_MOVED_TEMPORARILY:
if (!followRedirects) {
throw new SolrServerException("Server at " + getBaseURL()
+ " sent back a redirect (" + httpStatus + ").");
}
break;
case HttpStatus.SC_NOT_FOUND:
throw new SolrServerException("Server at " + getBaseURL()
+ " was not found (404).");
default:
throw new SolrException(SolrException.ErrorCode.getErrorCode(httpStatus), "Server at " + getBaseURL()
+ " returned non ok status:" + httpStatus + ", message:"
+ response.getStatusLine().getReasonPhrase());
}
NamedList<Object> rsp = processor.processResponse(respBody, charset);
if (httpStatus != HttpStatus.SC_OK) {
String reason = null;
try {
NamedList err = (NamedList) rsp.get("error");
if (err != null) {
reason = (String) err.get("msg");
// TODO? get the trace?
}
} catch (Exception ex) {}
if (reason == null) {
StringBuilder msg = new StringBuilder();
msg.append(response.getStatusLine().getReasonPhrase());
msg.append("\n\n");
msg.append("request: " + method.getURI());
reason = java.net.URLDecoder.decode(msg.toString(), UTF_8);
}
throw new SolrException(
SolrException.ErrorCode.getErrorCode(httpStatus), reason);
}
return rsp;
} catch (ConnectException e) {
throw new SolrServerException("Server refused connection at: "
+ getBaseURL(), e);
} catch (SocketTimeoutException e) {
throw new SolrServerException(
"Timeout occured while waiting response from server at: "
+ getBaseURL(), e);
} catch (IOException e) {
throw new SolrServerException(
"IOException occured when talking to server at: " + getBaseURL(), e);
} finally {
if (respBody != null) {
try {
respBody.close();
} catch (Throwable t) {} // ignore
}
}
}
|
diff --git a/VAGGS/src/com/vaggs/Utils/DebuggingDBObjects.java b/VAGGS/src/com/vaggs/Utils/DebuggingDBObjects.java
index 3d4c376..3f855d1 100644
--- a/VAGGS/src/com/vaggs/Utils/DebuggingDBObjects.java
+++ b/VAGGS/src/com/vaggs/Utils/DebuggingDBObjects.java
@@ -1,154 +1,154 @@
package com.vaggs.Utils;
import static com.vaggs.Utils.OfyService.ofy;
import java.util.ArrayList;
import java.util.Arrays;
import com.google.appengine.labs.repackaged.com.google.common.collect.Lists;
import com.vaggs.AirportDiagram.Airport;
import com.vaggs.Route.Route;
import com.vaggs.Route.Taxiway;
import com.vaggs.Route.Transponder;
import com.vaggs.Route.Waypoint;
public class DebuggingDBObjects {
public static void createDBObjects () {
/* Transponder Code = 1 */
Route debugRoute = Route.ParseRouteByTaxiways((new Waypoint(new LatLng(41.7258, -71.4368), false, false)), "");
debugRoute.addWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7258, -71.4368), false, false),
new Waypoint(new LatLng(41.7087976, -71.44134), false, false),
new Waypoint(new LatLng(41.73783, -71.41615), false, false),
new Waypoint(new LatLng(41.725, -71.433333), true, false)
));
//Transponder.Parse(1).setRoute(debugRoute);
//Transponder.Parse(2).setRoute(debugRoute);
ArrayList<Taxiway> taxiways = Lists.newArrayList();
Taxiway taxiway = new Taxiway('B');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.72853650684023, -71.42628192901611), false, false),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.726678855296136, -71.42430782318115), true, true),
new Waypoint(new LatLng(41.724180549563606, -71.42203330993652), false, false),
new Waypoint(new LatLng(41.72321963687659, -71.42310619354248), true, false),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('A');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.732027465276374, -71.42314910888672), false, false),
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.73074640164693, -71.42087459564209), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('C');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.43001556396484), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.42877101898193), false, false),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true),
new Waypoint(new LatLng(41.72453288061494, -71.42598152160645), true, true),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true),
new Waypoint(new LatLng(41.71783826026642, -71.41907215118408), false, false),
new Waypoint(new LatLng(41.718414857887055, -71.41825675964355), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('E');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('F');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, true),
new Waypoint(new LatLng(41.73151504289037, -71.43237590789795), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('M');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.72626247775354, -71.42602443695068), true, true),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('N');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72808811310961, -71.43435001373291), false, false),
- new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, true),
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, false),
new Waypoint(new LatLng(41.729561395043916, -71.43237590789795), false, true),
+ new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, false),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.72988166925439, -71.42160415649414), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('S');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true),
new Waypoint(new LatLng(41.714314495734975, -71.43537998199463), false, false),
new Waypoint(new LatLng(41.713769896707845, -71.43443584442139), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('T');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72094541960078, -71.4376974105835), false, false),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true),
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71754995951615, -71.43151760101318), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('V');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, true),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, true),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true)
));
taxiways.add(taxiway);
Airport kpvd = new Airport("kpvd", null, null, null, "");
kpvd.setTaxiways(taxiways);
kpvd.setRouteStartingPoints(Arrays.asList(new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, true)));
ofy().save().entities(kpvd).now();
AtcUser josh = new AtcUser("[email protected]");
AtcUser hawk = new AtcUser("[email protected]");
AtcUser max = new AtcUser("[email protected]");
ofy().save().entity(josh).now();
ofy().save().entity(hawk).now();
ofy().save().entity(max).now();
}
}
| false | true | public static void createDBObjects () {
/* Transponder Code = 1 */
Route debugRoute = Route.ParseRouteByTaxiways((new Waypoint(new LatLng(41.7258, -71.4368), false, false)), "");
debugRoute.addWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7258, -71.4368), false, false),
new Waypoint(new LatLng(41.7087976, -71.44134), false, false),
new Waypoint(new LatLng(41.73783, -71.41615), false, false),
new Waypoint(new LatLng(41.725, -71.433333), true, false)
));
//Transponder.Parse(1).setRoute(debugRoute);
//Transponder.Parse(2).setRoute(debugRoute);
ArrayList<Taxiway> taxiways = Lists.newArrayList();
Taxiway taxiway = new Taxiway('B');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.72853650684023, -71.42628192901611), false, false),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.726678855296136, -71.42430782318115), true, true),
new Waypoint(new LatLng(41.724180549563606, -71.42203330993652), false, false),
new Waypoint(new LatLng(41.72321963687659, -71.42310619354248), true, false),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('A');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.732027465276374, -71.42314910888672), false, false),
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.73074640164693, -71.42087459564209), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('C');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.43001556396484), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.42877101898193), false, false),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true),
new Waypoint(new LatLng(41.72453288061494, -71.42598152160645), true, true),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true),
new Waypoint(new LatLng(41.71783826026642, -71.41907215118408), false, false),
new Waypoint(new LatLng(41.718414857887055, -71.41825675964355), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('E');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('F');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, true),
new Waypoint(new LatLng(41.73151504289037, -71.43237590789795), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('M');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.72626247775354, -71.42602443695068), true, true),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('N');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72808811310961, -71.43435001373291), false, false),
new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, true),
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, false),
new Waypoint(new LatLng(41.729561395043916, -71.43237590789795), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, false),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.72988166925439, -71.42160415649414), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('S');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true),
new Waypoint(new LatLng(41.714314495734975, -71.43537998199463), false, false),
new Waypoint(new LatLng(41.713769896707845, -71.43443584442139), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('T');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72094541960078, -71.4376974105835), false, false),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true),
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71754995951615, -71.43151760101318), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('V');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, true),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, true),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true)
));
taxiways.add(taxiway);
Airport kpvd = new Airport("kpvd", null, null, null, "");
kpvd.setTaxiways(taxiways);
kpvd.setRouteStartingPoints(Arrays.asList(new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, true)));
ofy().save().entities(kpvd).now();
AtcUser josh = new AtcUser("[email protected]");
AtcUser hawk = new AtcUser("[email protected]");
AtcUser max = new AtcUser("[email protected]");
ofy().save().entity(josh).now();
ofy().save().entity(hawk).now();
ofy().save().entity(max).now();
}
| public static void createDBObjects () {
/* Transponder Code = 1 */
Route debugRoute = Route.ParseRouteByTaxiways((new Waypoint(new LatLng(41.7258, -71.4368), false, false)), "");
debugRoute.addWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7258, -71.4368), false, false),
new Waypoint(new LatLng(41.7087976, -71.44134), false, false),
new Waypoint(new LatLng(41.73783, -71.41615), false, false),
new Waypoint(new LatLng(41.725, -71.433333), true, false)
));
//Transponder.Parse(1).setRoute(debugRoute);
//Transponder.Parse(2).setRoute(debugRoute);
ArrayList<Taxiway> taxiways = Lists.newArrayList();
Taxiway taxiway = new Taxiway('B');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.72853650684023, -71.42628192901611), false, false),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.726678855296136, -71.42430782318115), true, true),
new Waypoint(new LatLng(41.724180549563606, -71.42203330993652), false, false),
new Waypoint(new LatLng(41.72321963687659, -71.42310619354248), true, false),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('A');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.732027465276374, -71.42314910888672), false, false),
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.73074640164693, -71.42087459564209), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('C');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.43001556396484), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.42877101898193), false, false),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true),
new Waypoint(new LatLng(41.72453288061494, -71.42598152160645), true, true),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true),
new Waypoint(new LatLng(41.71783826026642, -71.41907215118408), false, false),
new Waypoint(new LatLng(41.718414857887055, -71.41825675964355), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('E');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('F');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, true),
new Waypoint(new LatLng(41.73151504289037, -71.43237590789795), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('M');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.72626247775354, -71.42602443695068), true, true),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('N');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72808811310961, -71.43435001373291), false, false),
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, false),
new Waypoint(new LatLng(41.729561395043916, -71.43237590789795), false, true),
new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, false),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.72988166925439, -71.42160415649414), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('S');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true),
new Waypoint(new LatLng(41.714314495734975, -71.43537998199463), false, false),
new Waypoint(new LatLng(41.713769896707845, -71.43443584442139), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('T');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72094541960078, -71.4376974105835), false, false),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true),
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71754995951615, -71.43151760101318), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('V');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, true),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, true),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true)
));
taxiways.add(taxiway);
Airport kpvd = new Airport("kpvd", null, null, null, "");
kpvd.setTaxiways(taxiways);
kpvd.setRouteStartingPoints(Arrays.asList(new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, true)));
ofy().save().entities(kpvd).now();
AtcUser josh = new AtcUser("[email protected]");
AtcUser hawk = new AtcUser("[email protected]");
AtcUser max = new AtcUser("[email protected]");
ofy().save().entity(josh).now();
ofy().save().entity(hawk).now();
ofy().save().entity(max).now();
}
|
diff --git a/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java b/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java
index d876abaa..5b6a5eb1 100644
--- a/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java
+++ b/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java
@@ -1,11077 +1,11077 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.site.tool;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
import java.util.Set;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.alias.api.Alias;
import org.sakaiproject.alias.cover.AliasService;
import org.sakaiproject.archive.api.ImportMetadata;
import org.sakaiproject.archive.cover.ArchiveService;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.AuthzPermissionException;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.Member;
import org.sakaiproject.authz.api.PermissionsHelper;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceActionII;
import org.sakaiproject.cheftool.PortletConfig;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.api.Menu;
import org.sakaiproject.cheftool.api.MenuItem;
import org.sakaiproject.cheftool.menu.MenuEntry;
import org.sakaiproject.cheftool.menu.MenuImpl;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.cover.ContentHostingService;
import org.sakaiproject.email.cover.EmailService;
import org.sakaiproject.entity.api.EntityProducer;
import org.sakaiproject.entity.api.EntityPropertyNotDefinedException;
import org.sakaiproject.entity.api.EntityPropertyTypeException;
import org.sakaiproject.entity.api.EntityTransferrer;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.id.cover.IdManager;
import org.sakaiproject.javax.PagingPosition;
import org.sakaiproject.mailarchive.api.MailArchiveService;
import org.sakaiproject.site.api.Course;
import org.sakaiproject.site.api.CourseMember;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SitePage;
import org.sakaiproject.site.api.Term;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.site.api.SiteService.SortType;
import org.sakaiproject.site.cover.CourseManagementService;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.util.SubjectAffiliates;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserAlreadyDefinedException;
import org.sakaiproject.user.api.UserEdit;
import org.sakaiproject.user.api.UserIdInvalidException;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.api.UserPermissionException;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.ArrayUtil;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.SortedIterator;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
import org.sakaiproject.importer.api.ImportService;
import org.sakaiproject.importer.api.ImportDataSource;
import org.sakaiproject.importer.api.SakaiArchive;
/**
* <p>SiteAction controls the interface for worksite setup.</p>
*/
public class SiteAction extends PagedResourceActionII
{
/** Our logger. */
private static Log M_log = LogFactory.getLog(SiteAction.class);
private ImportService importService = org.sakaiproject.importer.cover.ImportService.getInstance();
/** portlet configuration parameter values**/
/** Resource bundle using current language locale */
private static ResourceLoader rb = new ResourceLoader("sitesetupgeneric");
private static final String SITE_MODE_SITESETUP = "sitesetup";
private static final String SITE_MODE_SITEINFO= "siteinfo";
private static final String STATE_SITE_MODE = "site_mode";
protected final static String[] TEMPLATE =
{
"-list",//0
"-type",
"-newSiteInformation",
"-newSiteFeatures",
"-addRemoveFeature",
"-addParticipant",
"-removeParticipants",
"-changeRoles",
"-siteDeleteConfirm",
"-publishUnpublish",
"-newSiteConfirm",//10
"-newSitePublishUnpublish",
"-siteInfo-list",//12
"-siteInfo-editInfo",
"-siteInfo-editInfoConfirm",
"-addRemoveFeatureConfirm",//15
"-publishUnpublish-sendEmail",
"-publishUnpublish-confirm",
"-siteInfo-editAccess",
"-addParticipant-sameRole",
"-addParticipant-differentRole",//20
"-addParticipant-notification",
"-addParticipant-confirm",
"-siteInfo-editAccess-globalAccess",
"-siteInfo-editAccess-globalAccess-confirm",
"-changeRoles-confirm",//25
"-modifyENW",
"-importSites",
"-siteInfo-import",
"-siteInfo-duplicate",
"",//30
"",//31
"",//32
"",//33
"",//34
"",//35
"-newSiteCourse",//36
"-newSiteCourseManual",//37
"",//38
"",//39
"",//40
"",//41
"-gradtoolsConfirm",//42
"-siteInfo-editClass",//43
"-siteInfo-addCourseConfirm",//44
"-siteInfo-importMtrlMaster", //45 -- htripath for import material from a file
"-siteInfo-importMtrlCopy", //46
"-siteInfo-importMtrlCopyConfirm",
"-siteInfo-importMtrlCopyConfirmMsg", //48
"-siteInfo-group", //49
"-siteInfo-groupedit", //50
"-siteInfo-groupDeleteConfirm" //51
};
/** Name of state attribute for Site instance id */
private static final String STATE_SITE_INSTANCE_ID = "site.instance.id";
/** Name of state attribute for Site Information */
private static final String STATE_SITE_INFO = "site.info";
/** Name of state attribute for CHEF site type */
private static final String STATE_SITE_TYPE = "site-type";
/** Name of state attribute for poissible site types */
private static final String STATE_SITE_TYPES = "site_types";
private static final String STATE_DEFAULT_SITE_TYPE = "default_site_type";
private static final String STATE_PUBLIC_CHANGEABLE_SITE_TYPES = "changeable_site_types";
private static final String STATE_PUBLIC_SITE_TYPES = "public_site_types";
private static final String STATE_PRIVATE_SITE_TYPES = "private_site_types";
private static final String STATE_DISABLE_JOINABLE_SITE_TYPE = "disable_joinable_site_types";
//Names of state attributes corresponding to properties of a site
private final static String PROP_SITE_CONTACT_EMAIL = "contact-email";
private final static String PROP_SITE_CONTACT_NAME = "contact-name";
private final static String PROP_SITE_TERM = "term";
/** Name of the state attribute holding the site list column list is sorted by */
private static final String SORTED_BY = "site.sorted.by";
/** the list of criteria for sorting */
private static final String SORTED_BY_TITLE = "title";
private static final String SORTED_BY_DESCRIPTION = "description";
private static final String SORTED_BY_TYPE = "type";
private static final String SORTED_BY_STATUS = "status";
private static final String SORTED_BY_CREATION_DATE = "creationdate";
private static final String SORTED_BY_JOINABLE = "joinable";
private static final String SORTED_BY_PARTICIPANT_NAME = "participant_name";
private static final String SORTED_BY_PARTICIPANT_UNIQNAME = "participant_uniqname";
private static final String SORTED_BY_PARTICIPANT_ROLE = "participant_role";
private static final String SORTED_BY_PARTICIPANT_ID = "participant_id";
private static final String SORTED_BY_PARTICIPANT_COURSE = "participant_course";
private static final String SORTED_BY_PARTICIPANT_CREDITS = "participant_credits";
private static final String SORTED_BY_MEMBER_NAME = "member_name";
/** Name of the state attribute holding the site list column to sort by */
private static final String SORTED_ASC = "site.sort.asc";
/** State attribute for list of sites to be deleted. */
private static final String STATE_SITE_REMOVALS = "site.removals";
/** Name of the state attribute holding the site list View selected */
private static final String STATE_VIEW_SELECTED = "site.view.selected";
/** Names of lists related to tools */
private static final String STATE_TOOL_REGISTRATION_LIST = "toolRegistrationList";
private static final String STATE_TOOL_REGISTRATION_SELECTED_LIST = "toolRegistrationSelectedList";
private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST = "toolRegistrationOldSelectedList";
private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME = "toolRegistrationOldSelectedHome";
private static final String STATE_TOOL_EMAIL_ADDRESS = "toolEmailAddress";
private static final String STATE_TOOL_HOME_SELECTED = "toolHomeSelected";
private static final String STATE_PROJECT_TOOL_LIST = "projectToolList";
private final static String STATE_NEWS_TITLES = "newstitles";
private final static String STATE_NEWS_URLS = "newsurls";
private final static String NEWS_DEFAULT_TITLE = ServerConfigurationService.getString("news.title");
private final static String NEWS_DEFAULT_URL = ServerConfigurationService.getString("news.feedURL");
private final static String STATE_WEB_CONTENT_TITLES = "webcontenttitles";
private final static String STATE_WEB_CONTENT_URLS = "wcUrls";
private final static String WEB_CONTENT_DEFAULT_TITLE = "Web Content";
private final static String WEB_CONTENT_DEFAULT_URL = "http://";
private final static String STATE_SITE_QUEST_UNIQNAME = "site_quest_uniqname";
// %%% get rid of the IdAndText tool lists and just use ToolConfiguration or ToolRegistration lists
// %%% same for CourseItems
// Names for other state attributes that are lists
private final static String STATE_WORKSITE_SETUP_PAGE_LIST = "wSetupPageList"; // the list of site pages consistent with Worksite Setup page patterns
/** The name of the state form field containing additional information for a course request */
private static final String FORM_ADDITIONAL = "form.additional";
/** %%% in transition from putting all form variables in state*/
private final static String FORM_TITLE = "form_title";
private final static String FORM_DESCRIPTION = "form_description";
private final static String FORM_HONORIFIC = "form_honorific";
private final static String FORM_INSTITUTION = "form_institution";
private final static String FORM_SUBJECT = "form_subject";
private final static String FORM_PHONE = "form_phone";
private final static String FORM_EMAIL = "form_email";
private final static String FORM_REUSE = "form_reuse";
private final static String FORM_RELATED_CLASS = "form_related_class";
private final static String FORM_RELATED_PROJECT = "form_related_project";
private final static String FORM_NAME = "form_name";
private final static String FORM_SHORT_DESCRIPTION = "form_short_description";
private final static String FORM_ICON_URL = "iconUrl";
/** site info edit form variables */
private final static String FORM_SITEINFO_TITLE = "siteinfo_title";
private final static String FORM_SITEINFO_TERM = "siteinfo_term";
private final static String FORM_SITEINFO_DESCRIPTION = "siteinfo_description";
private final static String FORM_SITEINFO_SHORT_DESCRIPTION = "siteinfo_short_description";
private final static String FORM_SITEINFO_SKIN = "siteinfo_skin";
private final static String FORM_SITEINFO_INCLUDE = "siteinfo_include";
private final static String FORM_SITEINFO_ICON_URL = "siteinfo_icon_url";
private final static String FORM_SITEINFO_CONTACT_NAME = "siteinfo_contact_name";
private final static String FORM_SITEINFO_CONTACT_EMAIL = "siteinfo_contact_email";
private final static String FORM_WILL_NOTIFY = "form_will_notify";
/** Context action */
private static final String CONTEXT_ACTION = "SiteAction";
/** The name of the Attribute for display template index */
private static final String STATE_TEMPLATE_INDEX = "site.templateIndex";
/** State attribute for state initialization. */
private static final String STATE_INITIALIZED = "site.initialized";
/** The action for menu */
private static final String STATE_ACTION = "site.action";
/** The user copyright string */
private static final String STATE_MY_COPYRIGHT = "resources.mycopyright";
/** The copyright character */
private static final String COPYRIGHT_SYMBOL = "copyright (c)";
/** The null/empty string */
private static final String NULL_STRING = "";
/** The state attribute alerting user of a sent course request */
private static final String REQUEST_SENT = "site.request.sent";
/** The state attributes in the make public vm */
private static final String STATE_JOINABLE = "state_joinable";
private static final String STATE_JOINERROLE = "state_joinerRole";
/** the list of selected user */
private static final String STATE_SELECTED_USER_LIST = "state_selected_user_list";
private static final String STATE_SELECTED_PARTICIPANT_ROLES = "state_selected_participant_roles";
private static final String STATE_SELECTED_PARTICIPANTS = "state_selected_participants";
private static final String STATE_PARTICIPANT_LIST = "state_participant_list";
private static final String STATE_ADD_PARTICIPANTS = "state_add_participants";
/** for changing participant roles*/
private static final String STATE_CHANGEROLE_SAMEROLE = "state_changerole_samerole";
private static final String STATE_CHANGEROLE_SAMEROLE_ROLE = "state_changerole_samerole_role";
/** for remove user */
private static final String STATE_REMOVEABLE_USER_LIST = "state_removeable_user_list";
private static final String STATE_IMPORT = "state_import";
private static final String STATE_IMPORT_SITES = "state_import_sites";
private static final String STATE_IMPORT_SITE_TOOL = "state_import_site_tool";
/** for navigating between sites in site list */
private static final String STATE_SITES = "state_sites";
private static final String STATE_PREV_SITE = "state_prev_site";
private static final String STATE_NEXT_SITE = "state_next_site";
/** for course information */
private final static String STATE_TERM_COURSE_LIST = "state_term_course_list";
private final static String STATE_TERM_SELECTED = "state_term_selected";
private final static String STATE_FUTURE_TERM_SELECTED = "state_future_term_selected";
private final static String STATE_ADD_CLASS_PROVIDER = "state_add_class_provider";
private final static String STATE_ADD_CLASS_PROVIDER_CHOSEN = "state_add_class_provider_chosen";
private final static String STATE_ADD_CLASS_MANUAL = "state_add_class_manual";
private final static String STATE_AUTO_ADD = "state_auto_add";
private final static String STATE_MANUAL_ADD_COURSE_NUMBER = "state_manual_add_course_number";
private final static String STATE_MANUAL_ADD_COURSE_FIELDS = "state_manual_add_course_fields";
public final static String PROP_SITE_REQUEST_COURSE = "site-request-course-sections";
public final static String SITE_PROVIDER_COURSE_LIST = "site_provider_course_list";
public final static String SITE_MANUAL_COURSE_LIST = "site_manual_course_list";
private final static String STATE_SUBJECT_AFFILIATES = "site.subject.affiliates";
private final static String STATE_ICONS = "icons";
//site template used to create a UM Grad Tools student site
public static final String SITE_GTS_TEMPLATE = "!gtstudent";
//the type used to identify a UM Grad Tools student site
public static final String SITE_TYPE_GRADTOOLS_STUDENT = "GradToolsStudent";
//list of UM Grad Tools site types for editing
public static final String GRADTOOLS_SITE_TYPES = "gradtools_site_types";
public static final String SITE_DUPLICATED = "site_duplicated";
public static final String SITE_DUPLICATED_NAME = "site_duplicated_named";
// used for site creation wizard title
public static final String SITE_CREATE_TOTAL_STEPS = "site_create_total_steps";
public static final String SITE_CREATE_CURRENT_STEP = "site_create_current_step";
// types of site whose title can be editable
public static final String TITLE_EDITABLE_SITE_TYPE = "title_editable_site_type";
// types of site where site view roster permission is editable
public static final String EDIT_VIEW_ROSTER_SITE_TYPE = "edit_view_roster_site_type";
//htripath : for import material from file - classic import
private static final String ALL_ZIP_IMPORT_SITES= "allzipImports";
private static final String FINAL_ZIP_IMPORT_SITES= "finalzipImports";
private static final String DIRECT_ZIP_IMPORT_SITES= "directzipImports";
private static final String CLASSIC_ZIP_FILE_NAME="classicZipFileName" ;
private static final String SESSION_CONTEXT_ID="sessionContextId";
// page size for worksite setup tool
private static final String STATE_PAGESIZE_SITESETUP = "state_pagesize_sitesetup";
// page size for site info tool
private static final String STATE_PAGESIZE_SITEINFO = "state_pagesize_siteinfo";
// group info
private static final String STATE_GROUP_INSTANCE_ID = "state_group_instance_id";
private static final String STATE_GROUP_TITLE = "state_group_title";
private static final String STATE_GROUP_DESCRIPTION = "state_group_description";
private static final String STATE_GROUP_MEMBERS = "state_group_members";
private static final String STATE_GROUP_REMOVE = "state_group_remove";
private static final String GROUP_PROP_WSETUP_CREATED = "group_prop_wsetup_created";
private static final String IMPORT_DATA_SOURCE = "import_data_source";
private static final String EMAIL_CHAR = "@";
// Special tool id for Home page
private static final String HOME_TOOL_ID = "home";
// the string marks the protocol part in url
private static final String PROTOCOL_STRING = "://";
/**
* Populate the state object, if needed.
*/
protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData rundata)
{
super.initState(state, portlet, rundata);
PortletConfig config = portlet.getPortletConfig();
// types of sites that can either be public or private
String changeableTypes = StringUtil.trimToNull(config.getInitParameter("publicChangeableSiteTypes"));
if (state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES) == null)
{
if (changeableTypes != null)
{
state.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES, new ArrayList(Arrays.asList(changeableTypes.split(","))));
}
else
{
state.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES, new Vector());
}
}
// type of sites that are always public
String publicTypes = StringUtil.trimToNull(config.getInitParameter("publicSiteTypes"));
if (state.getAttribute(STATE_PUBLIC_SITE_TYPES) == null)
{
if (publicTypes != null)
{
state.setAttribute(STATE_PUBLIC_SITE_TYPES, new ArrayList(Arrays.asList(publicTypes.split(","))));
}
else
{
state.setAttribute(STATE_PUBLIC_SITE_TYPES, new Vector());
}
}
// types of sites that are always private
String privateTypes = StringUtil.trimToNull(config.getInitParameter("privateSiteTypes"));
if (state.getAttribute(STATE_PRIVATE_SITE_TYPES) == null)
{
if (privateTypes != null)
{
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new ArrayList(Arrays.asList(privateTypes.split(","))));
}
else
{
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector());
}
}
// default site type
String defaultType = StringUtil.trimToNull(config.getInitParameter("defaultSiteType"));
if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) == null)
{
if (defaultType != null)
{
state.setAttribute(STATE_DEFAULT_SITE_TYPE, defaultType);
}
else
{
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector());
}
}
// certain type(s) of site cannot get its "joinable" option set
if (state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE) == null)
{
if (ServerConfigurationService.getStrings("wsetup.disable.joinable") != null)
{
state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE, new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("wsetup.disable.joinable"))));
}
else
{
state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE, new Vector());
}
}
if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null)
{
state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0));
}
// affiliates if any
if (state.getAttribute(STATE_SUBJECT_AFFILIATES) == null)
{
setupSubjectAffiliates(state);
}
//skins if any
if (state.getAttribute(STATE_ICONS) == null)
{
setupIcons(state);
}
if (state.getAttribute(GRADTOOLS_SITE_TYPES) == null)
{
List gradToolsSiteTypes = new Vector();
if (ServerConfigurationService.getStrings("gradToolsSiteType") != null)
{
gradToolsSiteTypes = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("gradToolsSiteType")));
}
state.setAttribute(GRADTOOLS_SITE_TYPES, gradToolsSiteTypes);
}
if (ServerConfigurationService.getStrings("titleEditableSiteType") != null)
{
state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("titleEditableSiteType"))));
}
else
{
state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new Vector());
}
if (state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE) == null)
{
List siteTypes = new Vector();
if (ServerConfigurationService.getStrings("editViewRosterSiteType") != null)
{
siteTypes = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("editViewRosterSiteType")));
}
state.setAttribute(EDIT_VIEW_ROSTER_SITE_TYPE, siteTypes);
}
//get site tool mode from tool registry
String site_mode = portlet.getPortletConfig().getInitParameter(STATE_SITE_MODE);
state.setAttribute(STATE_SITE_MODE, site_mode);
} // initState
/**
* cleanState removes the current site instance and it's properties from state
*/
private void cleanState(SessionState state)
{
state.removeAttribute(STATE_SITE_INSTANCE_ID);
state.removeAttribute(STATE_SITE_INFO);
state.removeAttribute(STATE_SITE_TYPE);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
state.removeAttribute(STATE_TOOL_HOME_SELECTED);
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_JOINABLE);
state.removeAttribute(STATE_JOINERROLE);
state.removeAttribute(STATE_NEWS_TITLES);
state.removeAttribute(STATE_NEWS_URLS);
state.removeAttribute(STATE_WEB_CONTENT_TITLES);
state.removeAttribute(STATE_WEB_CONTENT_URLS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
state.removeAttribute(STATE_IMPORT);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
// remove those state attributes related to course site creation
state.removeAttribute(STATE_TERM_COURSE_LIST);
state.removeAttribute(STATE_TERM_SELECTED);
state.removeAttribute(STATE_FUTURE_TERM_SELECTED);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_ADD_CLASS_MANUAL);
state.removeAttribute(STATE_AUTO_ADD);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(SITE_CREATE_TOTAL_STEPS);
state.removeAttribute(SITE_CREATE_CURRENT_STEP);
} // cleanState
/**
* Fire up the permissions editor
*/
public void doPermissions(RunData data, Context context)
{
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
SessionState state = ((JetspeedRunData)data).getPortletSessionState(((JetspeedRunData)data).getJs_peid());
String contextString = ToolManager.getCurrentPlacement().getContext();
String siteRef = SiteService.siteReference(contextString);
// if it is in Worksite setup tool, pass the selected site's reference
if (state.getAttribute(STATE_SITE_MODE) != null && ((String) state.getAttribute(STATE_SITE_MODE)).equals(SITE_MODE_SITESETUP))
{
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null)
{
Site s = getStateSite(state);
if (s != null)
{
siteRef = s.getReference();
}
}
}
// setup for editing the permissions of the site for this tool, using the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setperfor") + " "
+ SiteService.getSiteDisplay(contextString));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "site.");
} // doPermissions
/**
* Build the context for normal display
*/
public String buildMainPanelContext ( VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
context.put("tlang",rb);
// TODO: what is all this doing? if we are in helper mode, we are already setup and don't get called here now -ggolden
/*
String helperMode = (String) state.getAttribute(PermissionsAction.STATE_MODE);
if (helperMode != null)
{
Site site = getStateSite(state);
if (site != null)
{
if (site.getType() != null && ((List) state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE)).contains(site.getType()))
{
context.put("editViewRoster", Boolean.TRUE);
}
else
{
context.put("editViewRoster", Boolean.FALSE);
}
}
else
{
context.put("editViewRoster", Boolean.FALSE);
}
// for new, don't show site.del in Permission page
context.put("hiddenLock", "site.del");
String template = PermissionsAction.buildHelperContext(portlet, context, data, state);
if (template == null)
{
addAlert(state, rb.getString("theisa"));
}
else
{
return template;
}
}
*/
String template = null;
context.put ("action", CONTEXT_ACTION);
//updatePortlet(state, portlet, data);
if (state.getAttribute (STATE_INITIALIZED) == null)
{
init (portlet, data, state);
}
int index = Integer.valueOf((String)state.getAttribute(STATE_TEMPLATE_INDEX)).intValue();
template = buildContextForTemplate(index, portlet, context, data, state);
return template;
} // buildMainPanelContext
/**
* Build the context for each template using template_index parameter passed in a form hidden field.
* Each case is associated with a template. (Not all templates implemented). See String[] TEMPLATES.
* @param index is the number contained in the template's template_index
*/
private String buildContextForTemplate (int index, VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
String realmId = "";
String site_type = "";
String sortedBy = "";
String sortedAsc = "";
ParameterParser params = data.getParameters ();
context.put("tlang",rb);
context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
else
{
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
// Lists used in more than one template
// Access
List roles = new Vector();
// the hashtables for News and Web Content tools
Hashtable newsTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable wcUrls = new Hashtable();
List toolRegistrationList = new Vector();
List toolRegistrationSelectedList = new Vector();
ResourceProperties siteProperties = null;
// for showing site creation steps
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null)
{
context.put("totalSteps", state.getAttribute(SITE_CREATE_TOTAL_STEPS));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null)
{
context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP));
}
String hasGradSites = ServerConfigurationService.getString("withDissertation", Boolean.FALSE.toString());
Site site = getStateSite(state);
switch (index)
{
case 0:
/* buildContextForTemplate chef_site-list.vm
*
*/
// site types
List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);
//make sure auto-updates are enabled
Hashtable views = new Hashtable();
if (SecurityService.isSuperUser())
{
views.put(rb.getString("java.allmy"), rb.getString("java.allmy"));
views.put(rb.getString("java.my") + " " + rb.getString("java.sites"), rb.getString("java.my"));
for(int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++)
{
String type = (String) sTypes.get(sTypeIndex);
views.put(type + " " + rb.getString("java.sites"), type);
}
if (hasGradSites.equalsIgnoreCase("true"))
{
views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb.getString("java.gradtools"));
}
if(state.getAttribute(STATE_VIEW_SELECTED) == null)
{
state.setAttribute(STATE_VIEW_SELECTED, rb.getString("java.allmy"));
}
context.put("superUser", Boolean.TRUE);
}
else
{
context.put("superUser", Boolean.FALSE);
views.put(rb.getString("java.allmy"), rb.getString("java.allmy"));
// if there is a GradToolsStudent choice inside
boolean remove = false;
if (hasGradSites.equalsIgnoreCase("true"))
{
try
{
//the Grad Tools site option is only presented to GradTools Candidates
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
//am I a grad student?
if (!isGradToolsCandidate(userId))
{
// not a gradstudent
remove = true;
}
}
catch(Exception e)
{
remove = true;
}
}
else
{
// not support for dissertation sites
remove=true;
}
//do not show this site type in views
//sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT));
for(int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++)
{
String type = (String) sTypes.get(sTypeIndex);
if(!type.equals(SITE_TYPE_GRADTOOLS_STUDENT))
{
views.put(type + " "+rb.getString("java.sites"), type);
}
}
if (!remove)
{
views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb.getString("java.gradtools"));
}
//default view
if(state.getAttribute(STATE_VIEW_SELECTED) == null)
{
state.setAttribute(STATE_VIEW_SELECTED, rb.getString("java.allmy"));
}
}
context.put("views", views);
if(state.getAttribute(STATE_VIEW_SELECTED) != null)
{
context.put("viewSelected", (String) state.getAttribute(STATE_VIEW_SELECTED));
}
String search = (String) state.getAttribute(STATE_SEARCH);
context.put("search_term", search);
sortedBy = (String) state.getAttribute (SORTED_BY);
if (sortedBy == null)
{
state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
sortedBy = SortType.TITLE_ASC.toString();
}
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if (sortedAsc == null)
{
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
String portalUrl = ServerConfigurationService.getPortalUrl();
context.put("portalUrl", portalUrl);
List sites = prepPage(state);
state.setAttribute(STATE_SITES, sites);
context.put("sites", sites);
context.put("totalPageNumber", new Integer(totalPageNumber(state)));
context.put("searchString", state.getAttribute(STATE_SEARCH));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
// put the service in the context (used for allow update calls on each site)
context.put("service", SiteService.getInstance());
context.put("sortby_title", SortType.TITLE_ASC.toString());
context.put("sortby_type", SortType.TYPE_ASC.toString());
context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
// top menu bar
Menu bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null))
{
bar.add( new MenuEntry(rb.getString("java.new"), "doNew_site"));
}
bar.add( new MenuEntry(rb.getString("java.revise"), null, true, MenuItem.CHECKED_NA, "doGet_site", "sitesForm"));
bar.add( new MenuEntry(rb.getString("java.delete"), null, true, MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm"));
context.put("menu", bar);
// default to be no pageing
context.put("paged", Boolean.FALSE);
Menu bar2 = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
// add the search commands
addSearchMenus(bar2, state);
context.put("menu2", bar2);
pagingInfoToContext(state, context);
return (String)getContext(data).get("template") + TEMPLATE[0];
case 1:
/* buildContextForTemplate chef_site-type.vm
*
*/
if (hasGradSites.equalsIgnoreCase("true"))
{
context.put("withDissertation", Boolean.TRUE);
try
{
//the Grad Tools site option is only presented to UM grad students
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
//am I a UM grad student?
Boolean isGradStudent = new Boolean(isGradToolsCandidate(userId));
context.put("isGradStudent", isGradStudent);
//if I am a UM grad student, do I already have a Grad Tools site?
boolean noGradToolsSite = true;
if(hasGradToolsStudentSite(userId))
noGradToolsSite = false;
context.put("noGradToolsSite", new Boolean(noGradToolsSite));
}
catch(Exception e)
{
if(Log.isWarnEnabled())
{
M_log.warn("buildContextForTemplate chef_site-type.vm " + e);
}
}
}
else
{
context.put("withDissertation", Boolean.FALSE);
}
List types = (List) state.getAttribute(STATE_SITE_TYPES);
context.put("siteTypes", types);
// put selected/default site type into context
if (siteInfo.site_type != null && siteInfo.site_type.length() >0)
{
context.put("typeSelected", siteInfo.site_type);
}
else if (types.size() > 0)
{
context.put("typeSelected", types.get(0));
}
List termsForSiteCreation = getAvailableTerms();
if (termsForSiteCreation.size() > 0)
{
context.put("termList", termsForSiteCreation);
}
if (state.getAttribute(STATE_TERM_SELECTED) != null)
{
context.put("selectedTerm", state.getAttribute(STATE_TERM_SELECTED));
}
return (String)getContext(data).get("template") + TEMPLATE[1];
case 2:
/* buildContextForTemplate chef_site-newSiteInformation.vm
*
*/
context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES));
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("titleEditableSiteType", state.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", siteType);
if (siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put ("manualAddNumber", new Integer(number - 1));
context.put ("manualAddFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("back", "37");
}
else
{
context.put("back", "36");
}
context.put ("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null)
{
context.put("selectedIcon", siteInfo.getIconUrl());
}
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null)
{
context.put(FORM_ICON_URL, siteInfo.iconUrl);
}
context.put ("back", "1");
}
context.put (FORM_TITLE,siteInfo.title);
context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description);
context.put (FORM_DESCRIPTION,siteInfo.description);
// defalt the site contact person to the site creator
if (siteInfo.site_contact_name.equals(NULL_STRING) && siteInfo.site_contact_email.equals(NULL_STRING))
{
User user = UserDirectoryService.getCurrentUser();
siteInfo.site_contact_name = user.getDisplayName();
siteInfo.site_contact_email = user.getEmail();
}
context.put("form_site_contact_name", siteInfo.site_contact_name);
context.put("form_site_contact_email", siteInfo.site_contact_email);
// those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[2];
case 3:
/* buildContextForTemplate chef_site-newSiteFeatures.vm
*
*/
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType!=null && siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
}
context.put("defaultTools", ServerConfigurationService.getToolsRequired(siteType));
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// If this is the first time through, check for tools
// which should be selected by default.
List defaultSelectedTools = ServerConfigurationService.getDefaultTools(siteType);
if (toolRegistrationSelectedList == null) {
toolRegistrationSelectedList = new Vector(defaultSelectedTools);
}
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST) ); // %%% use ToolRegistrations for template list
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
// The "Home" tool checkbox needs special treatment to be selected by
// default.
Boolean checkHome = (Boolean)state.getAttribute(STATE_TOOL_HOME_SELECTED);
if (checkHome == null) {
if ((defaultSelectedTools != null) && defaultSelectedTools.contains(HOME_TOOL_ID)) {
checkHome = Boolean.TRUE;
}
}
context.put("check_home", checkHome);
//titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
//titles for web content tools
context.put("wcTitles", state.getAttribute(STATE_WEB_CONTENT_TITLES));
//urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
//urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put("sites", SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null));
context.put("import", state.getAttribute(STATE_IMPORT));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[3];
case 4:
/* buildContextForTemplate chef_site-addRemoveFeatures.vm
*
*/
context.put("SiteTitle", site.getTitle());
String type = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("defaultTools", ServerConfigurationService.getToolsRequired(type));
boolean myworkspace_site = false;
//Put up tool lists filtered by category
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes.contains(type))
{
myworkspace_site = false;
}
if (SiteService.isUserSite(site.getId()) || (type!=null && type.equalsIgnoreCase("myworkspace")))
{
myworkspace_site = true;
type="myworkspace";
}
context.put ("myworkspace_site", new Boolean(myworkspace_site));
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST));
//titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
//titles for web content tools
context.put("wcTitles", state.getAttribute(STATE_WEB_CONTENT_TITLES));
//urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
//urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
//get the email alias when an Email Archive tool has been selected
String channelReference = mailArchiveChannelReference(site.getId());
List aliases = AliasService.getAliases(channelReference, 1, 1);
if (aliases.size() > 0)
{
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases.get(0)).getId());
}
else
{
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null)
{
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService.getServerName());
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[4];
case 5:
/* buildContextForTemplate chef_site-addParticipant.vm
*
*/
context.put("title", site.getTitle());
roles = getRoles(state);
context.put("roles", roles);
// Note that (for now) these strings are in both sakai.properties and sitesetupgeneric.properties
context.put("noEmailInIdAccountName", ServerConfigurationService.getString("noEmailInIdAccountName"));
context.put("noEmailInIdAccountLabel", ServerConfigurationService.getString("noEmailInIdAccountLabel"));
context.put("emailInIdAccountName", ServerConfigurationService.getString("emailInIdAccountName"));
context.put("emailInIdAccountLabel", ServerConfigurationService.getString("emailInIdAccountLabel"));
if(state.getAttribute("noEmailInIdAccountValue")!=null)
{
context.put("noEmailInIdAccountValue", (String)state.getAttribute("noEmailInIdAccountValue"));
}
if(state.getAttribute("emailInIdAccountValue")!=null)
{
context.put("emailInIdAccountValue", (String)state.getAttribute("emailInIdAccountValue"));
}
if(state.getAttribute("form_same_role") != null)
{
context.put("form_same_role", ((Boolean) state.getAttribute("form_same_role")).toString());
}
else
{
context.put("form_same_role", Boolean.TRUE.toString());
}
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[5];
case 6:
/* buildContextForTemplate chef_site-removeParticipants.vm
*
*/
context.put("title", site.getTitle());
realmId = SiteService.siteReference(site.getId());
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
try
{
List removeableList = (List) state.getAttribute(STATE_REMOVEABLE_USER_LIST);
List removeableParticipants = new Vector();
for (int k = 0; k < removeableList.size(); k++)
{
User user = UserDirectoryService.getUser((String) removeableList.get(k));
Participant participant = new Participant();
participant.name = user.getSortName();
participant.uniqname = user.getId();
Role r = realm.getUserRole(user.getId());
if (r != null)
{
participant.role = r.getId();
}
removeableParticipants.add(participant);
}
context.put("removeableList", removeableParticipants);
}
catch (UserNotDefinedException ee)
{
}
}
catch (GroupNotDefinedException e)
{
}
context.put("backIndex", "18");
return (String)getContext(data).get("template") + TEMPLATE[6];
case 7:
/* buildContextForTemplate chef_site-changeRoles.vm
*
*/
context.put("same_role", state.getAttribute(STATE_CHANGEROLE_SAMEROLE));
roles = getRoles(state);
context.put("roles", roles);
context.put("currentRole", state.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
context.put("participantSelectedList", state.getAttribute(STATE_SELECTED_PARTICIPANTS));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("siteTitle", site.getTitle());
return (String)getContext(data).get("template") + TEMPLATE[7];
case 8:
/* buildContextForTemplate chef_site-siteDeleteConfirm.vm
*
*/
String site_title = NULL_STRING;
String[] removals = (String[]) state.getAttribute(STATE_SITE_REMOVALS);
List remove = new Vector();
String user = SessionManager.getCurrentSessionUserId();
String workspace = SiteService.getUserSiteId(user);
if( removals != null && removals.length != 0 )
{
for (int i = 0; i < removals.length; i++ )
{
String id = (String) removals[i];
if(!(id.equals(workspace)))
{
try
{
site_title = SiteService.getSite(id).getTitle();
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.doSite_delete_confirmed - IdUnusedException " + id);
addAlert(state, rb.getString("java.sitewith")+" " + id + " "+rb.getString("java.couldnt")+" ");
}
if(SiteService.allowRemoveSite(id))
{
try
{
Site removeSite = SiteService.getSite(id);
remove.add(removeSite);
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException");
}
}
else
{
addAlert(state, site_title + " "+rb.getString("java.couldntdel") + " ");
}
}
else
{
addAlert(state, rb.getString("java.yourwork"));
}
}
if(remove.size() == 0)
{
addAlert(state, rb.getString("java.click"));
}
}
context.put("removals", remove);
return (String)getContext(data).get("template") + TEMPLATE[8];
case 9:
/* buildContextForTemplate chef_site-publishUnpublish.vm
*
*/
context.put("publish", Boolean.valueOf(((SiteInfo)state.getAttribute(STATE_SITE_INFO)).getPublished()));
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[9];
case 10:
/* buildContextForTemplate chef_site-newSiteConfirm.vm
*
*/
siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put ("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put ("manualAddNumber", new Integer(number - 1));
context.put ("manualAddFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put ("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null)
{
context.put("selectedIcon", siteInfo.getIconUrl());
}
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType!=null && siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null)
{
context.put("iconUrl", siteInfo.iconUrl);
}
}
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("siteContactName", siteInfo.site_contact_name);
context.put("siteContactEmail", siteInfo.site_contact_email);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use Tool
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
context.put("include", new Boolean(siteInfo.include));
context.put("published", new Boolean(siteInfo.published));
context.put("joinable", new Boolean(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
context.put("newsTitles", (Hashtable) state.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES));
// back to edit access page
context.put("back", "18");
context.put("importSiteTools", state.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("siteService", SiteService.getInstance());
// those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[10];
case 11:
/* buildContextForTemplate chef_site-newSitePublishUnpublish.vm
*
*/
return (String)getContext(data).get("template") + TEMPLATE[11];
case 12:
/* buildContextForTemplate chef_site-siteInfo-list.vm
*
*/
context.put("userDirectoryService", UserDirectoryService.getInstance());
try
{
siteProperties = site.getProperties();
siteType = site.getType();
if (siteType != null)
{
state.setAttribute(STATE_SITE_TYPE, siteType);
}
boolean isMyWorkspace = false;
if (SiteService.isUserSite(site.getId()))
{
if (SiteService.getSiteUserId(site.getId()).equals(SessionManager.getCurrentSessionUserId()))
{
isMyWorkspace = true;
context.put("siteUserId", SiteService.getSiteUserId(site.getId()));
}
}
context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));
String siteId = site.getId();
if (state.getAttribute(STATE_ICONS)!= null)
{
List skins = (List)state.getAttribute(STATE_ICONS);
for (int i = 0; i < skins.size(); i++)
{
Icon s = (Icon)skins.get(i);
if(!StringUtil.different(s.getUrl(), site.getIconUrl()))
{
context.put("siteUnit", s.getName());
break;
}
}
}
context.put("siteIcon", site.getIconUrl());
context.put("siteTitle", site.getTitle());
context.put("siteDescription", site.getDescription());
context.put("siteJoinable", new Boolean(site.isJoinable()));
if(site.isPublished())
{
context.put("published", Boolean.TRUE);
}
else
{
context.put("published", Boolean.FALSE);
context.put("owner", site.getCreatedBy().getSortName());
}
Time creationTime = site.getCreatedTime();
if (creationTime != null)
{
context.put("siteCreationDate", creationTime.toStringLocalFull());
}
boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));
boolean allowUpdateGroupMembership = SiteService.allowUpdateGroupMembership(siteId);
context.put("allowUpdateGroupMembership", Boolean.valueOf(allowUpdateGroupMembership));
boolean allowUpdateSiteMembership = SiteService.allowUpdateSiteMembership(siteId);
context.put("allowUpdateSiteMembership", Boolean.valueOf(allowUpdateSiteMembership));
if (allowUpdateSite)
{
// top menu bar
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace)
{
b.add( new MenuEntry(rb.getString("java.editsite"), "doMenu_edit_site_info"));
}
b.add( new MenuEntry(rb.getString("java.edittools"), "doMenu_edit_site_tools"));
if (!isMyWorkspace
&& (ServerConfigurationService.getString("wsetup.group.support") == ""
|| ServerConfigurationService.getString("wsetup.group.support").equalsIgnoreCase(Boolean.TRUE.toString())))
{
// show the group toolbar unless configured to not support group
b.add( new MenuEntry(rb.getString("java.group"), "doMenu_group"));
}
if (!isMyWorkspace)
{
List gradToolsSiteTypes = (List) state.getAttribute(GRADTOOLS_SITE_TYPES);
boolean isGradToolSite = false;
if (siteType != null && gradToolsSiteTypes.contains(siteType))
{
isGradToolSite = true;
}
if (siteType == null
|| siteType != null && !isGradToolSite)
{
// hide site access for GRADTOOLS type of sites
b.add( new MenuEntry(rb.getString("java.siteaccess"), "doMenu_edit_site_access"));
}
b.add( new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant"));
if (siteType != null && siteType.equals("course"))
{
b.add( new MenuEntry(rb.getString("java.editc"), "doMenu_siteInfo_editClass"));
}
if (siteType == null || siteType != null && !isGradToolSite)
{
// hide site duplicate and import for GRADTOOLS type of sites
b.add( new MenuEntry(rb.getString("java.duplicate"), "doMenu_siteInfo_duplicate"));
List updatableSites = SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null);
// import link should be visible even if only one site
if (updatableSites.size() > 0)
{
b.add( new MenuEntry(rb.getString("java.import"), "doMenu_siteInfo_import"));
// a configuration param for showing/hiding import from file choice
String importFromFile = ServerConfigurationService.getString("site.setup.import.file", Boolean.TRUE.toString());
if (importFromFile.equalsIgnoreCase("true"))
{
//htripath: June 4th added as per Kris and changed desc of above
b.add(new MenuEntry(rb.getString("java.importFile"), "doAttachmentsMtrlFrmFile"));
}
}
}
}
// if the page order helper is available, not stealthed and not hidden, show the link
if (ToolManager.getTool("sakai-site-pageorder-helper") != null
&& !ServerConfigurationService
.getString("[email protected]")
.contains("sakai-site-pageorder-helper")
&& !ServerConfigurationService
.getString("[email protected]")
.contains("sakai-site-pageorder-helper"))
{
b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper"));
}
context.put("menu", b);
}
if (allowUpdateGroupMembership)
{
// show Manage Groups menu
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace
&& (ServerConfigurationService.getString("wsetup.group.support") == ""
|| ServerConfigurationService.getString("wsetup.group.support").equalsIgnoreCase(Boolean.TRUE.toString())))
{
// show the group toolbar unless configured to not support group
b.add( new MenuEntry(rb.getString("java.group"), "doMenu_group"));
}
context.put("menu", b);
}
if (allowUpdateSiteMembership)
{
// show add participant menu
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace)
{
// show the Add Participant menu
b.add( new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant"));
}
context.put("menu", b);
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
// editing from worksite setup tool
context.put("fromWSetup", Boolean.TRUE);
if (state.getAttribute(STATE_PREV_SITE) != null)
{
context.put("prevSite", state.getAttribute(STATE_PREV_SITE));
}
if (state.getAttribute(STATE_NEXT_SITE) != null)
{
context.put("nextSite", state.getAttribute(STATE_NEXT_SITE));
}
}
else
{
context.put("fromWSetup", Boolean.FALSE);
}
//allow view roster?
boolean allowViewRoster = SiteService.allowViewRoster(siteId);
if (allowViewRoster)
{
context.put("viewRoster", Boolean.TRUE);
}
else
{
context.put("viewRoster", Boolean.FALSE);
}
//set participant list
if (allowUpdateSite || allowViewRoster || allowUpdateSiteMembership)
{
List participants = new Vector();
participants = getParticipantList(state);
sortedBy = (String) state.getAttribute (SORTED_BY);
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if(sortedBy==null)
{
state.setAttribute(SORTED_BY, SORTED_BY_PARTICIPANT_NAME);
sortedBy = SORTED_BY_PARTICIPANT_NAME;
}
if (sortedAsc==null)
{
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
Iterator sortedParticipants = null;
if (sortedBy != null)
{
sortedParticipants = new SortedIterator (participants.iterator (), new SiteComparator (sortedBy, sortedAsc));
participants.clear();
while (sortedParticipants.hasNext())
{
participants.add(sortedParticipants.next());
}
}
context.put("participantListSize", new Integer(participants.size()));
context.put("participantList", prepPage(state));
pagingInfoToContext(state, context);
}
context.put("include", Boolean.valueOf(site.isPubView()));
// site contact information
String contactName = siteProperties.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null)
{
User u = site.getCreatedBy();
String email = u.getEmail();
if (email != null)
{
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
if (contactName != null)
{
context.put("contactName", contactName);
}
if (contactEmail != null)
{
context.put("contactEmail", contactEmail);
}
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
List providerCourseList = getProviderCourseList(StringUtil.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null)
{
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
context.put("providerCourseList", providerCourseList);
}
String manualCourseListString = site.getProperties().getProperty(PROP_SITE_REQUEST_COURSE);
if (manualCourseListString != null)
{
List manualCourseList = new Vector();
if (manualCourseListString.indexOf("+") != -1)
{
manualCourseList = new ArrayList(Arrays.asList(manualCourseListString.split("\\+")));
}
else
{
manualCourseList.add(manualCourseListString);
}
state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList);
context.put("manualCourseList", manualCourseList);
}
context.put("term", siteProperties.getProperty(PROP_SITE_TERM));
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
}
catch (Exception e)
{
M_log.warn(this + " site info list: " + e.toString());
}
roles = getRoles(state);
context.put("roles", roles);
// will have the choice to active/inactive user or not
String activeInactiveUser = ServerConfigurationService.getString("activeInactiveUser", Boolean.FALSE.toString());
if (activeInactiveUser.equalsIgnoreCase("true"))
{
context.put("activeInactiveUser", Boolean.TRUE);
// put realm object into context
realmId = SiteService.siteReference(site.getId());
try
{
context.put("realm", AuthzGroupService.getAuthzGroup(realmId));
}
catch (GroupNotDefinedException e)
{
M_log.warn(this + " IdUnusedException " + realmId);
}
}
else
{
context.put("activeInactiveUser", Boolean.FALSE);
}
context.put("groupsWithMember", site.getGroupsWithMember(UserDirectoryService.getCurrentUser().getId()));
return (String)getContext(data).get("template") + TEMPLATE[12];
case 13:
/* buildContextForTemplate chef_site-siteInfo-editInfo.vm
*
*/
siteProperties = site.getProperties();
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("titleEditableSiteType", state.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", site.getType());
List terms = CourseManagementService.getTerms();
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("skins", state.getAttribute(STATE_ICONS));
if (state.getAttribute(FORM_SITEINFO_SKIN) != null)
{
context.put("selectedIcon",state.getAttribute(FORM_SITEINFO_SKIN));
}
else if (site.getIconUrl() != null)
{
context.put("selectedIcon",site.getIconUrl());
}
if (terms != null && terms.size() >0)
{
context.put("termList", terms);
}
if (state.getAttribute(FORM_SITEINFO_TERM) == null)
{
String currentTerm = site.getProperties().getProperty(PROP_SITE_TERM);
if (currentTerm != null)
{
state.setAttribute(FORM_SITEINFO_TERM, currentTerm);
}
}
if (state.getAttribute(FORM_SITEINFO_TERM) != null)
{
context.put("selectedTerm", state.getAttribute(FORM_SITEINFO_TERM));
}
}
else
{
context.put("isCourseSite", Boolean.FALSE);
if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null && StringUtil.trimToNull(site.getIconUrl()) != null)
{
state.setAttribute(FORM_SITEINFO_ICON_URL, site.getIconUrl());
}
if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null)
{
context.put("iconUrl", state.getAttribute(FORM_SITEINFO_ICON_URL));
}
}
context.put("description", state.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("short_description", state.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("form_site_contact_name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("form_site_contact_email", state.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
//Display of appearance icon/url list with course site based on
// "disable.course.site.skin.selection" value set with sakai.properties file.
if ((ServerConfigurationService.getString("disable.course.site.skin.selection")).equals("true")){
context.put("disableCourseSelection", Boolean.TRUE);
}
return (String)getContext(data).get("template") + TEMPLATE[13];
case 14:
/* buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm
*
*/
siteProperties = site.getProperties();
siteType = (String)state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM));
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
context.put("oTitle", site.getTitle());
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("description", state.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("oDescription", site.getDescription());
context.put("short_description", state.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("oShort_description", site.getShortDescription());
context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN));
context.put("oSkin", site.getIconUrl());
context.put("skins", state.getAttribute(STATE_ICONS));
context.put("oIcon", site.getIconUrl());
context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL));
context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE));
context.put("oInclude", Boolean.valueOf(site.isPubView()));
context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("oName", siteProperties.getProperty(PROP_SITE_CONTACT_NAME));
context.put("email", state.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
context.put("oEmail", siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL));
return (String)getContext(data).get("template") + TEMPLATE[14];
case 15:
/* buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm
*
*/
context.put("title", site.getTitle());
site_type = (String)state.getAttribute(STATE_SITE_TYPE);
myworkspace_site = false;
if (SiteService.isUserSite(site.getId()))
{
if (SiteService.getSiteUserId(site.getId()).equals(SessionManager.getCurrentSessionUserId()))
{
myworkspace_site = true;
site_type = "myworkspace";
}
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("selectedTools", orderToolIds(state, (String) state.getAttribute(STATE_SITE_TYPE), (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)));
context.put("oldSelectedTools", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("oldSelectedHome", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME));
context.put("continueIndex", "12");
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null)
{
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService.getServerName());
context.put("newsTitles", (Hashtable) state.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES));
if (fromENWModifyView(state))
{
context.put("back", "26");
}
else
{
context.put("back", "4");
}
return (String)getContext(data).get("template") + TEMPLATE[15];
case 16:
/* buildContextForTemplate chef_site-publishUnpublish-sendEmail.vm
*
*/
context.put("title", site.getTitle());
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String)getContext(data).get("template") + TEMPLATE[16];
case 17:
/* buildContextForTemplate chef_site-publishUnpublish-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("continueIndex", "12");
SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (sInfo.getPublished())
{
context.put("publish", Boolean.TRUE);
context.put("backIndex", "16");
}
else
{
context.put("publish", Boolean.FALSE);
context.put("backIndex", "9");
}
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String)getContext(data).get("template") + TEMPLATE[17];
case 18:
/* buildContextForTemplate chef_siteInfo-editAccess.vm
*
*/
List publicChangeableSiteTypes = (List) state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
List unJoinableSiteTypes = (List) state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);
if (site != null)
{
//editing existing site
context.put("site", site);
siteType = state.getAttribute(STATE_SITE_TYPE)!=null?(String)state.getAttribute(STATE_SITE_TYPE):null;
if ( siteType != null
&& publicChangeableSiteTypes.contains(siteType))
{
context.put ("publicChangeable", Boolean.TRUE);
}
else
{
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(site.isPubView()));
if ( siteType != null && !unJoinableSiteTypes.contains(siteType))
{
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
if (state.getAttribute(STATE_JOINABLE) == null)
{
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site.isJoinable()));
}
if (state.getAttribute(STATE_JOINERROLE) == null
|| state.getAttribute(STATE_JOINABLE) != null && ((Boolean) state.getAttribute(STATE_JOINABLE)).booleanValue())
{
state.setAttribute(STATE_JOINERROLE, site.getJoinerRole());
}
if (state.getAttribute(STATE_JOINABLE) != null)
{
context.put("joinable", state.getAttribute(STATE_JOINABLE));
}
if (state.getAttribute(STATE_JOINERROLE) != null)
{
context.put("joinerRole", state.getAttribute(STATE_JOINERROLE));
}
}
else
{
//site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
context.put("roles", getRoles(state));
context.put("back", "12");
}
else
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if ( siteInfo.site_type != null
&& publicChangeableSiteTypes.contains(siteInfo.site_type))
{
context.put ("publicChangeable", Boolean.TRUE);
}
else
{
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(siteInfo.getInclude()));
context.put("published", Boolean.valueOf(siteInfo.getPublished()));
if ( siteInfo.site_type != null && !unJoinableSiteTypes.contains(siteInfo.site_type))
{
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
}
else
{
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
// use the type's template, if defined
String realmTemplate = "!site.template";
if (siteInfo.site_type != null)
{
realmTemplate = realmTemplate + "." + siteInfo.site_type;
}
try
{
AuthzGroup r = AuthzGroupService.getAuthzGroup(realmTemplate);
context.put("roles", r.getRoles());
}
catch (GroupNotDefinedException e)
{
try
{
AuthzGroup rr = AuthzGroupService.getAuthzGroup("!site.template");
context.put("roles", rr.getRoles());
}
catch (GroupNotDefinedException ee)
{
}
}
// new site, go to confirmation page
context.put("continue", "10");
if (fromENWModifyView(state))
{
context.put("back", "26");
}
else if (state.getAttribute(STATE_IMPORT) != null)
{
context.put("back", "27");
}
else
{
context.put("back", "3");
}
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType!=null && siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
}
}
return (String)getContext(data).get("template") + TEMPLATE[18];
case 19:
/* buildContextForTemplate chef_site-addParticipant-sameRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("participantList", state.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("form_selectedRole", state.getAttribute("form_selectedRole"));
return (String)getContext(data).get("template") + TEMPLATE[19];
case 20:
/* buildContextForTemplate chef_site-addParticipant-differentRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("participantList", state.getAttribute(STATE_ADD_PARTICIPANTS));
return (String)getContext(data).get("template") + TEMPLATE[20];
case 21:
/* buildContextForTemplate chef_site-addParticipant-notification.vm
*
*/
context.put("title", site.getTitle());
context.put("sitePublished", Boolean.valueOf(site.isPublished()));
if (state.getAttribute("form_selectedNotify") == null)
{
state.setAttribute("form_selectedNotify", Boolean.FALSE);
}
context.put("notify", state.getAttribute("form_selectedNotify"));
boolean same_role = state.getAttribute("form_same_role")==null?true:((Boolean) state.getAttribute("form_same_role")).booleanValue();
if (same_role)
{
context.put("backIndex", "19");
}
else
{
context.put("backIndex", "20");
}
return (String)getContext(data).get("template") + TEMPLATE[21];
case 22:
/* buildContextForTemplate chef_site-addParticipant-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("participants", state.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("notify", state.getAttribute("form_selectedNotify"));
context.put("roles", getRoles(state));
context.put("same_role", state.getAttribute("form_same_role"));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("selectedRole", state.getAttribute("form_selectedRole"));
return (String)getContext(data).get("template") + TEMPLATE[22];
case 23:
/* buildContextForTemplate chef_siteInfo-editAccess-globalAccess.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
if (state.getAttribute("form_joinable") == null)
{
state.setAttribute("form_joinable", new Boolean(site.isJoinable()));
}
context.put("form_joinable", state.getAttribute("form_joinable"));
if (state.getAttribute("form_joinerRole") == null)
{
state.setAttribute("form_joinerRole", site.getJoinerRole());
}
context.put("form_joinerRole", state.getAttribute("form_joinerRole"));
return (String)getContext(data).get("template") + TEMPLATE[23];
case 24:
/* buildContextForTemplate chef_siteInfo-editAccess-globalAccess-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("form_joinable", state.getAttribute("form_joinable"));
context.put("form_joinerRole", state.getAttribute("form_joinerRole"));
return (String)getContext(data).get("template") + TEMPLATE[24];
case 25:
/* buildContextForTemplate chef_changeRoles-confirm.vm
*
*/
Boolean sameRole = (Boolean) state.getAttribute(STATE_CHANGEROLE_SAMEROLE);
context.put("sameRole", sameRole);
if (sameRole.booleanValue())
{
// same role
context.put("currentRole", state.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
}
else
{
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
roles = getRoles(state);
context.put("roles", roles);
context.put("participantSelectedList", state.getAttribute(STATE_SELECTED_PARTICIPANTS));
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) != null)
{
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
context.put("siteTitle", site.getTitle());
return (String)getContext(data).get("template") + TEMPLATE[25];
case 26:
/* buildContextForTemplate chef_site-modifyENW.vm
*
*/
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean existingSite = site != null? true:false;
if (existingSite)
{
// revising a existing site's tool
context.put("existingSite", Boolean.TRUE);
context.put("back", "4");
context.put("continue", "15");
context.put("function", "eventSubmit_doAdd_remove_features");
}
else
{
// new site
context.put("existingSite", Boolean.FALSE);
context.put("function", "eventSubmit_doAdd_features");
if (state.getAttribute(STATE_IMPORT) != null)
{
context.put("back", "27");
}
else
{
// new site, go to edit access page
context.put("back", "3");
}
context.put("continue", "18");
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
String emailId = (String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
if (emailId != null)
{
context.put("emailId", emailId);
}
//titles for news tools
newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
if (newsTitles == null)
{
newsTitles = new Hashtable();
newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE);
state.setAttribute(STATE_NEWS_TITLES, newsTitles);
}
context.put("newsTitles", newsTitles);
//urls for news tools
newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
if (newsUrls == null)
{
newsUrls = new Hashtable();
newsUrls.put("sakai.news", NEWS_DEFAULT_URL);
state.setAttribute(STATE_NEWS_URLS, newsUrls);
}
context.put("newsUrls", newsUrls);
// titles for web content tools
wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES);
if (wcTitles == null)
{
wcTitles = new Hashtable();
wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE);
state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles);
}
context.put("wcTitles", wcTitles);
//URLs for web content tools
wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS);
if (wcUrls == null)
{
wcUrls = new Hashtable();
wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL);
state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls);
}
context.put("wcUrls", wcUrls);
context.put("serverName", ServerConfigurationService.getServerName());
context.put("oldSelectedTools", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
return (String)getContext(data).get("template") + TEMPLATE[26];
case 27:
/* buildContextForTemplate chef_site-importSites.vm
*
*/
existingSite = site != null? true:false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (existingSite)
{
// revising a existing site's tool
context.put("continue", "12");
context.put("back", "28");
context.put("totalSteps", "2");
context.put("step", "2");
context.put("currentSite", site);
}
else
{
// new site, go to edit access page
context.put("back", "3");
if (fromENWModifyView(state))
{
context.put("continue", "26");
}
else
{
context.put("continue", "18");
}
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put ("selectedTools", orderToolIds(state, site_type, getToolsAvailableForImport(state))); // String toolId's
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
return (String)getContext(data).get("template") + TEMPLATE[27];
case 28:
/* buildContextForTemplate chef_siteinfo-import.vm
*
*/
context.put("currentSite", site);
context.put("importSiteList", state.getAttribute(STATE_IMPORT_SITES));
context.put("sites", SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null));
return (String)getContext(data).get("template") + TEMPLATE[28];
case 29:
/* buildContextForTemplate chef_siteinfo-duplicate.vm
*
*/
context.put("siteTitle", site.getTitle());
String sType = site.getType();
if (sType != null && sType.equals("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("currentTermId", site.getProperties().getProperty(PROP_SITE_TERM));
context.put("termList", getAvailableTerms());
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
if (state.getAttribute(SITE_DUPLICATED) == null)
{
context.put("siteDuplicated", Boolean.FALSE);
}
else
{
context.put("siteDuplicated", Boolean.TRUE);
context.put("duplicatedName", state.getAttribute(SITE_DUPLICATED_NAME));
}
return (String)getContext(data).get("template") + TEMPLATE[29];
case 36:
/*
* buildContextForTemplate chef_site-newSiteCourse.vm
*/
if (site != null)
{
context.put("site", site);
context.put("siteTitle", site.getTitle());
terms = CourseManagementService.getTerms();
if (terms != null && terms.size() >0)
{
context.put("termList", terms);
}
List providerCourseList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
context.put("providerCourseList", providerCourseList);
context.put("manualCourseList", state.getAttribute(SITE_MANUAL_COURSE_LIST));
Term t = (Term) state.getAttribute(STATE_TERM_SELECTED);
context.put ("term", t);
if (t != null)
{
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
List courses = CourseManagementService.getInstructorCourses(userId, t.getYear(), t.getTerm());
if (courses != null && courses.size() > 0)
{
Vector notIncludedCourse = new Vector();
// remove included sites
for (Iterator i = courses.iterator(); i.hasNext(); )
{
Course c = (Course) i.next();
if (!providerCourseList.contains(c.getId()))
{
notIncludedCourse.add(c);
}
}
state.setAttribute(STATE_TERM_COURSE_LIST, notIncludedCourse);
}
else
{
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
}
// step number used in UI
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1"));
}
else
{
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if(state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
context.put("selectedManualCourse", Boolean.TRUE);
}
context.put ("term", (Term) state.getAttribute(STATE_TERM_SELECTED));
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
context.put("backIndex", "1");
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
context.put("backIndex", "");
}
context.put("termCourseList", (List) state.getAttribute(STATE_TERM_COURSE_LIST));
return (String)getContext(data).get("template") + TEMPLATE[36];
case 37:
/*
* buildContextForTemplate chef_site-newSiteCourseManual.vm
*/
if (site != null)
{
context.put("site", site);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
}
buildInstructorSectionsList(state, params, context);
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("form_requiredFieldsSizes", CourseManagementService.getCourseIdRequiredFieldsSizes());
context.put("form_additional", siteInfo.additional);
context.put("form_title", siteInfo.title);
context.put("form_description", siteInfo.description);
context.put("noEmailInIdAccountName", ServerConfigurationService.getString("noEmailInIdAccountName", ""));
context.put("value_uniqname", state.getAttribute(STATE_SITE_QUEST_UNIQNAME));
int number = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put("currentNumber", new Integer(number));
}
context.put("currentNumber", new Integer(number));
context.put("listSize", new Integer(number-1));
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
List l = (List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
context.put ("selectedProviderCourse", l);
context.put("size", new Integer(l.size()-1));
}
if (site != null)
{
context.put("back", "36");
}
else
{
if (state.getAttribute(STATE_AUTO_ADD) != null)
{
context.put("autoAdd", Boolean.TRUE);
context.put("back", "36");
}
else
{
context.put("back", "1");
}
}
context.put("isFutureTerm", state.getAttribute(STATE_FUTURE_TERM_SELECTED));
context.put("weeksAhead", ServerConfigurationService.getString("roster.available.weeks.before.term.start", "0"));
return (String)getContext(data).get("template") + TEMPLATE[37];
case 42:
/* buildContextForTemplate chef_site-gradtoolsConfirm.vm
*
*/
siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
toolRegistrationList = (Vector) state.getAttribute(STATE_PROJECT_TOOL_LIST);
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, toolRegistrationList ); // %%% use Tool
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
context.put("include", new Boolean(siteInfo.include));
return (String)getContext(data).get("template") + TEMPLATE[42];
case 43:
/* buildContextForTemplate chef_siteInfo-editClass.vm
*
*/
bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null))
{
bar.add( new MenuEntry(rb.getString("java.addclasses"), "doMenu_siteInfo_addClass"));
}
context.put("menu", bar);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
return (String)getContext(data).get("template") + TEMPLATE[43];
case 44:
/* buildContextForTemplate chef_siteInfo-addCourseConfirm.vm
*
*/
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
context.put("providerAddCourses", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int addNumber = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue() -1;
context.put("manualAddNumber", new Integer(addNumber));
context.put("requestFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("backIndex", "37");
}
else
{
context.put("backIndex", "36");
}
//those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[44];
//htripath - import materials from classic
case 45:
/* buildContextForTemplate chef_siteInfo-importMtrlMaster.vm
*
*/
return (String)getContext(data).get("template") + TEMPLATE[45];
case 46:
/* buildContextForTemplate chef_siteInfo-importMtrlCopy.vm
*
*/
// this is for list display in listbox
context.put("allZipSites", state.getAttribute(ALL_ZIP_IMPORT_SITES));
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
//zip file
//context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME));
return (String)getContext(data).get("template") + TEMPLATE[46];
case 47:
/* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[47];
case 48:
/* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[48];
case 49:
/* buildContextForTemplate chef_siteInfo-group.vm
*
*/
context.put("site", site);
bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowUpdateSite(site.getId()) || SiteService.allowUpdateGroupMembership(site.getId()))
{
- bar.add( new MenuEntry(rb.getString("java.new"), "doGroup_new"));
+ bar.add( new MenuEntry(rb.getString("editgroup.new"), "doGroup_new"));
}
context.put("menu", bar);
// the group list
sortedBy = (String) state.getAttribute (SORTED_BY);
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
// only show groups created by WSetup tool itself
Collection groups = (Collection) site.getGroups();
List groupsByWSetup = new Vector();
for(Iterator gIterator = groups.iterator(); gIterator.hasNext();)
{
Group gNext = (Group) gIterator.next();
String gProp = gNext.getProperties().getProperty(GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString()))
{
groupsByWSetup.add(gNext);
}
}
if (sortedBy != null && sortedAsc != null)
{
context.put("groups", new SortedIterator (groupsByWSetup.iterator (), new SiteComparator (sortedBy, sortedAsc)));
}
return (String)getContext(data).get("template") + TEMPLATE[49];
case 50:
/* buildContextForTemplate chef_siteInfo-groupedit.vm
*
*/
Group g = getStateGroup(state);
if (g != null)
{
context.put("group", g);
context.put("newgroup", Boolean.FALSE);
}
else
{
context.put("newgroup", Boolean.TRUE);
}
if (state.getAttribute(STATE_GROUP_TITLE) != null)
{
context.put("title", state.getAttribute(STATE_GROUP_TITLE));
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null)
{
context.put("description", state.getAttribute(STATE_GROUP_DESCRIPTION));
}
Iterator siteMembers = new SortedIterator (getParticipantList(state).iterator (), new SiteComparator (SORTED_BY_PARTICIPANT_NAME, Boolean.TRUE.toString()));
if (siteMembers != null && siteMembers.hasNext())
{
context.put("generalMembers", siteMembers);
}
Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
if (state.getAttribute(STATE_GROUP_MEMBERS) != null)
{
context.put("groupMembers", new SortedIterator(groupMembersSet.iterator(), new SiteComparator (SORTED_BY_MEMBER_NAME, Boolean.TRUE.toString())));
}
context.put("groupMembersClone", groupMembersSet);
context.put("userDirectoryService", UserDirectoryService.getInstance());
return (String)getContext(data).get("template") + TEMPLATE[50];
case 51:
/* buildContextForTemplate chef_siteInfo-groupDeleteConfirm.vm
*
*/
context.put("site", site);
context.put("removeGroupIds", new ArrayList(Arrays.asList((String[])state.getAttribute(STATE_GROUP_REMOVE))));
return (String)getContext(data).get("template") + TEMPLATE[51];
}
// should never be reached
return (String)getContext(data).get("template") + TEMPLATE[0];
} // buildContextForTemplate
// obtain a list of available terms
private List getAvailableTerms()
{
List terms = CourseManagementService.getTerms();
List termsForSiteCreation = new Vector();
if (terms != null && terms.size() >0)
{
for (int i=0; i<terms.size();i++)
{
Term t = (Term) terms.get(i);
if (!t.getEndTime().before(TimeService.newTime()))
{
// don't show those terms which have ended already
termsForSiteCreation.add(t);
}
}
}
return termsForSiteCreation;
}
/**
* Launch the Page Order Helper Tool -- for ordering, adding and customizing pages
* @see case 12
*
*/
public void doPageOrderHelper(RunData data)
{
SessionState state = ((JetspeedRunData)data)
.getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//pass in the siteId of the site to be ordered (so it can configure sites other then the current site)
SessionManager.getCurrentToolSession()
.setAttribute(HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
//launch the helper
startHelper(data.getRequest(), "sakai-site-pageorder-helper");
}
//htripath: import materials from classic
/**
* Master import -- for import materials from a file
* @see case 45
*
*/
public void doAttachmentsMtrlFrmFile(RunData data)
{
SessionState state =
((JetspeedRunData) data).getPortletSessionState(
((JetspeedRunData) data).getJs_peid());
//state.setAttribute(FILE_UPLOAD_MAX_SIZE, ServerConfigurationService.getString("content.upload.max", "1"));
state.setAttribute(STATE_TEMPLATE_INDEX, "45");
} // doImportMtrlFrmFile
/**
* Handle File Upload request
* @see case 46
* @throws Exception
*/
public void doUpload_Mtrl_Frm_File(RunData data)
{
SessionState state =
((JetspeedRunData) data).getPortletSessionState(
((JetspeedRunData) data).getJs_peid());
List allzipList = new Vector();
List finalzipList = new Vector();
List directcopyList = new Vector();
// see if the user uploaded a file
FileItem fileFromUpload = null;
String fileName = null;
fileFromUpload = data.getParameters().getFileItem("file");
String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1");
int max_bytes = 1024 * 1024;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1024 * 1024;
}
if(fileFromUpload == null)
{
// "The user submitted a file to upload but it was too big!"
addAlert(state, rb.getString("importFile.size") + " " + max_file_size_mb + "MB " + rb.getString("importFile.exceeded"));
}
else if (fileFromUpload.getFileName() == null || fileFromUpload.getFileName().length() == 0)
{
addAlert(state, rb.getString("importFile.choosefile"));
}
else
{
byte[] fileData = fileFromUpload.get();
if(fileData.length >= max_bytes)
{
addAlert(state, rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("importFile.exceeded"));
}
else if(fileData.length > 0)
{
if (importService.isValidArchive(fileData)) {
ImportDataSource importDataSource = importService.parseFromFile(fileData);
Log.info("chef","Getting import items from manifest.");
List lst = importDataSource.getItemCategories();
if (lst != null && lst.size() > 0)
{
Iterator iter = lst.iterator();
while (iter.hasNext())
{
ImportMetadata importdata = (ImportMetadata) iter.next();
// Log.info("chef","Preparing import item '" + importdata.getId() + "'");
if ((!importdata.isMandatory())
&& (importdata.getFileName().endsWith(".xml")))
{
allzipList.add(importdata);
}
else
{
directcopyList.add(importdata);
}
}
}
//set Attributes
state.setAttribute(ALL_ZIP_IMPORT_SITES, allzipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, finalzipList);
state.setAttribute(DIRECT_ZIP_IMPORT_SITES, directcopyList);
state.setAttribute(CLASSIC_ZIP_FILE_NAME, fileName);
state.setAttribute(IMPORT_DATA_SOURCE, importDataSource);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} else { // uploaded file is not a valid archive
}
}
}
} // doImportMtrlFrmFile
/**
* Handle addition to list request
* @param data
*/
public void doAdd_MtrlSite(RunData data)
{
SessionState state =
((JetspeedRunData) data).getPortletSessionState(
((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List importSites = new ArrayList(Arrays.asList(params
.getStrings("addImportSelected")));
for (int i = 0; i < importSites.size(); i++)
{
String value = (String) importSites.get(i);
fnlList.add(removeItems(value, zipList));
}
state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} // doAdd_MtrlSite
/**
* Helper class for Add and remove
* @param value
* @param items
* @return
*/
public ImportMetadata removeItems(String value, List items)
{
ImportMetadata result = null;
for (int i = 0; i < items.size(); i++)
{
ImportMetadata item = (ImportMetadata) items.get(i);
if (value.equals(item.getId()))
{
result = (ImportMetadata) items.remove(i);
break;
}
}
return result;
}
/**
* Handle the request for remove
* @param data
*/
public void doRemove_MtrlSite(RunData data)
{
SessionState state =
((JetspeedRunData) data).getPortletSessionState(
((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List importSites = new ArrayList(Arrays.asList(params
.getStrings("removeImportSelected")));
for (int i = 0; i < importSites.size(); i++)
{
String value = (String) importSites.get(i);
zipList.add(removeItems(value, fnlList));
}
state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} // doAdd_MtrlSite
/**
* Handle the request for copy
* @param data
*/
public void doCopyMtrlSite(RunData data)
{
SessionState state =
((JetspeedRunData) data).getPortletSessionState(
((JetspeedRunData) data).getJs_peid());
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "47");
} // doCopy_MtrlSite
/**
* Handle the request for Save
* @param data
* @throws ImportException
*/
public void doSaveMtrlSite(RunData data)
{
SessionState state =
((JetspeedRunData) data).getPortletSessionState(
((JetspeedRunData) data).getJs_peid());
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List directList = (List) state.getAttribute(DIRECT_ZIP_IMPORT_SITES);
ImportDataSource importDataSource = (ImportDataSource) state.getAttribute(IMPORT_DATA_SOURCE);
// combine the selected import items with the mandatory import items
fnlList.addAll(directList);
Log.info("chef","doSaveMtrlSite() about to import " + fnlList.size() + " top level items");
Log.info("chef", "doSaveMtrlSite() the importDataSource is " + importDataSource.getClass().getName());
if (importDataSource instanceof SakaiArchive) {
Log.info("chef","doSaveMtrlSite() our data source is a Sakai format");
((SakaiArchive)importDataSource).buildSourceFolder(fnlList);
Log.info("chef","doSaveMtrlSite() source folder is " + ((SakaiArchive)importDataSource).getSourceFolder());
ArchiveService.merge(((SakaiArchive)importDataSource).getSourceFolder(), siteId, null);
} else {
importService.doImportItems(importDataSource.getItemsForCategories(fnlList), siteId);
}
//remove attributes
state.removeAttribute(ALL_ZIP_IMPORT_SITES);
state.removeAttribute(FINAL_ZIP_IMPORT_SITES);
state.removeAttribute(DIRECT_ZIP_IMPORT_SITES);
state.removeAttribute(CLASSIC_ZIP_FILE_NAME);
state.removeAttribute(SESSION_CONTEXT_ID);
state.removeAttribute(IMPORT_DATA_SOURCE);
state.setAttribute(STATE_TEMPLATE_INDEX, "48");
//state.setAttribute(STATE_TEMPLATE_INDEX, "28");
} // doSave_MtrlSite
public void doSaveMtrlSiteMsg(RunData data)
{
SessionState state =
((JetspeedRunData) data).getPortletSessionState(
((JetspeedRunData) data).getJs_peid());
//remove attributes
state.removeAttribute(ALL_ZIP_IMPORT_SITES);
state.removeAttribute(FINAL_ZIP_IMPORT_SITES);
state.removeAttribute(DIRECT_ZIP_IMPORT_SITES);
state.removeAttribute(CLASSIC_ZIP_FILE_NAME);
state.removeAttribute(SESSION_CONTEXT_ID);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
//htripath-end
/**
* Handle the site search request.
**/
public void doSite_search(RunData data, Context context)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// read the search form field into the state object
String search = StringUtil.trimToNull(data.getParameters().getString(FORM_SEARCH));
// set the flag to go to the prev page on the next list
if (search == null)
{
state.removeAttribute(STATE_SEARCH);
}
else
{
state.setAttribute(STATE_SEARCH, search);
}
} // doSite_search
/**
* Handle a Search Clear request.
**/
public void doSite_search_clear(RunData data, Context context)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// clear the search
state.removeAttribute(STATE_SEARCH);
} // doSite_search_clear
private void coursesIntoContext(SessionState state, Context context, Site site)
{
List providerCourseList = getProviderCourseList(StringUtil.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null && providerCourseList.size() > 0)
{
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
context.put("providerCourseList", providerCourseList);
}
String manualCourseListString = StringUtil.trimToNull(site.getProperties().getProperty(PROP_SITE_REQUEST_COURSE));
if (manualCourseListString != null)
{
List manualCourseList = new Vector();
if (manualCourseListString.indexOf("+") != -1)
{
manualCourseList = new ArrayList(Arrays.asList(manualCourseListString.split("\\+")));
}
else
{
manualCourseList.add(manualCourseListString);
}
state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList);
context.put("manualCourseList", manualCourseList);
}
}
/**
* buildInstructorSectionsList
* Build the CourseListItem list for this Instructor for the requested Term
*
*/
private void buildInstructorSectionsList(SessionState state, ParameterParser params, Context context)
{
//Site information
// The sections of the specified term having this person as Instructor
context.put ("providerCourseSectionList", state.getAttribute("providerCourseSectionList"));
context.put ("manualCourseSectionList", state.getAttribute("manualCourseSectionList"));
context.put ("term", (Term) state.getAttribute(STATE_TERM_SELECTED));
context.put ("termList", CourseManagementService.getTerms());
context.put(STATE_TERM_COURSE_LIST, (List) state.getAttribute(STATE_TERM_COURSE_LIST));
context.put("tlang",rb);
} // buildInstructorSectionsList
/**
* getProviderCourseList
* a course site/realm id in one of three formats,
* for a single section, for multiple sections of the same course, or
* for a cross-listing having multiple courses. getProviderCourseList
* parses a realm id into year, term, campus_code, catalog_nbr, section components.
* @param id is a String representation of the course realm id (external id).
*/
private List getProviderCourseList(String id)
{
Vector rv = new Vector();
if(id == null || id == NULL_STRING)
{
return rv;
}
String course_part = NULL_STRING;
String section_part = NULL_STRING;
String key = NULL_STRING;
try
{
//Break Provider Id into course_nbr parts
List course_nbrs = new ArrayList(Arrays.asList(id.split("\\+")));
//Iterate through course_nbrs
for (ListIterator i = course_nbrs.listIterator(); i.hasNext(); )
{
String course_nbr = (String) i.next();
//Course_nbr pattern will be for either one section or more than one section
if (course_nbr.indexOf("[") == -1)
{
// This course_nbr matches the pattern for one section
try
{
rv.add(course_nbr);
}
catch (Exception e)
{
M_log.warn(this + ": cannot find class " + course_nbr);
}
}
else
{
// This course_nbr matches the pattern for more than one section
course_part = course_nbr.substring(0, course_nbr.indexOf("[")); // includes trailing ","
section_part = course_nbr.substring(course_nbr.indexOf("[")+1, course_nbr.indexOf("]"));
String[] sect = section_part.split(",");
for (int j = 0; j < sect.length; j++)
{
key = course_part + sect[j];
try
{
rv.add(key);
}
catch (Exception e)
{
M_log.warn(this + ": cannot find class " + key);
}
}
}
}
}
catch (Exception ee)
{
M_log.warn(ee.getMessage());
}
return rv;
} // getProviderCourseList
/**
* {@inheritDoc}
*/
protected int sizeResources(SessionState state)
{
int size = 0;
String search = "";
String userId = SessionManager.getCurrentSessionUserId();
//if called from the site list page
if(((String)state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0"))
{
search = StringUtil.trimToNull((String) state.getAttribute(STATE_SEARCH));
if (SecurityService.isSuperUser())
{
// admin-type of user
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null)
{
if (view.equals(rb.getString("java.allmy")))
{
//search for non-user sites, using the criteria
size = SiteService.countSites(org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, null, search, null);
}
else if (view.equals(rb.getString("java.my")))
{
//search for a specific user site for the particular user id in the criteria - exact match only
try
{
SiteService.getSite(SiteService.getUserSiteId(search));
size++;
}
catch (IdUnusedException e) {}
}
else if (view.equalsIgnoreCase(rb.getString("java.gradtools")))
{
//search for gradtools sites
size = SiteService.countSites(org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, state.getAttribute(GRADTOOLS_SITE_TYPES), search, null);
}
else
{
//search for specific type of sites
size = SiteService.countSites(org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, view, search, null);
}
}
}
else
{
Site userWorkspaceSite = null;
try
{
userWorkspaceSite = SiteService.getSite(SiteService.getUserSiteId(userId));
}
catch (IdUnusedException e)
{
M_log.warn("Cannot find user " + SessionManager.getCurrentSessionUserId() + "'s My Workspace site.");
}
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view!= null)
{
if (view.equals(rb.getString("java.allmy")))
{
view = null;
//add my workspace if any
if (userWorkspaceSite != null)
{
if (search!=null)
{
if (userId.indexOf(search) != -1)
{
size++;
}
}
else
{
size++;
}
}
size += SiteService.countSites(org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, null, search, null);
}
else if (view.equalsIgnoreCase(rb.getString("java.gradtools")))
{
//search for gradtools sites
size += SiteService.countSites(org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, state.getAttribute(GRADTOOLS_SITE_TYPES), search, null);
}
else
{
// search for specific type of sites
size += SiteService.countSites(org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, view, search, null);
}
}
}
}
//for SiteInfo list page
else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals("12"))
{
List l = (List) state.getAttribute(STATE_PARTICIPANT_LIST);
size = (l!= null)?l.size():0;
}
return size;
} // sizeResources
/**
* {@inheritDoc}
*/
protected List readResourcesPage(SessionState state, int first, int last)
{
String search = StringUtil.trimToNull((String) state.getAttribute(STATE_SEARCH));
//if called from the site list page
if(((String)state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0"))
{
// get sort type
SortType sortType = null;
String sortBy = (String) state.getAttribute(SORTED_BY);
boolean sortAsc = (new Boolean((String) state.getAttribute(SORTED_ASC))).booleanValue();
if (sortBy.equals(SortType.TITLE_ASC.toString()))
{
sortType=sortAsc?SortType.TITLE_ASC:SortType.TITLE_DESC;
}
else if (sortBy.equals(SortType.TYPE_ASC.toString()))
{
sortType=sortAsc?SortType.TYPE_ASC:SortType.TYPE_DESC;
}
else if (sortBy.equals(SortType.CREATED_BY_ASC.toString()))
{
sortType=sortAsc?SortType.CREATED_BY_ASC:SortType.CREATED_BY_DESC;
}
else if (sortBy.equals(SortType.CREATED_ON_ASC.toString()))
{
sortType=sortAsc?SortType.CREATED_ON_ASC:SortType.CREATED_ON_DESC;
}
else if (sortBy.equals(SortType.PUBLISHED_ASC.toString()))
{
sortType=sortAsc?SortType.PUBLISHED_ASC:SortType.PUBLISHED_DESC;
}
if (SecurityService.isSuperUser())
{
// admin-type of user
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null)
{
if (view.equals(rb.getString("java.allmy")))
{
//search for non-user sites, using the criteria
return SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
null, search, null, sortType, new PagingPosition(first, last));
}
else if (view.equalsIgnoreCase(rb.getString("java.my")))
{
//search for a specific user site for the particular user id in the criteria - exact match only
List rv = new Vector();
try
{
Site userSite = SiteService.getSite(SiteService.getUserSiteId(search));
rv.add(userSite);
}
catch (IdUnusedException e) {}
return rv;
}
else if (view.equalsIgnoreCase(rb.getString("java.gradtools")))
{
//search for gradtools sites
return SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
state.getAttribute(GRADTOOLS_SITE_TYPES), search, null, sortType, new PagingPosition(first, last));
}
else
{
//search for a specific site
return SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.ANY,
view, search, null, sortType, new PagingPosition(first, last));
}
}
}
else
{
List rv = new Vector();
Site userWorkspaceSite = null;
String userId = SessionManager.getCurrentSessionUserId();
try
{
userWorkspaceSite = SiteService.getSite(SiteService.getUserSiteId(userId));
}
catch (IdUnusedException e)
{
M_log.warn("Cannot find user " + SessionManager.getCurrentSessionUserId() + "'s My Workspace site.");
}
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view!= null)
{
if (view.equals(rb.getString("java.allmy")))
{
view = null;
//add my workspace if any
if (userWorkspaceSite != null)
{
if (search!=null)
{
if (userId.indexOf(search) != -1)
{
rv.add(userWorkspaceSite);
}
}
else
{
rv.add(userWorkspaceSite);
}
}
rv.addAll(SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
null, search, null, sortType, new PagingPosition(first, last)));
}
else if (view.equalsIgnoreCase(rb.getString("java.gradtools")))
{
//search for a specific user site for the particular user id in the criteria - exact match only
rv.addAll(SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
state.getAttribute(GRADTOOLS_SITE_TYPES), search, null, sortType, new PagingPosition(first, last)));
}
else
{
rv.addAll(SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
view, search, null, sortType, new PagingPosition(first, last)));
}
}
return rv;
}
}
//if in Site Info list view
else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals("12"))
{
List participants = (state.getAttribute(STATE_PARTICIPANT_LIST) != null)?(List) state.getAttribute(STATE_PARTICIPANT_LIST):new Vector();
PagingPosition page = new PagingPosition(first, last);
page.validate(participants.size());
participants = participants.subList(page.getFirst()-1, page.getLast());
return participants;
}
return null;
} // readResourcesPage
/**
* get the selected tool ids from import sites
*/
private boolean select_import_tools(ParameterParser params, SessionState state)
{
// has the user selected any tool for importing?
boolean anyToolSelected = false;
Hashtable importTools = new Hashtable();
// the tools for current site
List selectedTools = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // String toolId's
for (int i=0; i<selectedTools.size(); i++)
{
// any tools chosen from import sites?
String toolId = (String) selectedTools.get(i);
if (params.getStrings(toolId) != null)
{
importTools.put(toolId, new ArrayList(Arrays.asList(params.getStrings(toolId))));
if (!anyToolSelected)
{
anyToolSelected = true;
}
}
}
state.setAttribute(STATE_IMPORT_SITE_TOOL, importTools);
return anyToolSelected;
} // select_import_tools
/**
* Is it from the ENW edit page?
* @return ture if the process went through the ENW page; false, otherwise
*/
private boolean fromENWModifyView(SessionState state)
{
boolean fromENW = false;
List oTools = (List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
List toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
for (int i=0; i<toolList.size() && !fromENW; i++)
{
String toolId = (String) toolList.get(i);
if (toolId.equals("sakai.mailbox") || toolId.indexOf("sakai.news") != -1 || toolId.indexOf("sakai.iframe") != -1)
{
if (oTools == null)
{
// if during site creation proces
fromENW = true;
}
else if (!oTools.contains(toolId))
{
//if user is adding either EmailArchive tool, News tool or Web Content tool, go to the Customize page for the tool
fromENW = true;
}
}
}
return fromENW;
}
/**
* doNew_site is called when the Site list tool bar New... button is clicked
*
*/
public void doNew_site ( RunData data )
throws Exception
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// start clean
cleanState(state);
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes != null)
{
if (siteTypes.size() == 1)
{
String siteType = (String) siteTypes.get(0);
if (!siteType.equals(ServerConfigurationService.getString("courseSiteType", "")))
{
// if only one site type is allowed and the type isn't course type
// skip the select site type step
setNewSiteType(state, siteType);
state.setAttribute (STATE_TEMPLATE_INDEX, "2");
}
else
{
state.setAttribute (STATE_TEMPLATE_INDEX, "1");
}
}
else
{
state.setAttribute (STATE_TEMPLATE_INDEX, "1");
}
}
} // doNew_site
/**
* doMenu_site_delete is called when the Site list tool bar Delete button is clicked
*
*/
public void doMenu_site_delete ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
if (params.getStrings ("selectedMembers") == null)
{
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
String[] removals = (String[]) params.getStrings ("selectedMembers");
state.setAttribute(STATE_SITE_REMOVALS, removals );
//present confirm delete template
state.setAttribute(STATE_TEMPLATE_INDEX, "8");
} // doMenu_site_delete
public void doSite_delete_confirmed ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
if (params.getStrings ("selectedMembers") == null)
{
M_log.warn("SiteAction.doSite_delete_confirmed selectedMembers null");
state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the site list
return;
}
List chosenList = new ArrayList(Arrays.asList(params.getStrings ("selectedMembers"))); // Site id's of checked sites
if(!chosenList.isEmpty())
{
for (ListIterator i = chosenList.listIterator(); i.hasNext(); )
{
String id = (String)i.next();
String site_title = NULL_STRING;
try
{
site_title = SiteService.getSite(id).getTitle();
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.doSite_delete_confirmed - IdUnusedException " + id);
addAlert(state,rb.getString("java.sitewith") + " " + id + " "+ rb.getString("java.couldnt")+" ");
}
if(SiteService.allowRemoveSite(id))
{
try
{
Site site = SiteService.getSite(id);
site_title = site.getTitle();
SiteService.removeSite(site);
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.doSite_delete_confirmed - IdUnusedException " + id);
addAlert(state, rb.getString("java.sitewith")+" " + site_title + "(" + id + ") "+ rb.getString("java.couldnt")+" ");
}
catch (PermissionException e)
{
M_log.warn("SiteAction.doSite_delete_confirmed - PermissionException, site " + site_title + "(" + id + ").");
addAlert(state, site_title + " "+ rb.getString("java.dontperm")+" ");
}
}
else
{
M_log.warn("SiteAction.doSite_delete_confirmed - allowRemoveSite failed for site " + id);
addAlert(state, site_title + " "+ rb.getString("java.dontperm") +" ");
}
}
}
state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the site list
// TODO: hard coding this frame id is fragile, portal dependent, and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
} // doSite_delete_confirmed
/**
* get the Site object based on SessionState attribute values
* @return Site object related to current state; null if no such Site object could be found
*/
protected Site getStateSite(SessionState state)
{
Site site = null;
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null)
{
try
{
site = SiteService.getSite((String) state.getAttribute(STATE_SITE_INSTANCE_ID));
}
catch (Exception ignore)
{
}
}
return site;
} // getStateSite
/**
* get the Group object based on SessionState attribute values
* @return Group object related to current state; null if no such Group object could be found
*/
protected Group getStateGroup(SessionState state)
{
Group group = null;
Site site = getStateSite(state);
if (site != null && state.getAttribute(STATE_GROUP_INSTANCE_ID) != null)
{
try
{
group = site.getGroup((String) state.getAttribute(STATE_GROUP_INSTANCE_ID));
}
catch (Exception ignore)
{
}
}
return group;
} // getStateGroup
/**
* do called when "eventSubmit_do" is in the request parameters to c
* is called from site list menu entry Revise... to get a locked site as editable and to go to the correct template to begin
* DB version of writes changes to disk at site commit whereas XML version writes at server shutdown
*/
public void doGet_site ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
//check form filled out correctly
if (params.getStrings ("selectedMembers") == null)
{
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
List chosenList = new ArrayList(Arrays.asList(params.getStrings ("selectedMembers"))); // Site id's of checked sites
String siteId = "";
if(!chosenList.isEmpty())
{
if(chosenList.size() != 1)
{
addAlert(state, rb.getString("java.please"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
siteId = (String) chosenList.get(0);
getReviseSite(state, siteId);
state.setAttribute(SORTED_BY, SORTED_BY_PARTICIPANT_NAME);
state.setAttribute (SORTED_ASC, Boolean.TRUE.toString());
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
state.setAttribute(STATE_PAGESIZE_SITESETUP, state.getAttribute(STATE_PAGESIZE));
}
Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO);
if (!h.containsKey(siteId))
{
// when first entered Site Info, set the participant list size to 200 as default
state.setAttribute(STATE_PAGESIZE, new Integer(200));
// update
h.put(siteId, new Integer(200));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
}
else
{
//restore the page size in site info tool
state.setAttribute(STATE_PAGESIZE, h.get(siteId));
}
} // doGet_site
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doMenu_site_reuse ( RunData data )
throws Exception
{
// called from chef_site-list.vm after a site has been selected from list
// create a new Site object based on selected Site object and put in state
//
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute (STATE_TEMPLATE_INDEX, "1");
} // doMenu_site_reuse
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doMenu_site_revise ( RunData data )
throws Exception
{
// called from chef_site-list.vm after a site has been selected from list
// get site as Site object, check SiteCreationStatus and SiteType of site, put in state, and set STATE_TEMPLATE_INDEX correctly
// set mode to state_mode_site_type
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute (STATE_TEMPLATE_INDEX, "1");
} // doMenu_site_revise
/**
* doView_sites is called when "eventSubmit_doView_sites" is in the request parameters
*/
public void doView_sites ( RunData data )
throws Exception
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
state.setAttribute (STATE_VIEW_SELECTED, params.getString("view"));
state.setAttribute (STATE_TEMPLATE_INDEX, "0");
resetPaging(state);
} // doView_sites
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doView ( RunData data )
throws Exception
{
// called from chef_site-list.vm with a select option to build query of sites
//
//
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute (STATE_TEMPLATE_INDEX, "1");
} // doView
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doSite_type ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
int index = Integer.valueOf(params.getString ("template-index")).intValue();
actionForTemplate("continue", index, params, state);
String type = StringUtil.trimToNull(params.getString ("itemType"));
int totalSteps = 0;
if (type == null)
{
addAlert(state, rb.getString("java.select")+" ");
}
else
{
setNewSiteType(state, type);
if (type.equalsIgnoreCase("course"))
{
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
String termId = params.getString("selectTerm");
Term t = CourseManagementService.getTerm(termId);
state.setAttribute(STATE_TERM_SELECTED, t);
if (t != null)
{
List courses = CourseManagementService.getInstructorCourses(userId, t.getYear(), t.getTerm());
// future term? roster information is not available yet?
int weeks = 0;
Calendar c = (Calendar) Calendar.getInstance().clone();
try
{
weeks = Integer.parseInt(ServerConfigurationService.getString("roster.available.weeks.before.term.start", "0"));
c.add(Calendar.DATE, weeks*7);
}
catch (Exception ignore)
{
}
if ((courses == null || courses != null && courses.size() == 0)
&& c.getTimeInMillis() < t.getStartTime().getTime())
{
//if a future term is selected
state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.TRUE);
}
else
{
state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.FALSE);
}
if (courses != null && courses.size() > 0)
{
state.setAttribute(STATE_TERM_COURSE_LIST, courses);
state.setAttribute (STATE_TEMPLATE_INDEX, "36");
state.setAttribute(STATE_AUTO_ADD, Boolean.TRUE);
totalSteps = 6;
}
else
{
state.removeAttribute(STATE_TERM_COURSE_LIST);
state.setAttribute (STATE_TEMPLATE_INDEX, "37");
totalSteps = 5;
}
}
else
{
state.setAttribute (STATE_TEMPLATE_INDEX, "37");
totalSteps = 5;
}
}
else if (type.equals("project"))
{
totalSteps = 4;
state.setAttribute (STATE_TEMPLATE_INDEX, "2");
}
else if (type.equals (SITE_TYPE_GRADTOOLS_STUDENT))
{
//if a GradTools site use pre-defined site info and exclude from public listing
SiteInfo siteInfo = new SiteInfo();
if(state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
User currentUser = UserDirectoryService.getCurrentUser();
siteInfo.title = rb.getString("java.grad")+" - " + currentUser.getId();
siteInfo.description = rb.getString("java.gradsite")+" " + currentUser.getDisplayName();
siteInfo.short_description = rb.getString("java.grad")+" - " + currentUser.getId();
siteInfo.include = false;
state.setAttribute(STATE_SITE_INFO, siteInfo);
//skip directly to confirm creation of site
state.setAttribute (STATE_TEMPLATE_INDEX, "42");
}
else
{
state.setAttribute (STATE_TEMPLATE_INDEX, "2");
}
}
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) == null)
{
state.setAttribute(SITE_CREATE_TOTAL_STEPS, new Integer(totalSteps));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) == null)
{
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(1));
}
} // doSite_type
/**
* cleanEditGroupParams
* clean the state parameters used by editing group process
*
*/
public void cleanEditGroupParams ( SessionState state )
{
state.removeAttribute(STATE_GROUP_INSTANCE_ID);
state.removeAttribute(STATE_GROUP_TITLE);
state.removeAttribute(STATE_GROUP_DESCRIPTION);
state.removeAttribute(STATE_GROUP_MEMBERS);
state.removeAttribute(STATE_GROUP_REMOVE);
} //cleanEditGroupParams
/**
* doGroup_edit
*
*/
public void doGroup_update ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
Set gMemberSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
Site site = getStateSite(state);
String title = StringUtil.trimToNull(params.getString(rb.getString("group.title")));
state.setAttribute(STATE_GROUP_TITLE, title);
String description = StringUtil.trimToZero(params.getString(rb.getString("group.description")));
state.setAttribute(STATE_GROUP_DESCRIPTION, description);
boolean found = false;
String option = params.getString("option");
if (option.equals("add"))
{
// add selected members into it
if (params.getStrings("generallist") != null)
{
List addMemberIds = new ArrayList(Arrays.asList(params.getStrings("generallist")));
for (int i=0; i<addMemberIds.size(); i++)
{
String aId = (String) addMemberIds.get(i);
found = false;
for(Iterator iSet = gMemberSet.iterator(); !found && iSet.hasNext();)
{
if (((Member) iSet.next()).getUserEid().equals(aId))
{
found = true;
}
}
if (!found)
{
try
{
User u = UserDirectoryService.getUser(aId);
gMemberSet.add(site.getMember(u.getId()));
}
catch (UserNotDefinedException e)
{
try
{
User u2 = UserDirectoryService.getUserByEid(aId);
gMemberSet.add(site.getMember(u2.getId()));
}
catch (UserNotDefinedException ee)
{
M_log.warn(this + ee.getMessage() + aId);
}
}
}
}
}
state.setAttribute(STATE_GROUP_MEMBERS, gMemberSet);
}
else if (option.equals("remove"))
{
// update the group member list by remove selected members from it
if (params.getStrings("grouplist") != null)
{
List removeMemberIds = new ArrayList(Arrays.asList(params.getStrings("grouplist")));
for (int i=0; i<removeMemberIds.size(); i++)
{
found = false;
for(Iterator iSet = gMemberSet.iterator(); !found && iSet.hasNext();)
{
Member mSet = (Member) iSet.next();
if (mSet.getUserId().equals((String) removeMemberIds.get(i)))
{
found = true;
gMemberSet.remove(mSet);
}
}
}
}
state.setAttribute(STATE_GROUP_MEMBERS, gMemberSet);
}
else if (option.equals("cancel"))
{
// cancel from the update the group member process
doCancel(data);
cleanEditGroupParams(state);
}
else if (option.equals("save"))
{
Group group = null;
if (site != null && state.getAttribute(STATE_GROUP_INSTANCE_ID) != null)
{
try
{
group = site.getGroup((String) state.getAttribute(STATE_GROUP_INSTANCE_ID));
}
catch (Exception ignore)
{
}
}
if (title == null)
{
addAlert(state, rb.getString("editgroup.titlemissing"));
}
else
{
if (group == null)
{
// when adding a group, check whether the group title has been used already
boolean titleExist = false;
for (Iterator iGroups = site.getGroups().iterator(); !titleExist && iGroups.hasNext(); )
{
Group iGroup = (Group) iGroups.next();
if (iGroup.getTitle().equals(title))
{
// found same title
titleExist = true;
}
}
if (titleExist)
{
addAlert(state, rb.getString("group.title.same"));
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (group == null)
{
// adding new group
group = site.addGroup();
group.getProperties().addProperty(GROUP_PROP_WSETUP_CREATED, Boolean.TRUE.toString());
}
if (group != null)
{
group.setTitle(title);
group.setDescription(description);
// save the modification to group members
// remove those no longer included in the group
Set members = group.getMembers();
for(Iterator iMembers = members.iterator(); iMembers.hasNext();)
{
found = false;
String mId = ((Member)iMembers.next()).getUserId();
for(Iterator iMemberSet = gMemberSet.iterator(); !found && iMemberSet.hasNext();)
{
if (mId.equals(((Member) iMemberSet.next()).getUserId()))
{
found = true;
}
}
if (!found)
{
group.removeMember(mId);
}
}
// add those seleted members
for(Iterator iMemberSet = gMemberSet.iterator(); iMemberSet.hasNext();)
{
String memberId = ((Member) iMemberSet.next()).getUserId();
if (group.getUserRole(memberId) == null)
{
Role r = site.getUserRole(memberId);
Member m = site.getMember(memberId);
// for every member added through the "Manage Groups" interface, he should be defined as non-provided
group.addMember(memberId, r!= null?r.getId():"", m!=null?m.isActive():true, false);
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
}
catch (PermissionException e)
{
}
// return to group list view
state.setAttribute (STATE_TEMPLATE_INDEX, "49");
cleanEditGroupParams(state);
}
}
}
}
} // doGroup_updatemembers
/**
* doGroup_new
*
*/
public void doGroup_new ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
if (state.getAttribute(STATE_GROUP_TITLE) == null)
{
state.setAttribute(STATE_GROUP_TITLE, "");
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) == null)
{
state.setAttribute(STATE_GROUP_DESCRIPTION, "");
}
if (state.getAttribute(STATE_GROUP_MEMBERS) == null)
{
state.setAttribute(STATE_GROUP_MEMBERS, new HashSet());
}
state.setAttribute (STATE_TEMPLATE_INDEX, "50");
} // doGroup_new
/**
* doGroup_edit
*
*/
public void doGroup_edit ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String groupId = data.getParameters ().getString("groupId");
state.setAttribute(STATE_GROUP_INSTANCE_ID, groupId);
Site site = getStateSite(state);
if (site != null)
{
Group g = site.getGroup(groupId);
if (g != null)
{
if (state.getAttribute(STATE_GROUP_TITLE) == null)
{
state.setAttribute(STATE_GROUP_TITLE, g.getTitle());
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) == null)
{
state.setAttribute(STATE_GROUP_DESCRIPTION, g.getDescription());
}
if (state.getAttribute(STATE_GROUP_MEMBERS) == null)
{
// double check the member existance
Set gMemberSet = g.getMembers();
Set rvGMemberSet = new HashSet();
for(Iterator iSet = gMemberSet.iterator(); iSet.hasNext();)
{
Member member = (Member) iSet.next();
try
{
UserDirectoryService.getUser(member.getUserId());
((Set) rvGMemberSet).add(member);
}
catch (UserNotDefinedException e)
{
// cannot find user
M_log.warn(this + rb.getString("user.notdefined") + member.getUserId());
}
}
state.setAttribute(STATE_GROUP_MEMBERS, rvGMemberSet);
}
}
}
state.setAttribute (STATE_TEMPLATE_INDEX, "50");
} // doGroup_edit
/**
* doGroup_remove_prep
* Go to confirmation page before deleting group(s)
*
*/
public void doGroup_remove_prep ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String[] removeGroupIds = data.getParameters ().getStrings("removeGroups");
if (removeGroupIds.length > 0)
{
state.setAttribute(STATE_GROUP_REMOVE, removeGroupIds);
state.setAttribute (STATE_TEMPLATE_INDEX, "51");
}
} // doGroup_remove_prep
/**
* doGroup_remove_confirmed
* Delete selected groups after confirmation
*
*/
public void doGroup_remove_confirmed ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String[] removeGroupIds = (String[]) state.getAttribute(STATE_GROUP_REMOVE);
Site site = getStateSite(state);
for (int i=0; i<removeGroupIds.length; i++)
{
if (site != null)
{
Group g = site.getGroup(removeGroupIds[i]);
if (g != null)
{
site.removeGroup(g);
}
}
}
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("editgroup.site.notfound.alert"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("editgroup.site.permission.alert"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
cleanEditGroupParams(state);
state.setAttribute (STATE_TEMPLATE_INDEX, "49");
}
} // doGroup_remove_confirmed
/**
* doMenu_edit_site_info
* The menu choice to enter group view
*
*/
public void doMenu_group ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// reset sort criteria
state.setAttribute(SORTED_BY, rb.getString("group.title"));
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
state.setAttribute (STATE_TEMPLATE_INDEX, "49");
} // doMenu_group
/**
* dispatch to different functions based on the option value in the parameter
*/
public void doManual_add_course ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String option = params.getString("option");
if (option.equalsIgnoreCase("change") || option.equalsIgnoreCase("add"))
{
readCourseSectionInfo(state, params);
String uniqname = StringUtil.trimToNull(params.getString("uniqname"));
state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname);
if (getStateSite(state) == null)
{
// creating new site
updateSiteInfo(params, state);
}
if (option.equalsIgnoreCase("add"))
{
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& !((Boolean) state.getAttribute(STATE_FUTURE_TERM_SELECTED)).booleanValue())
{
// if a future term is selected, do not check authorization uniqname
if (uniqname == null)
{
addAlert(state, rb.getString("java.author") + " " + ServerConfigurationService.getString("noEmailInIdAccountName") + ". ");
}
else
{
try
{
UserDirectoryService.getUserByEid(uniqname);
}
catch (UserNotDefinedException e)
{
addAlert(state, rb.getString("java.validAuthor1")+" "+ ServerConfigurationService.getString("noEmailInIdAccountName") + " "+ rb.getString("java.validAuthor2"));
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (getStateSite(state) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
}
else
{
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
}
}
updateCurrentStep(state, true);
}
}
else if (option.equalsIgnoreCase("back"))
{
doBack(data);
if (state.getAttribute(STATE_MESSAGE) == null)
{
updateCurrentStep(state, false);
}
}
else if (option.equalsIgnoreCase("cancel"))
{
if (getStateSite(state) == null)
{
doCancel_create(data);
}
else
{
doCancel(data);
}
}
} // doManual_add_course
/**
* read the input information of subject, course and section in the manual site creation page
*/
private void readCourseSectionInfo (SessionState state, ParameterParser params)
{
int oldNumber = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
oldNumber = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
}
// read the user input
int validInputSites = 0;
boolean validInput = true;
List requiredFields = CourseManagementService.getCourseIdRequiredFields();
List multiCourseInputs = new Vector();
for (int i = 0; i < oldNumber; i++)
{
List aCourseInputs = new Vector();
int emptyInputNum = 0;
// iterate through all required fields
for (int k = 0; k<requiredFields.size(); k++)
{
String field = (String) requiredFields.get(k);
String fieldInput = StringUtil.trimToZero(params.getString(field + i));
aCourseInputs.add(fieldInput);
if (fieldInput.length() == 0)
{
// is this an empty String input?
emptyInputNum++;
}
}
// add to the multiCourseInput vector
multiCourseInputs.add(i, aCourseInputs);
// is any input invalid?
if (emptyInputNum == 0)
{
// valid if all the inputs are not empty
validInputSites++;
}
else if (emptyInputNum == requiredFields.size())
{
// ignore if all inputs are empty
}
else
{
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& ((Boolean) state.getAttribute(STATE_FUTURE_TERM_SELECTED)).booleanValue())
{
// if future term selected, then not all fields are required %%%
validInputSites++;
}
else
{
validInput = false;
}
}
}
//how many more course/section to include in the site?
String option = params.getString("option");
if (option.equalsIgnoreCase("change"))
{
if (params.getString("number") != null)
{
int newNumber = Integer.parseInt(params.getString("number"));
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(oldNumber + newNumber));
for (int j = 0; j<newNumber; j++)
{
// add a new course input
List aCourseInputs = new Vector();
// iterate through all required fields
for (int m = 0; m<requiredFields.size(); m++)
{
aCourseInputs.add("");
}
multiCourseInputs.add(aCourseInputs);
}
}
}
state.setAttribute(STATE_MANUAL_ADD_COURSE_FIELDS, multiCourseInputs);
if (!option.equalsIgnoreCase("change"))
{
if (!validInput || validInputSites == 0)
{
// not valid input
addAlert(state, rb.getString("java.miss"));
}
else
{
// valid input, adjust the add course number
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(validInputSites));
}
}
// set state attributes
state.setAttribute(FORM_ADDITIONAL, StringUtil.trimToZero(params.getString("additional")));
SiteInfo siteInfo = new SiteInfo();
if(state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
List providerCourseList = (List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
//store the manually requested sections in one site property
if ((providerCourseList == null || providerCourseList.size() == 0) && multiCourseInputs.size() > 0)
{
String courseId = CourseManagementService.getCourseId((Term) state.getAttribute(STATE_TERM_SELECTED), (List) multiCourseInputs.get(0));
String title = "";
try
{
title = CourseManagementService.getCourseName(courseId);
}
catch (IdUnusedException e)
{
// ignore
}
siteInfo.title = appendTermInSiteTitle(state, title);
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
} // readCourseSectionInfo
/**
* set the site type for new site
*
* @param type The type String
*/
private void setNewSiteType(SessionState state, String type)
{
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
//start out with fresh site information
SiteInfo siteInfo = new SiteInfo();
siteInfo.site_type = type;
siteInfo.published = true;
state.setAttribute(STATE_SITE_INFO, siteInfo);
// get registered tools list
Set categories = new HashSet();
categories.add(type);
Set toolRegistrations = ToolManager.findTools(categories, null);
List tools = new Vector();
SortedIterator i = new SortedIterator(toolRegistrations.iterator(), new ToolComparator());
for (; i.hasNext();)
{
// form a new Tool
Tool tr = (Tool) i.next();
MyTool newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = tr.getId();
newTool.description = tr.getDescription();
tools.add(newTool);
}
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, tools);
state.setAttribute (STATE_SITE_TYPE, type);
}
/**
* Set the field on which to sort the list of students
*
*/
public void doSort_roster ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the field on which to sort the student list
ParameterParser params = data.getParameters ();
String criterion = params.getString ("criterion");
// current sorting sequence
String asc = "";
if (!criterion.equals (state.getAttribute (SORTED_BY)))
{
state.setAttribute (SORTED_BY, criterion);
asc = Boolean.TRUE.toString ();
state.setAttribute (SORTED_ASC, asc);
}
else
{
// current sorting sequence
asc = (String) state.getAttribute (SORTED_ASC);
//toggle between the ascending and descending sequence
if (asc.equals (Boolean.TRUE.toString ()))
{
asc = Boolean.FALSE.toString ();
}
else
{
asc = Boolean.TRUE.toString ();
}
state.setAttribute (SORTED_ASC, asc);
}
} //doSort_roster
/**
* Set the field on which to sort the list of sites
*
*/
public void doSort_sites ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//call this method at the start of a sort for proper paging
resetPaging(state);
//get the field on which to sort the site list
ParameterParser params = data.getParameters ();
String criterion = params.getString ("criterion");
// current sorting sequence
String asc = "";
if (!criterion.equals (state.getAttribute (SORTED_BY)))
{
state.setAttribute (SORTED_BY, criterion);
asc = Boolean.TRUE.toString ();
state.setAttribute (SORTED_ASC, asc);
}
else
{
// current sorting sequence
asc = (String) state.getAttribute (SORTED_ASC);
//toggle between the ascending and descending sequence
if (asc.equals (Boolean.TRUE.toString ()))
{
asc = Boolean.FALSE.toString ();
}
else
{
asc = Boolean.TRUE.toString ();
}
state.setAttribute (SORTED_ASC, asc);
}
state.setAttribute(SORTED_BY, criterion);
} //doSort_sites
/**
* doContinue is called when "eventSubmit_doContinue" is in the request parameters
*/
public void doContinue ( RunData data )
{
// Put current form data in state and continue to the next template, make any permanent changes
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
int index = Integer.valueOf(params.getString ("template-index")).intValue();
// Let actionForTemplate know to make any permanent changes before continuing to the next template
String direction = "continue";
actionForTemplate(direction, index, params, state);
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (index == 9)
{
// go to the send site publish email page if "publish" option is chosen
SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (sInfo.getPublished())
{
state.setAttribute(STATE_TEMPLATE_INDEX, "16");
}
else
{
state.setAttribute(STATE_TEMPLATE_INDEX, "17");
}
}
else if (params.getString ("continue") != null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString ("continue"));
}
}
}// doContinue
/**
* doBack is called when "eventSubmit_doBack" is in the request parameters
* Pass parameter to actionForTemplate to request action for backward direction
*/
public void doBack ( RunData data )
{
// Put current form data in state and return to the previous template
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
int currentIndex = Integer.parseInt((String)state.getAttribute(STATE_TEMPLATE_INDEX));
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString ("back"));
// Let actionForTemplate know not to make any permanent changes before continuing to the next template
String direction = "back";
actionForTemplate(direction, currentIndex, params, state);
}// doBack
/**
* doFinish is called when a site has enough information to be saved as an unpublished site
*/
public void doFinish ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString ("continue"));
int index = Integer.valueOf(params.getString ("template-index")).intValue();
actionForTemplate("continue", index, params, state);
addNewSite(params, state);
addFeatures(state);
Site site = getStateSite(state);
// for course sites
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
String siteId = site.getId();
ResourcePropertiesEdit rp = site.getPropertiesEdit();
Term term = null;
if (state.getAttribute(STATE_TERM_SELECTED) != null)
{
term = (Term) state.getAttribute(STATE_TERM_SELECTED);
rp.addProperty(PROP_SITE_TERM, term.getId());
}
List providerCourseList = (List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
int manualAddNumber = 0;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
manualAddNumber = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
}
String realm = SiteService.siteReference(siteId);
if ((providerCourseList != null) && (providerCourseList.size() != 0))
{
String providerRealm = buildExternalRealm(siteId, state, providerCourseList);
try
{
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realm);
realmEdit.setProviderGroupId(providerRealm);
AuthzGroupService.save(realmEdit);
}
catch (GroupNotDefinedException e)
{
M_log.warn(this + " IdUnusedException, not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.realm"));
return;
}
// catch (AuthzPermissionException e)
// {
// M_log.warn(this + " PermissionException, user does not have permission to edit AuthzGroup object.");
// addAlert(state, rb.getString("java.notaccess"));
// return;
// }
catch (Exception e)
{
addAlert(state, this + rb.getString("java.problem"));
return;
}
addSubjectAffliates(state, providerCourseList);
sendSiteNotification(state, providerCourseList);
}
if (manualAddNumber != 0)
{
// set the manual sections to the site property
String manualSections = "";
List manualCourseInputs = (List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
for (int j = 0; j < manualAddNumber; j++)
{
manualSections = manualSections.concat(CourseManagementService.getCourseId(term, (List) manualCourseInputs.get(j))).concat("+");
}
// trim the trailing plus sign
if (manualSections.endsWith("+"))
{
manualSections = manualSections.substring(0, manualSections.lastIndexOf("+"));
}
rp.addProperty(PROP_SITE_REQUEST_COURSE, manualSections);
// send request
sendSiteRequest(state, "new", manualAddNumber, manualCourseInputs);
}
}
// commit site
commitSite(site);
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
//now that the site exists, we can set the email alias when an Email Archive tool has been selected
String alias = StringUtil.trimToNull((String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
if (alias != null)
{
String channelReference = mailArchiveChannelReference(siteId);
try
{
AliasService.setAlias(alias, channelReference);
}
catch (IdUsedException ee)
{
addAlert(state, rb.getString("java.alias")+" " + alias + " "+rb.getString("java.exists"));
}
catch (IdInvalidException ee)
{
addAlert(state, rb.getString("java.alias")+" " + alias + " "+rb.getString("java.isinval"));
}
catch (PermissionException ee)
{
addAlert(state, rb.getString("java.addalias")+" ");
}
}
// TODO: hard coding this frame id is fragile, portal dependent, and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
resetPaging(state);
// clean state variables
cleanState(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
}// doFinish
private void addSubjectAffliates(SessionState state, List providerCourseList)
{
Vector subjAffiliates = new Vector();
Vector affiliates = new Vector();
String subject = "";
String affiliate = "";
//get all subject and campus pairs for this site
for (ListIterator i = providerCourseList.listIterator(); i.hasNext(); )
{
String courseId = (String) i.next();
try
{
Course c = CourseManagementService.getCourse(courseId);
if(c.getSubject() != null && c.getSubject() != "") subject = c.getSubject();
subjAffiliates.add(subject);
}
catch (IdUnusedException e)
{
// M_log.warn(this + " cannot find course " + courseId + ". ");
}
}
// remove duplicates
Collection noDups = new HashSet(subjAffiliates);
// get affliates for subjects
for (Iterator i = noDups.iterator(); i.hasNext(); )
{
subject = (String)i.next();
Collection uniqnames = getSubjectAffiliates(state, subject);
try
{
affiliates.addAll(uniqnames);
}
catch(Exception ignore){}
}
// remove duplicates
Collection addAffiliates = new HashSet(affiliates);
// try to add uniqnames with appropriate role
for (Iterator i = addAffiliates.iterator(); i.hasNext(); )
{
affiliate = (String)i.next();
try
{
User user = UserDirectoryService.getUserByEid(affiliate);
String realmId = "/site/" + (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
if (AuthzGroupService.allowUpdate(realmId))
{
try
{
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId);
Role role = realmEdit.getRole("Affiliate");
realmEdit.addMember(user.getId(), role.getId(), true, false);
AuthzGroupService.save(realmEdit);
}
catch(Exception ignore) {}
}
}
catch(Exception ignore)
{
M_log.warn(this + " cannot find affiliate " + affiliate);
}
}
} //addSubjectAffliates
/**
* @params - SessionState state
* @params - String subject is the University's Subject code
* @return - Collection of uniqnames of affiliates for this subject
*/
private Collection getSubjectAffiliates(SessionState state, String subject)
{
Collection rv = null;
List allAffiliates = (Vector) state.getAttribute(STATE_SUBJECT_AFFILIATES);
//iterate through the subjects looking for this subject
for (Iterator i = allAffiliates.iterator(); i.hasNext(); )
{
SubjectAffiliates sa = (SubjectAffiliates)i.next();
if(subject.equals(sa.getCampus() + "_" + sa.getSubject())) return sa.getUniqnames();
}
return rv;
} //getSubjectAffiliates
/**
* buildExternalRealm creates a site/realm id in one of three formats,
* for a single section, for multiple sections of the same course, or
* for a cross-listing having multiple courses
* @param sectionList is a Vector of CourseListItem
* @param id The site id
*/
private String buildExternalRealm(String id, SessionState state, List providerIdList)
{
String realm = SiteService.siteReference(id);
if (!AuthzGroupService.allowUpdate(realm))
{
addAlert(state, rb.getString("java.rosters"));
return null;
}
return CourseManagementService.getProviderId(providerIdList);
} // buildExternalRealm
/**
* Notification sent when a course site needs to be set up by Support
*
*/
private void sendSiteRequest(SessionState state, String request, int requestListSize, List requestFields)
{
User cUser = UserDirectoryService.getCurrentUser();
boolean sendEmailToRequestee = false;
StringBuffer buf = new StringBuffer();
// get the request email from configuration
String requestEmail = ServerConfigurationService.getString("setup.request", null);
if (requestEmail == null)
{
M_log.warn(this + " - no 'setup.request' in configuration");
}
else
{
String noEmailInIdAccountName = ServerConfigurationService.getString("noEmailInIdAccountName", "");
SiteInfo siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
Site site = getStateSite(state);
String id = site.getId();
String title = site.getTitle();
Time time = TimeService.newTime();
String local_time = time.toStringLocalTime();
String local_date = time.toStringLocalDate();
Term term = null;
boolean termExist = false;
if (state.getAttribute(STATE_TERM_SELECTED) != null)
{
termExist = true;
term = (Term) state.getAttribute(STATE_TERM_SELECTED);
}
String productionSiteName = ServerConfigurationService.getServerName();
String from = NULL_STRING;
String to = NULL_STRING;
String headerTo = NULL_STRING;
String replyTo = NULL_STRING;
String message_subject = NULL_STRING;
String content = NULL_STRING;
String sessionUserName = cUser.getDisplayName();
String additional = NULL_STRING;
if (request.equals("new"))
{
additional = siteInfo.getAdditional();
}
else
{
additional = (String)state.getAttribute(FORM_ADDITIONAL);
}
boolean isFutureTerm = false;
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null && ((Boolean) state.getAttribute(STATE_FUTURE_TERM_SELECTED)).booleanValue())
{
isFutureTerm = true;
}
// message subject
if (termExist)
{
message_subject = rb.getString("java.sitereqfrom")+" " + sessionUserName + " " + rb.getString("java.for") + " " + term.getId();
}
else
{
message_subject = rb.getString("java.official")+" " + sessionUserName;
}
// there is no offical instructor for future term sites
String requestId = (String) state.getAttribute(STATE_SITE_QUEST_UNIQNAME);
if (!isFutureTerm)
{
//To site quest account - the instructor of record's
if (requestId != null)
{
try
{
User instructor = UserDirectoryService.getUser(requestId);
from = requestEmail;
to = instructor.getEmail();
headerTo = instructor.getEmail();
replyTo = requestEmail;
buf.append(rb.getString("java.hello")+" \n\n");
buf.append(rb.getString("java.receiv")+" " + sessionUserName + ", ");
buf.append(rb.getString("java.who")+"\n");
if (termExist)
{
buf.append(term.getTerm() + " " + term.getYear() + "\n");
}
// what are the required fields shown in the UI
List requiredFields = CourseManagementService.getCourseIdRequiredFields();
for (int i = 0; i < requestListSize; i++)
{
List requiredFieldList = (List) requestFields.get(i);
for (int j = 0; j < requiredFieldList.size(); j++)
{
String requiredField = (String) requiredFields.get(j);
buf.append(requiredField +"\t" + requiredFieldList.get(j) + "\n");
}
}
buf.append("\n" + rb.getString("java.sitetitle")+"\t" + title + "\n");
buf.append(rb.getString("java.siteid")+"\t" + id);
buf.append("\n\n"+rb.getString("java.according")+" " + sessionUserName + " "+rb.getString("java.record"));
buf.append(" " + rb.getString("java.canyou")+" " + sessionUserName + " "+ rb.getString("java.assoc")+"\n\n");
buf.append(rb.getString("java.respond")+" " + sessionUserName + rb.getString("java.appoint")+"\n\n");
buf.append(rb.getString("java.thanks")+"\n");
buf.append(productionSiteName + " "+rb.getString("java.support"));
content = buf.toString();
// send the email
EmailService.send(from, to, message_subject, content, headerTo, replyTo, null);
// email has been sent successfully
sendEmailToRequestee = true;
}
catch (UserNotDefinedException ee)
{
} // try
}
}
//To Support
from = cUser.getEmail();
to = requestEmail;
headerTo = requestEmail;
replyTo = cUser.getEmail();
buf.setLength(0);
buf.append(rb.getString("java.to")+"\t\t" + productionSiteName + " "+rb.getString("java.supp")+"\n");
buf.append("\n"+rb.getString("java.from")+"\t" + sessionUserName + "\n");
if (request.equals("new"))
{
buf.append(rb.getString("java.subj")+"\t"+rb.getString("java.sitereq")+"\n");
}
else
{
buf.append(rb.getString("java.subj")+"\t"+rb.getString("java.sitechreq")+"\n");
}
buf.append(rb.getString("java.date")+"\t" + local_date + " " + local_time + "\n\n");
if (request.equals("new"))
{
buf.append(rb.getString("java.approval") + " " + productionSiteName + " "+rb.getString("java.coursesite")+" ");
}
else
{
buf.append(rb.getString("java.approval2")+" " + productionSiteName + " "+rb.getString("java.coursesite")+" ");
}
if (termExist)
{
buf.append(term.getTerm() + " " + term.getYear());
}
if (requestListSize >1)
{
buf.append(" "+rb.getString("java.forthese")+" " + requestListSize + " "+rb.getString("java.sections")+"\n\n");
}
else
{
buf.append(" "+rb.getString("java.forthis")+"\n\n");
}
//what are the required fields shown in the UI
List requiredFields = CourseManagementService.getCourseIdRequiredFields();
for (int i = 0; i < requestListSize; i++)
{
List requiredFieldList = (List) requestFields.get(i);
for (int j = 0; j < requiredFieldList.size(); j++)
{
String requiredField = (String) requiredFields.get(j);
buf.append(requiredField +"\t" + requiredFieldList.get(j) + "\n");
}
}
buf.append(rb.getString("java.name")+"\t" + sessionUserName + " (" + noEmailInIdAccountName + " " + cUser.getEid() + ")\n");
buf.append(rb.getString("java.email")+"\t" + replyTo + "\n\n");
buf.append(rb.getString("java.sitetitle")+"\t" + title + "\n");
buf.append(rb.getString("java.siteid")+"\t" + id + "\n");
buf.append(rb.getString("java.siteinstr")+"\n" + additional + "\n\n");
if (!isFutureTerm)
{
if (sendEmailToRequestee)
{
buf.append(rb.getString("java.authoriz")+" " + requestId + " "+rb.getString("java.asreq"));
}
else
{
buf.append(rb.getString("java.thesiteemail")+" " + requestId + " "+rb.getString("java.asreq"));
}
}
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo, replyTo, null);
//To the Instructor
from = requestEmail;
to = cUser.getEmail();
headerTo = to;
replyTo = to;
buf.setLength(0);
buf.append(rb.getString("java.isbeing")+" ");
buf.append(rb.getString("java.meantime")+"\n\n");
buf.append(rb.getString("java.copy")+"\n\n");
buf.append(content);
buf.append("\n"+rb.getString("java.wish")+" " + requestEmail);
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo, replyTo, null);
state.setAttribute(REQUEST_SENT, new Boolean(true));
} // if
} // sendSiteRequest
/**
* Notification sent when a course site is set up automatcally
*
*/
private void sendSiteNotification(SessionState state, List notifySites)
{
// get the request email from configuration
String requestEmail = ServerConfigurationService.getString("setup.request", null);
if (requestEmail == null)
{
M_log.warn(this + " - no 'setup.request' in configuration");
}
else
{
// send emails
Site site = getStateSite(state);
String id = site.getId();
String title = site.getTitle();
Time time = TimeService.newTime();
String local_time = time.toStringLocalTime();
String local_date = time.toStringLocalDate();
String term_name = "";
if (state.getAttribute(STATE_TERM_SELECTED) != null)
{
term_name = ((Term) state.getAttribute(STATE_TERM_SELECTED)).getId();
}
String message_subject = rb.getString("java.official")+ " " + UserDirectoryService.getCurrentUser().getDisplayName() + " " + rb.getString("java.for") + " " + term_name;
String from = NULL_STRING;
String to = NULL_STRING;
String headerTo = NULL_STRING;
String replyTo = NULL_STRING;
String sender = UserDirectoryService.getCurrentUser().getDisplayName();
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
try
{
userId = UserDirectoryService.getUserEid(userId);
}
catch (UserNotDefinedException e)
{
M_log.warn(this + rb.getString("user.notdefined") + " " + userId);
}
//To Support
from = UserDirectoryService.getCurrentUser().getEmail();
to = requestEmail;
headerTo = requestEmail;
replyTo = UserDirectoryService.getCurrentUser().getEmail();
StringBuffer buf = new StringBuffer();
buf.append("\n"+rb.getString("java.fromwork")+" " + ServerConfigurationService.getServerName() + " "+rb.getString("java.supp")+":\n\n");
buf.append(rb.getString("java.off")+" '" + title + "' (id " + id + "), " +rb.getString("java.wasset")+" ");
buf.append(sender + " (" + userId + ", " + rb.getString("java.email2")+ " " + replyTo + ") ");
buf.append(rb.getString("java.on")+" " + local_date + " " + rb.getString("java.at")+ " " + local_time + " ");
buf.append(rb.getString("java.for")+" " + term_name + ", ");
int nbr_sections = notifySites.size();
if (nbr_sections >1)
{
buf.append(rb.getString("java.withrost")+" " + Integer.toString(nbr_sections) + " "+rb.getString("java.sections")+"\n\n");
}
else
{
buf.append(" "+rb.getString("java.withrost2")+"\n\n");
}
for (int i = 0; i < nbr_sections; i++)
{
String course = (String) notifySites.get(i);
buf.append(rb.getString("java.course2")+" " + course + "\n");
}
String content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo, replyTo, null);
} // if
} // sendSiteNotification
/**
* doCancel called when "eventSubmit_doCancel_create" is in the request parameters to c
*/
public void doCancel_create ( RunData data )
{
// Don't put current form data in state, just return to the previous template
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
removeAddClassContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} // doCancel_create
/**
* doCancel called when "eventSubmit_doCancel" is in the request parameters to c
* int index = Integer.valueOf(params.getString ("template-index")).intValue();
*/
public void doCancel ( RunData data )
{
// Don't put current form data in state, just return to the previous template
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
state.removeAttribute(STATE_MESSAGE);
String currentIndex = (String)state.getAttribute(STATE_TEMPLATE_INDEX);
String backIndex = params.getString("back");
state.setAttribute(STATE_TEMPLATE_INDEX, backIndex);
if (currentIndex.equals("4"))
{
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
state.removeAttribute(STATE_MESSAGE);
removeEditToolState(state);
}
else if (currentIndex.equals("5"))
{
//remove related state variables
removeAddParticipantContext(state);
params = data.getParameters ();
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("back"));
}
else if (currentIndex.equals("6"))
{
state.removeAttribute(STATE_REMOVEABLE_USER_LIST);
}
else if (currentIndex.equals("9"))
{
state.removeAttribute(FORM_WILL_NOTIFY);
}
else if (currentIndex.equals("17") || currentIndex.equals("16"))
{
state.removeAttribute(FORM_WILL_NOTIFY);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
else if (currentIndex.equals("13") || currentIndex.equals("14"))
{
// clean state attributes
state.removeAttribute(FORM_SITEINFO_TITLE);
state.removeAttribute(FORM_SITEINFO_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SKIN);
state.removeAttribute(FORM_SITEINFO_INCLUDE);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
else if (currentIndex.equals("15"))
{
params = data.getParameters ();
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("cancelIndex"));
removeEditToolState(state);
}
//htripath: added 'currentIndex.equals("45")' for import from file cancel
else if (currentIndex.equals("19") || currentIndex.equals("20") || currentIndex.equals("21") || currentIndex.equals("22")|| currentIndex.equals("45"))
{
// from adding participant pages
//remove related state variables
removeAddParticipantContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
else if (currentIndex.equals("23") || currentIndex.equals("24"))
{
// from change global access
state.removeAttribute("form_joinable");
state.removeAttribute("form_joinerRole");
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
else if (currentIndex.equals("7") || currentIndex.equals("25"))
{
//from change role
removeChangeRoleContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
else if (currentIndex.equals("3"))
{
//from adding class
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
}
else if (currentIndex.equals("27") || currentIndex.equals("28"))
{
// from import
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
// worksite setup
if (getStateSite(state) == null)
{
//in creating new site process
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
else
{
// in editing site process
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
// site info
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
}
else if (currentIndex.equals("26"))
{
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP)
&& getStateSite(state) == null)
{
//from creating site
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
else
{
//from revising site
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
removeEditToolState(state);
}
else if (currentIndex.equals("37") || currentIndex.equals("44"))
{
// cancel back to edit class view
state.setAttribute(STATE_TEMPLATE_INDEX, "43");
removeAddClassContext(state);
}
} // doCancel
/**
* doMenu_customize is called when "eventSubmit_doBack" is in the request parameters
* Pass parameter to actionForTemplate to request action for backward direction
*/
public void doMenu_customize ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute(STATE_TEMPLATE_INDEX, "15");
}// doMenu_customize
/**
* doBack_to_list cancels an outstanding site edit, cleans state and returns to the site list
*
*/
public void doBack_to_list ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Site site = getStateSite(state);
if (site != null)
{
Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO);
h.put(site.getId(), state.getAttribute(STATE_PAGESIZE));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
}
//restore the page size for Worksite setup tool
if (state.getAttribute(STATE_PAGESIZE_SITESETUP) != null)
{
state.setAttribute(STATE_PAGESIZE, state.getAttribute(STATE_PAGESIZE_SITESETUP));
state.removeAttribute(STATE_PAGESIZE_SITESETUP);
}
cleanState(state);
setupFormNamesAndConstants(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} // doBack_to_list
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doAdd_custom_link ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
if ((params.getString("name")) == null || (params.getString("url") == null))
{
Tool tr = ToolManager.getTool("sakai.iframe");
Site site = getStateSite(state);
SitePage page = site.addPage();
page.setTitle(params.getString("name")); // the visible label on the tool menu
ToolConfiguration tool = page.addTool();
tool.setTool("sakai.iframe", tr);
tool.setTitle(params.getString("name"));
commitSite(site);
}
else
{
addAlert(state, rb.getString("java.reqmiss"));
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("template-index"));
}
} // doAdd_custom_link
/**
* doAdd_remove_features is called when Make These Changes is clicked in chef_site-addRemoveFeatures
*/
public void doAdd_remove_features ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
List existTools = (List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
ParameterParser params = data.getParameters ();
String option = params.getString("option");
// dispatch
if (option.equalsIgnoreCase("addNews"))
{
updateSelectedToolList(state, params, false);
insertTool(state, "sakai.news", STATE_NEWS_TITLES, NEWS_DEFAULT_TITLE, STATE_NEWS_URLS, NEWS_DEFAULT_URL, Integer.parseInt(params.getString("newsNum")));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
else if (option.equalsIgnoreCase("addWC"))
{
updateSelectedToolList(state, params, false);
insertTool(state, "sakai.iframe", STATE_WEB_CONTENT_TITLES, WEB_CONTENT_DEFAULT_TITLE, STATE_WEB_CONTENT_URLS, WEB_CONTENT_DEFAULT_URL, Integer.parseInt(params.getString("wcNum")));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
else if (option.equalsIgnoreCase("save"))
{
List idsSelected = new Vector();
boolean goToENWPage = false;
boolean homeSelected = false;
// Add new pages and tools, if any
if (params.getStrings ("selectedTools") == null)
{
addAlert(state, rb.getString("atleastonetool"));
}
else
{
List l = new ArrayList(Arrays.asList(params.getStrings ("selectedTools"))); // toolId's & titles of chosen tools
for (int i = 0; i < l.size(); i++)
{
String toolId = (String) l.get(i);
if (toolId.equals(HOME_TOOL_ID))
{
homeSelected = true;
}
else if (toolId.equals("sakai.mailbox") || toolId.indexOf("sakai.news") != -1 || toolId.indexOf("sakai.iframe") != -1)
{
// if user is adding either EmailArchive tool, News tool or Web Content tool, go to the Customize page for the tool
if (!existTools.contains(toolId))
{
goToENWPage = true;
}
if (toolId.equals("sakai.mailbox"))
{
//get the email alias when an Email Archive tool has been selected
String channelReference = mailArchiveChannelReference((String) state.getAttribute(STATE_SITE_INSTANCE_ID));
List aliases = AliasService.getAliases(channelReference, 1, 1);
if (aliases.size() > 0)
{
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases.get(0)).getId());
}
}
}
idsSelected.add(toolId);
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(homeSelected));
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List of ToolRegistration toolId's
if (state.getAttribute(STATE_MESSAGE)== null)
{
if (goToENWPage)
{
// go to the configuration page for Email Archive, News and Web Content tools
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
else
{
// go to confirmation page
state.setAttribute(STATE_TEMPLATE_INDEX, "15");
}
}
}
else if (option.equalsIgnoreCase("continue"))
{
// continue
doContinue(data);
}
else if (option.equalsIgnoreCase("Back"))
{
//back
doBack(data);
}
else if (option.equalsIgnoreCase("Cancel"))
{
//cancel
doCancel(data);
}
} // doAdd_remove_features
/**
* doSave_revised_features
*/
public void doSave_revised_features ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
getRevisedFeatures(params, state);
Site site = getStateSite(state);
String id = site.getId();
//now that the site exists, we can set the email alias when an Email Archive tool has been selected
String alias = StringUtil.trimToNull((String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
if (alias != null)
{
String channelReference = mailArchiveChannelReference(id);
try
{
AliasService.setAlias(alias, channelReference);
}
catch (IdUsedException ee)
{
}
catch (IdInvalidException ee)
{
addAlert(state, rb.getString("java.alias")+" " + alias + " "+rb.getString("java.isinval"));
}
catch (PermissionException ee)
{
addAlert(state, rb.getString("java.addalias")+" ");
}
}
if (state.getAttribute(STATE_MESSAGE)== null)
{
// clean state variables
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_NEWS_TITLES);
state.removeAttribute(STATE_NEWS_URLS);
state.removeAttribute(STATE_WEB_CONTENT_TITLES);
state.removeAttribute(STATE_WEB_CONTENT_URLS);
state.setAttribute(STATE_SITE_INSTANCE_ID, id);
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString ("continue"));
}
// refresh the whole page
scheduleTopRefresh();
} // doSave_revised_features
/**
* doMenu_add_participant
*/
public void doMenu_add_participant ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.setAttribute (STATE_TEMPLATE_INDEX, "5");
} // doMenu_add_participant
/**
* doMenu_siteInfo_addParticipant
*/
public void doMenu_siteInfo_addParticipant ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.removeAttribute(STATE_SELECTED_USER_LIST);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_TEMPLATE_INDEX, "5");
}
} // doMenu_siteInfo_addParticipant
/**
* doMenu_siteInfo_removeParticipant
*/
public void doMenu_siteInfo_removeParticipant( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
if (params.getStrings ("selectedUser") == null)
{
addAlert(state, rb.getString("java.nousers"));
}
else
{
List removeUser = Arrays.asList(params.getStrings ("selectedUser"));
// all or some selected user(s) can be removed, go to confirmation page
if (removeUser.size() > 0)
{
state.setAttribute (STATE_TEMPLATE_INDEX, "6");
}
else
{
addAlert(state, rb.getString("java.however"));
}
state.setAttribute (STATE_REMOVEABLE_USER_LIST, removeUser);
}
} // doMenu_siteInfo_removeParticipant
/**
* doMenu_siteInfo_changeRole
*/
public void doMenu_siteInfo_changeRole ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
if (params.getStrings ("selectedUser") == null)
{
state.removeAttribute(STATE_SELECTED_USER_LIST);
addAlert(state, rb.getString("java.nousers2"));
}
else
{
state.setAttribute (STATE_CHANGEROLE_SAMEROLE, Boolean.TRUE);
List selectedUserIds = Arrays.asList(params.getStrings ("selectedUser"));
state.setAttribute (STATE_SELECTED_USER_LIST, selectedUserIds);
// get roles for selected participants
setSelectedParticipantRoles(state);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_TEMPLATE_INDEX, "7");
}
}
} // doMenu_siteInfo_changeRole
/**
* doMenu_siteInfo_globalAccess
*/
public void doMenu_siteInfo_globalAccess(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "23");
}
} //doMenu_siteInfo_globalAccess
/**
* doMenu_siteInfo_cancel_access
*/
public void doMenu_siteInfo_cancel_access( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} // doMenu_siteInfo_cancel_access
/**
* doMenu_siteInfo_import
*/
public void doMenu_siteInfo_import ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_TEMPLATE_INDEX, "28");
}
} // doMenu_siteInfo_import
/**
* doMenu_siteInfo_editClass
*/
public void doMenu_siteInfo_editClass( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute (STATE_TEMPLATE_INDEX, "43");
} // doMenu_siteInfo_editClass
/**
* doMenu_siteInfo_addClass
*/
public void doMenu_siteInfo_addClass( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Site site = getStateSite(state);
state.setAttribute(STATE_TERM_SELECTED, CourseManagementService.getTerm(site.getProperties().getProperty(PROP_SITE_TERM)));
state.setAttribute (STATE_TEMPLATE_INDEX, "36");
} // doMenu_siteInfo_addClass
/**
* first step of adding class
*/
public void doAdd_class_select( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String option = params.getString("option");
if (option.equalsIgnoreCase("change"))
{
// change term
String termId = params.getString("selectTerm");
Term t = CourseManagementService.getTerm(termId);
state.setAttribute(STATE_TERM_SELECTED, t);
}
else if (option.equalsIgnoreCase("cancel"))
{
// cancel
state.removeAttribute(STATE_TERM_SELECTED);
removeAddClassContext(state);
state.setAttribute (STATE_TEMPLATE_INDEX, "43");
}
else if (option.equalsIgnoreCase("add"))
{
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
Term t = (Term) state.getAttribute(STATE_TERM_SELECTED);
if (t != null)
{
List courses = CourseManagementService.getInstructorCourses(userId, t.getYear(), t.getTerm());
// future term? roster information is not available yet?
int weeks = 0;
try
{
weeks = Integer.parseInt(ServerConfigurationService.getString("roster.available.weeks.before.term.start", "0"));
}
catch (Exception ignore)
{
}
if ((courses == null || courses != null && courses.size() == 0)
&& System.currentTimeMillis() + weeks*7*24*60*60*1000 < t.getStartTime().getTime())
{
//if a future term is selected
state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.TRUE);
}
else
{
state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.FALSE);
}
}
// continue
doContinue(data);
}
} // doAdd_class_select
/**
* doMenu_siteInfo_duplicate
*/
public void doMenu_siteInfo_duplicate ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_TEMPLATE_INDEX, "29");
}
} // doMenu_siteInfo_import
/**
* doMenu_change_roles
*/
public void doMenu_change_roles ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
if (params.getStrings ("removeUser") != null)
{
state.setAttribute(STATE_SELECTED_USER_LIST, new ArrayList(Arrays.asList(params.getStrings ("removeUser"))));
state.setAttribute (STATE_TEMPLATE_INDEX, "7");
}
else
{
addAlert(state, rb.getString("java.nousers2"));
}
} // doMenu_change_roles
/**
* doMenu_edit_site_info
*
*/
public void doMenu_edit_site_info ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Site Site = getStateSite(state);
ResourceProperties siteProperties = Site.getProperties();
state.setAttribute(FORM_SITEINFO_TITLE, Site.getTitle());
String site_type = (String)state.getAttribute(STATE_SITE_TYPE);
if(site_type != null && !site_type.equalsIgnoreCase("myworkspace"))
{
state.setAttribute(FORM_SITEINFO_INCLUDE, Boolean.valueOf(Site.isPubView()).toString());
}
state.setAttribute(FORM_SITEINFO_DESCRIPTION, Site.getDescription());
state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION, Site.getShortDescription());
state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl());
if (Site.getIconUrl() != null)
{
state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl());
}
// site contact information
String contactName = siteProperties.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null)
{
String creatorId = siteProperties.getProperty(ResourceProperties.PROP_CREATOR);
try
{
User u = UserDirectoryService.getUser(creatorId);
String email = u.getEmail();
if (email != null)
{
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
catch (UserNotDefinedException e)
{
}
}
if (contactName != null)
{
state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName);
}
if (contactEmail != null)
{
state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, contactEmail);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
}
} // doMenu_edit_site_info
/**
* doMenu_edit_site_tools
*
*/
public void doMenu_edit_site_tools ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "4");
}
} // doMenu_edit_site_tools
/**
* doMenu_edit_site_access
*
*/
public void doMenu_edit_site_access ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} // doMenu_edit_site_access
/**
* doMenu_publish_site
*
*/
public void doMenu_publish_site ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the site properties
sitePropertiesIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "9");
}
} // doMenu_publish_site
/**
* Back to worksite setup's list view
*
*/
public void doBack_to_site_list ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_SITE_TYPE);
state.removeAttribute(STATE_SITE_INSTANCE_ID);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} // doBack_to_site_list
/**
* doSave_site_info
*
*/
public void doSave_siteInfo ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Site Site = getStateSite(state);
ResourcePropertiesEdit siteProperties = Site.getPropertiesEdit();
String site_type = (String)state.getAttribute(STATE_SITE_TYPE);
List titleEditableSiteType = (List) state.getAttribute(TITLE_EDITABLE_SITE_TYPE);
if (titleEditableSiteType.contains(Site.getType()))
{
Site.setTitle((String) state.getAttribute(FORM_SITEINFO_TITLE));
}
Site.setDescription((String) state.getAttribute(FORM_SITEINFO_DESCRIPTION));
Site.setShortDescription((String) state.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
if(site_type != null)
{
if (site_type.equals("course"))
{
//set icon url for course
String skin = (String) state.getAttribute(FORM_SITEINFO_SKIN);
setAppearance(state, Site, skin);
}
else
{
//set icon url for others
String iconUrl = (String) state.getAttribute(FORM_SITEINFO_ICON_URL);
Site.setIconUrl(iconUrl);
}
}
// site contact information
String contactName = (String) state.getAttribute(FORM_SITEINFO_CONTACT_NAME);
if (contactName != null)
{
siteProperties.addProperty(PROP_SITE_CONTACT_NAME, contactName);
}
String contactEmail = (String) state.getAttribute(FORM_SITEINFO_CONTACT_EMAIL);
if (contactEmail != null)
{
siteProperties.addProperty(PROP_SITE_CONTACT_EMAIL, contactEmail);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
try
{
SiteService.save(Site);
}
catch (IdUnusedException e)
{
// TODO:
}
catch (PermissionException e)
{
// TODO:
}
// clean state attributes
state.removeAttribute(FORM_SITEINFO_TITLE);
state.removeAttribute(FORM_SITEINFO_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SKIN);
state.removeAttribute(FORM_SITEINFO_INCLUDE);
state.removeAttribute(FORM_SITEINFO_CONTACT_NAME);
state.removeAttribute(FORM_SITEINFO_CONTACT_EMAIL);
// back to site info view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
//refresh the whole page
scheduleTopRefresh();
}
} // doSave_siteInfo
/**
* init
*
*/
private void init (VelocityPortlet portlet, RunData data, SessionState state)
{
state.setAttribute(STATE_ACTION, "SiteAction");
setupFormNamesAndConstants(state);
if (state.getAttribute(STATE_PAGESIZE_SITEINFO) == null)
{
state.setAttribute(STATE_PAGESIZE_SITEINFO, new Hashtable());
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
String siteId = ToolManager.getCurrentPlacement().getContext();
getReviseSite(state, siteId);
Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO);
if (!h.containsKey(siteId))
{
// update
h.put(siteId, new Integer(200));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
state.setAttribute(STATE_PAGESIZE, new Integer(200));
}
}
if (state.getAttribute(STATE_SITE_TYPES) == null)
{
PortletConfig config = portlet.getPortletConfig();
// all site types
String t = StringUtil.trimToNull(config.getInitParameter("siteTypes"));
if (t != null)
{
state.setAttribute(STATE_SITE_TYPES, new ArrayList(Arrays.asList(t.split(","))));
}
else
{
state.setAttribute(STATE_SITE_TYPES, new Vector());
}
}
} // init
public void doNavigate_to_site ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String siteId = StringUtil.trimToNull(data.getParameters().getString("option"));
if (siteId != null)
{
getReviseSite(state, siteId);
}
else
{
doBack_to_list(data);
}
} // doNavigate_to_site
/**
* Get site information for revise screen
*/
private void getReviseSite(SessionState state, String siteId)
{
if (state.getAttribute(STATE_SELECTED_USER_LIST) == null)
{
state.setAttribute(STATE_SELECTED_USER_LIST, new Vector());
}
List sites = (List) state.getAttribute(STATE_SITES);
try
{
Site site = SiteService.getSite(siteId);
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
if (sites != null)
{
int pos = -1;
for (int index=0;index<sites.size() && pos==-1;index++)
{
if (((Site) sites.get(index)).getId().equals(siteId))
{
pos = index;
}
}
// has any previous site in the list?
if (pos > 0)
{
state.setAttribute(STATE_PREV_SITE, sites.get(pos-1));
}
else
{
state.removeAttribute(STATE_PREV_SITE);
}
//has any next site in the list?
if (pos < sites.size()-1)
{
state.setAttribute(STATE_NEXT_SITE,sites.get(pos+1));
}
else
{
state.removeAttribute(STATE_NEXT_SITE);
}
}
String type = site.getType();
if (type == null)
{
if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null)
{
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
}
state.setAttribute(STATE_SITE_TYPE, type);
}
catch (IdUnusedException e)
{
M_log.warn(this + e.toString());
}
//one site has been selected
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} // getReviseSite
/**
* doUpdate_participant
*
*/
public void doUpdate_participant(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
Site s = getStateSite(state);
String realmId = SiteService.siteReference(s.getId());
if (AuthzGroupService.allowUpdate(realmId) || SiteService.allowUpdateSiteMembership(s.getId()))
{
try
{
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId);
// does the site has maintain type user(s) before updating participants?
String maintainRoleString = realmEdit.getMaintainRole();
boolean hadMaintainUser = realmEdit.getUsersHasRole(maintainRoleString).isEmpty();
// update participant roles
List participants = (List) state.getAttribute(STATE_PARTICIPANT_LIST);;
// remove all roles and then add back those that were checked
for (int i=0; i<participants.size(); i++)
{
String id = null;
// added participant
Participant participant = (Participant) participants.get(i);
id = participant.getUniqname();
if (id != null)
{
//get the newly assigned role
String inputRoleField = "role" + id;
String roleId = params.getString(inputRoleField);
// only change roles when they are different than before
if (roleId!= null)
{
// get the grant active status
boolean activeGrant = true;
String activeGrantField = "activeGrant" + id;
if (params.getString(activeGrantField) != null)
{
activeGrant = params.getString(activeGrantField).equalsIgnoreCase("true")?true:false;
}
boolean fromProvider = !participant.isRemoveable();
if(fromProvider && !roleId.equals(participant.getProviderRole()))
{
fromProvider=false;
}
realmEdit.addMember(id, roleId, activeGrant, fromProvider);
}
}
}
//remove selected users
if (params.getStrings ("selectedUser") != null)
{
List removals = new ArrayList(Arrays.asList(params.getStrings ("selectedUser")));
state.setAttribute(STATE_SELECTED_USER_LIST, removals);
for(int i = 0; i<removals.size(); i++)
{
String rId = (String) removals.get(i);
try
{
User user = UserDirectoryService.getUser(rId);
Participant selected = new Participant();
selected.name = user.getDisplayName();
selected.uniqname = user.getId();
realmEdit.removeMember(user.getId());
}
catch (UserNotDefinedException e)
{
M_log.warn(this + " IdUnusedException " + rId + ". ");
}
}
}
if (hadMaintainUser && realmEdit.getUsersHasRole(maintainRoleString).isEmpty())
{
// if after update, the "had maintain type user" status changed, show alert message and don't save the update
addAlert(state, rb.getString("sitegen.siteinfolist.nomaintainuser") + maintainRoleString + ".");
}
else
{
AuthzGroupService.save(realmEdit);
}
}
catch (GroupNotDefinedException e)
{
addAlert(state, rb.getString("java.problem2"));
M_log.warn(this + " IdUnusedException " + s.getTitle() + "(" + realmId + "). ");
}
catch(AuthzPermissionException e)
{
addAlert(state, rb.getString("java.changeroles"));
M_log.warn(this + " PermissionException " + s.getTitle() + "(" + realmId + "). ");
}
}
} // doUpdate_participant
/**
* doUpdate_site_access
*
*/
public void doUpdate_site_access(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Site sEdit = getStateSite(state);
ParameterParser params = data.getParameters ();
String publishUnpublish = params.getString("publishunpublish");
String include = params.getString("include");
String joinable = params.getString("joinable");
if (sEdit != null)
{
// editing existing site
//publish site or not
if (publishUnpublish != null&& publishUnpublish.equalsIgnoreCase("publish"))
{
sEdit.setPublished(true);
}
else
{
sEdit.setPublished(false);
}
//site public choice
if (include != null)
{
// if there is pubview input, use it
sEdit.setPubView(include.equalsIgnoreCase("true")?true:false);
}
else if (state.getAttribute(STATE_SITE_TYPE) != null)
{
String type = (String) state.getAttribute(STATE_SITE_TYPE);
List publicSiteTypes = (List) state.getAttribute(STATE_PUBLIC_SITE_TYPES);
List privateSiteTypes = (List) state.getAttribute(STATE_PRIVATE_SITE_TYPES);
if (publicSiteTypes.contains(type))
{
//sites are always public
sEdit.setPubView(true);
}
else if (privateSiteTypes.contains(type))
{
//site are always private
sEdit.setPubView(false);
}
}
else
{
sEdit.setPubView(false);
}
//publish site or not
if (joinable != null && joinable.equalsIgnoreCase("true"))
{
state.setAttribute(STATE_JOINABLE, Boolean.TRUE);
sEdit.setJoinable(true);
String joinerRole = StringUtil.trimToNull(params.getString("joinerRole"));
if (joinerRole!= null)
{
state.setAttribute(STATE_JOINERROLE, joinerRole);
sEdit.setJoinerRole(joinerRole);
}
else
{
state.setAttribute(STATE_JOINERROLE, "");
addAlert(state, rb.getString("java.joinsite")+" ");
}
}
else
{
state.setAttribute(STATE_JOINABLE, Boolean.FALSE);
state.removeAttribute(STATE_JOINERROLE);
sEdit.setJoinable(false);
sEdit.setJoinerRole(null);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
commitSite(sEdit);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
// TODO: hard coding this frame id is fragile, portal dependent, and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
state.removeAttribute(STATE_JOINABLE);
state.removeAttribute(STATE_JOINERROLE);
}
}
else
{
// adding new site
if(state.getAttribute(STATE_SITE_INFO) != null)
{
SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (publishUnpublish != null&& publishUnpublish.equalsIgnoreCase("publish"))
{
siteInfo.published = true;
}
else
{
siteInfo.published = false;
}
//site public choice
if (include != null)
{
siteInfo.include = include.equalsIgnoreCase("true")?true:false;
}
else if (StringUtil.trimToNull(siteInfo.site_type) != null)
{
String type = StringUtil.trimToNull(siteInfo.site_type);
List publicSiteTypes = (List) state.getAttribute(STATE_PUBLIC_SITE_TYPES);
List privateSiteTypes = (List) state.getAttribute(STATE_PRIVATE_SITE_TYPES);
if (publicSiteTypes.contains(type))
{
//sites are always public
siteInfo.include = true;
}
else if (privateSiteTypes.contains(type))
{
//site are always private
siteInfo.include = false;
}
}
else
{
siteInfo.include = false;
}
//joinable site or not
if (joinable != null && joinable.equalsIgnoreCase("true"))
{
siteInfo.joinable = true;
String joinerRole = StringUtil.trimToNull(params.getString("joinerRole"));
if (joinerRole!= null)
{
siteInfo.joinerRole = joinerRole;
}
else
{
addAlert(state, rb.getString("java.joinsite")+" ");
}
}
else
{
siteInfo.joinable = false;
siteInfo.joinerRole = null;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "10");
updateCurrentStep(state, true);
}
}
// if editing an existing site, refresh the whole page so that the publish/unpublish icon could be updated
if (sEdit != null)
{
scheduleTopRefresh();
}
} // doUpdate_site_access
/**
* remove related state variable for changing participants roles
* @param state SessionState object
*/
private void removeChangeRoleContext(SessionState state)
{
// remove related state variables
state.removeAttribute(STATE_CHANGEROLE_SAMEROLE);
state.removeAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE);
state.removeAttribute(STATE_ADD_PARTICIPANTS);
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
} // removeChangeRoleContext
/**
/* Actions for vm templates under the "chef_site" root. This method is called by doContinue.
* Each template has a hidden field with the value of template-index that becomes the value of
* index for the switch statement here. Some cases not implemented.
*/
private void actionForTemplate ( String direction, int index, ParameterParser params, SessionState state)
{
// Continue - make any permanent changes, Back - keep any data entered on the form
boolean forward = direction.equals("continue") ? true : false;
SiteInfo siteInfo = new SiteInfo();
switch (index)
{
case 0:
/* actionForTemplate chef_site-list.vm
*
*/
break;
case 1:
/* actionForTemplate chef_site-type.vm
*
*/
break;
case 2:
/* actionForTemplate chef_site-newSiteInformation.vm
*
*/
if(state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
//defaults to be true
siteInfo.include=true;
state.setAttribute(STATE_SITE_INFO, siteInfo);
updateSiteInfo(params, state);
// alerts after clicking Continue but not Back
if(forward)
{
if (StringUtil.trimToNull(siteInfo.title) == null)
{
addAlert(state, rb.getString("java.reqfields"));
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
return;
}
}
updateSiteAttributes(state);
if (state.getAttribute(STATE_MESSAGE) == null)
{
updateCurrentStep(state, forward);
}
break;
case 3:
/* actionForTemplate chef_site-newSiteFeatures.vm
*
*/
if (forward)
{
getFeatures(params, state);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
updateCurrentStep(state, forward);
}
break;
case 4:
/* actionForTemplate chef_site-addRemoveFeature.vm
*
*/
break;
case 5:
/* actionForTemplate chef_site-addParticipant.vm
*
*/
if(forward)
{
checkAddParticipant(params, state);
}
else
{
// remove related state variables
removeAddParticipantContext(state);
}
break;
case 6:
/* actionForTemplate chef_site-removeParticipants.vm
*
*/
break;
case 7:
/* actionForTemplate chef_site-changeRoles.vm
*
*/
if (forward)
{
if (!((Boolean) state.getAttribute(STATE_CHANGEROLE_SAMEROLE)).booleanValue())
{
getSelectedRoles(state, params, STATE_SELECTED_USER_LIST);
}
else
{
String role = params.getString("role_to_all");
if (role == null)
{
addAlert(state, rb.getString("java.pleasechoose")+" ");
}
else
{
state.setAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE, role);
}
}
}
else
{
removeChangeRoleContext(state);
}
break;
case 8:
/* actionForTemplate chef_site-siteDeleteConfirm.vm
*
*/
break;
case 9:
/* actionForTemplate chef_site-publishUnpublish.vm
*
*/
updateSiteInfo(params, state);
break;
case 10:
/* actionForTemplate chef_site-newSiteConfirm.vm
*
*/
if (!forward)
{
if (state.getAttribute(STATE_MESSAGE) == null)
{
updateCurrentStep(state, false);
}
}
break;
case 11:
/* actionForTemplate chef_site_newsitePublishUnpublish.vm
*
*/
break;
case 12:
/* actionForTemplate chef_site_siteInfo-list.vm
*
*/
break;
case 13:
/* actionForTemplate chef_site_siteInfo-editInfo.vm
*
*/
if (forward)
{
Site Site = getStateSite(state);
List titleEditableSiteType = (List) state.getAttribute(TITLE_EDITABLE_SITE_TYPE);
if (titleEditableSiteType.contains(Site.getType()))
{
// site titel is editable and could not be null
String title = StringUtil.trimToNull(params.getString("title"));
state.setAttribute(FORM_SITEINFO_TITLE, title);
if (title == null)
{
addAlert(state, rb.getString("java.specify")+" ");
}
}
String description = StringUtil.trimToNull(params.getString("description"));
state.setAttribute(FORM_SITEINFO_DESCRIPTION, description);
String short_description = StringUtil.trimToNull(params.getString("short_description"));
state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION, short_description);
String skin = params.getString("skin");
if (skin != null)
{
// if there is a skin input for course site
skin = StringUtil.trimToNull(skin);
state.setAttribute(FORM_SITEINFO_SKIN, skin);
}
else
{
// if ther is a icon input for non-course site
String icon = StringUtil.trimToNull(params.getString("icon"));
if (icon != null)
{
if (icon.endsWith(PROTOCOL_STRING))
{
addAlert(state, rb.getString("alert.protocol"));
}
state.setAttribute(FORM_SITEINFO_ICON_URL, icon);
}
else
{
state.removeAttribute(FORM_SITEINFO_ICON_URL);
}
}
// site contact information
String contactName = StringUtil.trimToZero(params.getString ("siteContactName"));
state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName);
String email = StringUtil.trimToZero(params.getString ("siteContactEmail"));
String[] parts = email.split("@");
if(email.length() > 0 && (email.indexOf("@") == -1 || parts.length != 2 || parts[0].length() == 0 || !Validator.checkEmailLocal(parts[0])))
{
// invalid email
addAlert(state, email + " "+rb.getString("java.invalid") + rb.getString("java.theemail"));
}
state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, email);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "14");
}
}
break;
case 14:
/* actionForTemplate chef_site_siteInfo-editInfoConfirm.vm
*
*/
break;
case 15:
/* actionForTemplate chef_site_siteInfo-addRemoveFeatureConfirm.vm
*
*/
break;
case 16:
/* actionForTemplate chef_site_siteInfo-publishUnpublish-sendEmail.vm
*
*/
if (forward)
{
String notify = params.getString("notify");
if (notify != null)
{
state.setAttribute(FORM_WILL_NOTIFY, new Boolean(notify));
}
}
break;
case 17:
/* actionForTemplate chef_site_siteInfo--publishUnpublish-confirm.vm
*
*/
if (forward)
{
boolean oldStatus = getStateSite(state).isPublished();
boolean newStatus = ((SiteInfo) state.getAttribute(STATE_SITE_INFO)).getPublished();
saveSiteStatus(state, newStatus);
if (oldStatus == false || newStatus == true)
{
// if site's status been changed from unpublish to publish and notification is selected, send out notification to participants.
if (((Boolean) state.getAttribute(FORM_WILL_NOTIFY)).booleanValue())
{
// %%% place holder for sending email
}
}
// commit site edit
Site site = getStateSite(state);
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
// TODO:
}
catch (PermissionException e)
{
// TODO:
}
// TODO: hard coding this frame id is fragile, portal dependent, and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
}
break;
case 18:
/* actionForTemplate chef_siteInfo-editAccess.vm
*
*/
if (!forward)
{
if (state.getAttribute(STATE_MESSAGE) == null)
{
updateCurrentStep(state, false);
}
}
case 19:
/* actionForTemplate chef_site-addParticipant-sameRole.vm
*
*/
String roleId = StringUtil.trimToNull(params.getString("selectRole"));
if (roleId == null && forward)
{
addAlert(state, rb.getString("java.pleasesel")+" ");
}
else
{
state.setAttribute("form_selectedRole", params.getString("selectRole"));
}
break;
case 20:
/* actionForTemplate chef_site-addParticipant-differentRole.vm
*
*/
if (forward)
{
getSelectedRoles(state, params, STATE_ADD_PARTICIPANTS);
}
break;
case 21:
/* actionForTemplate chef_site-addParticipant-notification.vm
*
' */
if (params.getString("notify") == null)
{
if (forward)
addAlert(state, rb.getString("java.pleasechoice")+" ");
}
else
{
state.setAttribute("form_selectedNotify", new Boolean(params.getString("notify")));
}
break;
case 22:
/* actionForTemplate chef_site-addParticipant-confirm.vm
*
*/
break;
case 23:
/* actionForTemplate chef_siteInfo-editAccess-globalAccess.vm
*
*/
if (forward)
{
String joinable = params.getString("joinable");
state.setAttribute("form_joinable", Boolean.valueOf(joinable));
String joinerRole = params.getString("joinerRole");
state.setAttribute("form_joinerRole", joinerRole);
if (joinable.equals("true"))
{
if (joinerRole == null)
{
addAlert(state, rb.getString("java.pleasesel")+" ");
}
}
}
else
{
}
break;
case 24:
/* actionForTemplate chef_site-siteInfo-editAccess-globalAccess-confirm.vm
*
*/
break;
case 25:
/* actionForTemplate chef_site-changeRoles-confirm.vm
*
*/
break;
case 26:
/* actionForTemplate chef_site-modifyENW.vm
*
*/
updateSelectedToolList(state, params, forward);
if (state.getAttribute(STATE_MESSAGE) == null)
{
updateCurrentStep(state, forward);
}
break;
case 27:
/* actionForTemplate chef_site-importSites.vm
*
*/
if (forward)
{
Site existingSite = getStateSite(state);
if (existingSite != null)
{
// revising a existing site's tool
if (select_import_tools(params, state))
{
Hashtable importTools = (Hashtable) state.getAttribute(STATE_IMPORT_SITE_TOOL);
List selectedTools = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
importToolIntoSite(selectedTools, importTools, existingSite);
existingSite = getStateSite(state); // refresh site for WC and News
if (state.getAttribute(STATE_MESSAGE) == null)
{
commitSite(existingSite);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
}
}
else
{
// show alert and remain in current page
addAlert(state, rb.getString("java.toimporttool"));
}
}
else
{
// new site
select_import_tools(params, state);
}
}
else
{
// read form input about import tools
select_import_tools(params, state);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
updateCurrentStep(state, forward);
}
break;
case 28:
/* actionForTemplate chef_siteinfo-import.vm
*
*/
if (forward)
{
if (params.getStrings("importSites") == null)
{
addAlert(state, rb.getString("java.toimport")+" ");
state.removeAttribute(STATE_IMPORT_SITES);
}
else
{
List importSites = new ArrayList(Arrays.asList(params.getStrings("importSites")));
Hashtable sites = new Hashtable();
for (index = 0; index < importSites.size(); index ++)
{
try
{
Site s = SiteService.getSite((String) importSites.get(index));
sites.put(s, new Vector());
}
catch (IdUnusedException e)
{
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
}
break;
case 29:
/* actionForTemplate chef_siteinfo-duplicate.vm
*
*/
if (forward)
{
if (state.getAttribute(SITE_DUPLICATED) == null)
{
if (StringUtil.trimToNull(params.getString("title")) == null)
{
addAlert(state, rb.getString("java.dupli")+" ");
}
else
{
String title = params.getString("title");
state.setAttribute(SITE_DUPLICATED_NAME, title);
try
{
String oSiteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
String nSiteId = IdManager.createUuid();
Site site = SiteService.addSite(nSiteId, getStateSite(state));
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
// TODO:
}
catch (PermissionException e)
{
// TODO:
}
try
{
site = SiteService.getSite(nSiteId);
// set title
site.setTitle(title);
// import tool content
List pageList = site.getPages();
if (!((pageList == null) || (pageList.size() == 0)))
{
for (ListIterator i = pageList.listIterator(); i.hasNext(); )
{
SitePage page = (SitePage) i.next();
List pageToolList = page.getTools();
String toolId = ((ToolConfiguration)pageToolList.get(0)).getTool().getId();
if (toolId.equalsIgnoreCase("sakai.resources"))
{
// handle resource tool specially
transferCopyEntities(toolId, ContentHostingService.getSiteCollection(oSiteId), ContentHostingService.getSiteCollection(nSiteId));
}
else
{
// other tools
transferCopyEntities(toolId, oSiteId, nSiteId);
}
}
}
}
catch (Exception e1)
{
//if goes here, IdService or SiteService has done something wrong.
M_log.warn(this + "Exception" + e1 + ":"+ nSiteId + "when duplicating site");
}
if (site.getType().equals("course"))
{
// for course site, need to read in the input for term information
String termId = StringUtil.trimToNull(params.getString("selectTerm"));
if (termId != null)
{
site.getPropertiesEdit().addProperty(PROP_SITE_TERM, termId);
}
}
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
// TODO:
}
catch (PermissionException e)
{
// TODO:
}
// TODO: hard coding this frame id is fragile, portal dependent, and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
state.setAttribute(SITE_DUPLICATED, Boolean.TRUE);
}
catch (IdInvalidException e)
{
addAlert(state, rb.getString("java.siteinval"));
}
catch (IdUsedException e)
{
addAlert(state, rb.getString("java.sitebeenused")+" ");
}
catch (PermissionException e)
{
addAlert(state, rb.getString("java.allowcreate")+" ");
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// site duplication confirmed
state.removeAttribute(SITE_DUPLICATED);
state.removeAttribute(SITE_DUPLICATED_NAME);
// return to the list view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
}
break;
case 33:
break;
case 36:
/*
* actionForTemplate chef_site-newSiteCourse.vm
*/
if (forward)
{
List providerChosenList = new Vector();
if (params.getStrings("providerCourseAdd") == null)
{
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (params.getString("manualAdds") == null)
{
addAlert(state, rb.getString("java.manual")+" ");
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// The list of courses selected from provider listing
if (params.getStrings("providerCourseAdd") != null)
{
providerChosenList = new ArrayList(Arrays.asList(params.getStrings("providerCourseAdd"))); // list of course ids
state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN, providerChosenList);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
siteInfo = new SiteInfo();
if(state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
if (providerChosenList.size() >= 1)
{
siteInfo.title = getCourseTab(state, (String) providerChosenList.get(0));
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (params.getString("manualAdds") != null)
{
// if creating a new site
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(1));
}
else
{
// no manual add
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
if (getStateSite(state) != null)
{
// if revising a site, go to the confirmation page of adding classes
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
}
else
{
// if creating a site, go the the site information entry page
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
}
}
}
}
//next step
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2));
}
break;
case 38:
break;
case 39:
break;
case 42:
/* actionForTemplate chef_site-gradtoolsConfirm.vm
*
*/
break;
case 43:
/* actionForTemplate chef_site-editClass.vm
*
*/
if (forward)
{
if (params.getStrings("providerClassDeletes") == null && params.getStrings("manualClassDeletes") == null &&
!direction.equals("back"))
{
addAlert(state, rb.getString("java.classes"));
}
if (params.getStrings("providerClassDeletes") != null)
{
// build the deletions list
List providerCourseList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
List providerCourseDeleteList = new ArrayList(Arrays.asList(params.getStrings("providerClassDeletes")));
for (ListIterator i = providerCourseDeleteList.listIterator(); i.hasNext(); )
{
providerCourseList.remove((String) i.next());
}
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
}
if (params.getStrings("manualClassDeletes") != null)
{
// build the deletions list
List manualCourseList = (List) state.getAttribute(SITE_MANUAL_COURSE_LIST);
List manualCourseDeleteList = new ArrayList(Arrays.asList(params.getStrings("manualClassDeletes")));
for (ListIterator i = manualCourseDeleteList.listIterator(); i.hasNext(); )
{
manualCourseList.remove((String) i.next());
}
state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList);
}
updateCourseClasses (state, new Vector(), new Vector());
}
break;
case 44:
if (forward)
{
List providerList = (state.getAttribute(SITE_PROVIDER_COURSE_LIST) == null)?new Vector():(List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
List addProviderList = (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) == null)?new Vector():(List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
providerList.addAll(addProviderList);
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerList);
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
// if manually added course
List manualList = (state.getAttribute(SITE_MANUAL_COURSE_LIST) == null)?new Vector():(List) state.getAttribute(SITE_MANUAL_COURSE_LIST);
int manualAddNumber = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
List manualAddFields = (List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
Term t = (Term) state.getAttribute(STATE_TERM_SELECTED);
for (int m=0; m<manualAddNumber && t!=null; m++)
{
String manualAddClassId = CourseManagementService.getCourseId(t, (List) manualAddFields.get(m));
manualList.add(manualAddClassId);
}
state.setAttribute(SITE_MANUAL_COURSE_LIST, manualList);
}
updateCourseClasses(state, (List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN), (List) state.getAttribute(SITE_MANUAL_COURSE_LIST));
removeAddClassContext(state);
}
break;
case 49:
if (!forward)
{
state.removeAttribute(SORTED_BY);
state.removeAttribute(SORTED_ASC);
}
break;
}
}// actionFor Template
/**
* update current step index within the site creation wizard
* @param state The SessionState object
* @param forward Moving forward or backward?
*/
private void updateCurrentStep(SessionState state, boolean forward)
{
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null)
{
int currentStep = ((Integer) state.getAttribute(SITE_CREATE_CURRENT_STEP)).intValue();
if (forward)
{
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(currentStep+1));
}
else
{
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(currentStep-1));
}
}
}
/**
* remove related state variable for adding class
* @param state SessionState object
*/
private void removeAddClassContext(SessionState state)
{
// remove related state variables
state.removeAttribute(STATE_ADD_CLASS_MANUAL);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
state.removeAttribute(STATE_AUTO_ADD);
state.removeAttribute(SITE_CREATE_TOTAL_STEPS);
state.removeAttribute(SITE_CREATE_CURRENT_STEP);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
} // removeAddClassContext
private void updateCourseClasses (SessionState state, List notifyClasses, List requestClasses)
{
List providerCourseSectionList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
List manualCourseSectionList = (List) state.getAttribute(SITE_MANUAL_COURSE_LIST);
Site site = getStateSite(state);
String id = site.getId();
String realmId = SiteService.siteReference(id);
if ((providerCourseSectionList == null) || (providerCourseSectionList.size() == 0))
{
//no section access so remove Provider Id
try
{
AuthzGroup realmEdit1 = AuthzGroupService.getAuthzGroup(realmId);
realmEdit1.setProviderGroupId(NULL_STRING);
AuthzGroupService.save(realmEdit1);
}
catch (GroupNotDefinedException e)
{
M_log.warn(this + " IdUnusedException, " + site.getTitle() + "(" + realmId + ") not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.cannotedit"));
return;
}
catch (AuthzPermissionException e)
{
M_log.warn(this + " PermissionException, user does not have permission to edit AuthzGroup object " + site.getTitle() + "(" + realmId + "). ");
addAlert(state, rb.getString("java.notaccess"));
return;
}
}
if ((providerCourseSectionList != null) && (providerCourseSectionList.size() != 0))
{
// section access so rewrite Provider Id
String externalRealm = buildExternalRealm(id, state, providerCourseSectionList);
try
{
AuthzGroup realmEdit2 = AuthzGroupService.getAuthzGroup(realmId);
realmEdit2.setProviderGroupId(externalRealm);
AuthzGroupService.save(realmEdit2);
}
catch (GroupNotDefinedException e)
{
M_log.warn(this + " IdUnusedException, " + site.getTitle() + "(" + realmId + ") not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.cannotclasses"));
return;
}
catch (AuthzPermissionException e)
{
M_log.warn(this + " PermissionException, user does not have permission to edit AuthzGroup object " + site.getTitle() + "(" + realmId + "). ");
addAlert(state, rb.getString("java.notaccess"));
return;
}
}
if ((manualCourseSectionList != null) && (manualCourseSectionList.size() != 0))
{
// store the manually requested sections in one site property
String manualSections = "";
for (int j = 0; j < manualCourseSectionList.size(); )
{
manualSections = manualSections + (String) manualCourseSectionList.get(j);
j++;
if (j < manualCourseSectionList.size())
{
manualSections = manualSections + "+";
}
}
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.addProperty(PROP_SITE_REQUEST_COURSE, manualSections);
}
else
{
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.removeProperty(PROP_SITE_REQUEST_COURSE);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
commitSite(site);
}
else
{
}
if (requestClasses != null && requestClasses.size() > 0 && state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
try
{
// send out class request notifications
sendSiteRequest( state,
"change",
((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue(),
(List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
catch (Exception e)
{
M_log.warn(this + e.toString());
}
}
if (notifyClasses != null && notifyClasses.size() > 0)
{
try
{
// send out class access confirmation notifications
sendSiteNotification(state, notifyClasses);
}
catch (Exception e)
{
M_log.warn(this + e.toString());
}
}
} // updateCourseClasses
/**
* Sets selected roles for multiple users
* @param params The ParameterParser object
* @param listName The state variable
*/
private void getSelectedRoles(SessionState state, ParameterParser params, String listName)
{
Hashtable pSelectedRoles = (Hashtable) state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
if (pSelectedRoles == null)
{
pSelectedRoles = new Hashtable();
}
List userList = (List) state.getAttribute(listName);
for (int i = 0; i < userList.size(); i++)
{
String userId = null;
if(listName.equalsIgnoreCase(STATE_ADD_PARTICIPANTS))
{
userId = ((Participant) userList.get(i)).getUniqname();
}
else if (listName.equalsIgnoreCase(STATE_SELECTED_USER_LIST))
{
userId = (String) userList.get(i);
}
if (userId != null)
{
String rId = StringUtil.trimToNull(params.getString("role" + userId));
if (rId == null)
{
addAlert(state, rb.getString("java.rolefor")+" " + userId + ". ");
pSelectedRoles.remove(userId);
}
else
{
pSelectedRoles.put(userId, rId);
}
}
}
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, pSelectedRoles);
} // getSelectedRoles
/**
* dispatch function for changing participants roles
*/
public void doSiteinfo_edit_role(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String option = params.getString("option");
// dispatch
if (option.equalsIgnoreCase("same_role_true"))
{
state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.TRUE);
state.setAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE, params.getString("role_to_all"));
}
else if (option.equalsIgnoreCase("same_role_false"))
{
state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.FALSE);
state.removeAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE);
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) == null)
{
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, new Hashtable());
}
}
else if (option.equalsIgnoreCase("continue"))
{
doContinue(data);
}
else if (option.equalsIgnoreCase("back"))
{
doBack(data);
}
else if (option.equalsIgnoreCase("cancel"))
{
doCancel(data);
}
} // doSiteinfo_edit_globalAccess
/**
* dispatch function for changing site global access
*/
public void doSiteinfo_edit_globalAccess(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String option = params.getString("option");
// dispatch
if (option.equalsIgnoreCase("joinable"))
{
state.setAttribute("form_joinable", Boolean.TRUE);
state.setAttribute("form_joinerRole", getStateSite(state).getJoinerRole());
}
else if (option.equalsIgnoreCase("unjoinable"))
{
state.setAttribute("form_joinable", Boolean.FALSE);
state.removeAttribute("form_joinerRole");
}
else if (option.equalsIgnoreCase("continue"))
{
doContinue(data);
}
else if (option.equalsIgnoreCase("cancel"))
{
doCancel(data);
}
} // doSiteinfo_edit_globalAccess
/**
* save changes to site global access
*/
public void doSiteinfo_save_globalAccess(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Site s = getStateSite(state);
boolean joinable = ((Boolean) state.getAttribute("form_joinable")).booleanValue();
s.setJoinable(joinable);
if (joinable)
{
// set the joiner role
String joinerRole = (String) state.getAttribute("form_joinerRole");
s.setJoinerRole(joinerRole);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
//release site edit
commitSite(s);
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} // doSiteinfo_save_globalAccess
/**
* updateSiteAttributes
*
*/
private void updateSiteAttributes (SessionState state)
{
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
else
{
M_log.warn("SiteAction.updateSiteAttributes STATE_SITE_INFO == null");
return;
}
Site site = getStateSite(state);
if (site != null)
{
if (StringUtil.trimToNull(siteInfo.title) != null)
{
site.setTitle(siteInfo.title);
}
if (siteInfo.description != null)
{
site.setDescription(siteInfo.description);
}
site.setPublished(siteInfo.published);
setAppearance(state, site, siteInfo.iconUrl);
site.setJoinable(siteInfo.joinable);
if (StringUtil.trimToNull(siteInfo.joinerRole) != null)
{
site.setJoinerRole(siteInfo.joinerRole);
}
// Make changes and then put changed site back in state
String id = site.getId();
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
// TODO:
}
catch (PermissionException e)
{
// TODO:
}
if (SiteService.allowUpdateSite(id))
{
try
{
SiteService.getSite(id);
state.setAttribute(STATE_SITE_INSTANCE_ID, id);
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.commitSite IdUnusedException " + siteInfo.getTitle() + "(" + id + ") not found");
}
}
// no permission
else
{
addAlert(state, rb.getString("java.makechanges"));
M_log.warn("SiteAction.commitSite PermissionException " + siteInfo.getTitle() + "(" + id + ")");
}
}
} // updateSiteAttributes
/**
* %%% legacy properties, to be removed
*/
private void updateSiteInfo (ParameterParser params, SessionState state)
{
SiteInfo siteInfo = new SiteInfo();
if(state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
siteInfo.site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (params.getString ("title") != null)
{
siteInfo.title = params.getString ("title");
}
if (params.getString ("description") != null)
{
siteInfo.description = params.getString ("description");
}
if (params.getString ("short_description") != null)
{
siteInfo.short_description = params.getString ("short_description");
}
if (params.getString ("additional") != null)
{
siteInfo.additional = params.getString ("additional");
}
if (params.getString ("iconUrl") != null)
{
siteInfo.iconUrl = params.getString ("iconUrl");
}
else
{
siteInfo.iconUrl = params.getString ("skin");
}
if (params.getString ("joinerRole") != null)
{
siteInfo.joinerRole = params.getString ("joinerRole");
}
if (params.getString ("joinable") != null)
{
boolean joinable = params.getBoolean("joinable");
siteInfo.joinable = joinable;
if(!joinable) siteInfo.joinerRole = NULL_STRING;
}
if (params.getString ("itemStatus") != null)
{
siteInfo.published = Boolean.valueOf(params.getString ("itemStatus")).booleanValue();
}
// site contact information
String name = StringUtil.trimToZero(params.getString ("siteContactName"));
siteInfo.site_contact_name = name;
String email = StringUtil.trimToZero(params.getString ("siteContactEmail"));
if (email != null)
{
String[] parts = email.split("@");
if(email.length() > 0 && (email.indexOf("@") == -1 || parts.length != 2 || parts[0].length() == 0 || !Validator.checkEmailLocal(parts[0])))
{
// invalid email
addAlert(state, email + " "+rb.getString("java.invalid") + rb.getString("java.theemail"));
}
siteInfo.site_contact_email = email;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
} // updateSiteInfo
/**
* getExternalRealmId
*
*/
private String getExternalRealmId (SessionState state)
{
String realmId = SiteService.siteReference((String) state.getAttribute(STATE_SITE_INSTANCE_ID));
String rv = null;
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
rv = realm.getProviderGroupId();
}
catch (GroupNotDefinedException e)
{
M_log.warn("SiteAction.getExternalRealmId, site realm not found");
}
return rv;
} // getExternalRealmId
/**
* getParticipantList
*
*/
private List getParticipantList(SessionState state)
{
List members = new Vector();
List participants = new Vector();
String realmId = SiteService.siteReference((String) state.getAttribute(STATE_SITE_INSTANCE_ID));
List providerCourseList = null;
providerCourseList = getProviderCourseList(StringUtil.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null && providerCourseList.size() > 0)
{
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
}
if (providerCourseList != null)
{
for (int k = 0; k < providerCourseList.size(); k++)
{
String courseId = (String) providerCourseList.get(k);
try
{
members.addAll(CourseManagementService.getCourseMembers(courseId));
}
catch (Exception e)
{
// M_log.warn(this + " Cannot find course " + courseId);
}
}
}
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
Set grants = realm.getMembers();
//Collections.sort(users);
for (Iterator i = grants.iterator(); i.hasNext();)
{
Member g = (Member) i.next();
String userString = g.getUserEid();
Role r = g.getRole();
boolean alreadyInList = false;
for (Iterator p = members.iterator(); p.hasNext() && !alreadyInList;)
{
CourseMember member = (CourseMember) p.next();
String memberUniqname = member.getUniqname();
if (userString.equalsIgnoreCase(memberUniqname))
{
alreadyInList = true;
if (r != null)
{
member.setRole(r.getId());
}
try
{
User user = UserDirectoryService.getUserByEid(memberUniqname);
Participant participant = new Participant();
participant.name = user.getSortName();
participant.uniqname = user.getId();
participant.role = member.getRole();
participant.providerRole = member.getProviderRole();
participant.course = member.getCourse();
participant.section = member.getSection();
participant.credits = member.getCredits();
participant.regId = member.getId();
participant.removeable = false;
participants.add(participant);
}
catch (UserNotDefinedException e)
{
// deal with missing user quietly without throwing a warning message
}
}
}
if (!alreadyInList)
{
try
{
User user = UserDirectoryService.getUserByEid(userString);
Participant participant = new Participant();
participant.name = user.getSortName();
participant.uniqname = user.getId();
if (r != null)
{
participant.role = r.getId();
}
participants.add(participant);
}
catch (UserNotDefinedException e)
{
// deal with missing user quietly without throwing a warning message
}
}
}
}
catch (GroupNotDefinedException e)
{
M_log.warn(this + " IdUnusedException " + realmId);
}
state.setAttribute(STATE_PARTICIPANT_LIST, participants);
return participants;
} // getParticipantList
/**
* getRoles
*
*/
private List getRoles (SessionState state)
{
List roles = new Vector();
String realmId = SiteService.siteReference((String) state.getAttribute(STATE_SITE_INSTANCE_ID));
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
roles.addAll(realm.getRoles());
Collections.sort(roles);
}
catch (GroupNotDefinedException e)
{
M_log.warn("SiteAction.getRoles IdUnusedException " + realmId);
}
return roles;
} // getRoles
private void addSynopticTool(SitePage page, String toolId, String toolTitle, String layoutHint)
{
// Add synoptic announcements tool
ToolConfiguration tool = page.addTool();
Tool reg = ToolManager.getTool(toolId);
tool.setTool(toolId, reg);
tool.setTitle(toolTitle);
tool.setLayoutHints(layoutHint);
}
private void getRevisedFeatures(ParameterParser params, SessionState state)
{
Site site = getStateSite(state);
//get the list of Worksite Setup configured pages
List wSetupPageList = (List)state.getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST);
WorksiteSetupPage wSetupPage = new WorksiteSetupPage();
WorksiteSetupPage wSetupHome = new WorksiteSetupPage();
List pageList = new Vector();
//declare some flags used in making decisions about Home, whether to add, remove, or do nothing
boolean homeInChosenList = false;
boolean homeInWSetupPageList = false;
List chosenList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
//if features were selected, diff wSetupPageList and chosenList to get page adds and removes
// boolean values for adding synoptic views
boolean hasAnnouncement = false;
boolean hasChat = false;
boolean hasDiscussion = false;
boolean hasEmail = false;
boolean hasNewSiteInfo = false;
//Special case - Worksite Setup Home comes from a hardcoded checkbox on the vm template rather than toolRegistrationList
//see if Home was chosen
for (ListIterator j = chosenList.listIterator(); j.hasNext(); )
{
String choice = (String) j.next();
if(choice.equalsIgnoreCase(HOME_TOOL_ID))
{
homeInChosenList = true;
}
else if (choice.equals("sakai.mailbox"))
{
hasEmail = true;
String alias = StringUtil.trimToNull((String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
if (alias != null)
{
if (!Validator.checkEmailLocal(alias))
{
addAlert(state, rb.getString("java.theemail"));
}
else
{
try
{
String channelReference = mailArchiveChannelReference(site.getId());
//first, clear any alias set to this channel
AliasService.removeTargetAliases(channelReference); // check to see whether the alias has been used
try
{
String target = AliasService.getTarget(alias);
if (target != null)
{
addAlert(state, rb.getString("java.emailinuse")+" ");
}
}
catch (IdUnusedException ee)
{
try
{
AliasService.setAlias(alias, channelReference);
}
catch (IdUsedException exception) {}
catch (IdInvalidException exception) {}
catch (PermissionException exception) {}
}
}
catch (PermissionException exception) {}
}
}
}
else if (choice.equals("sakai.announcements"))
{
hasAnnouncement = true;
}
else if (choice.equals("sakai.chat"))
{
hasChat = true;
}
else if (choice.equals("sakai.discussion"))
{
hasDiscussion = true;
}
}
//see if Home and/or Help in the wSetupPageList (can just check title here, because we checked patterns before adding to the list)
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext(); )
{
wSetupPage = (WorksiteSetupPage) i.next();
if(wSetupPage.getToolId().equals(HOME_TOOL_ID)){ homeInWSetupPageList = true; }
}
if (homeInChosenList)
{
SitePage page = null;
// Were the synoptic views of Announcement, Discussioin, Chat existing before the editing
boolean hadAnnouncement=false,hadDiscussion=false,hadChat=false;
if (homeInWSetupPageList)
{
if (!SiteService.isUserSite(site.getId()))
{
//for non-myworkspace site, if Home is chosen and Home is in the wSetupPageList, remove synoptic tools
WorksiteSetupPage homePage = new WorksiteSetupPage();
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext(); )
{
WorksiteSetupPage comparePage = (WorksiteSetupPage) i.next();
if((comparePage.getToolId()).equals(HOME_TOOL_ID)) { homePage = comparePage; }
}
page = site.getPage(homePage.getPageId());
List toolList = page.getTools();
List removeToolList = new Vector();
// get those synoptic tools
for (ListIterator iToolList = toolList.listIterator(); iToolList.hasNext(); )
{
ToolConfiguration tool = (ToolConfiguration) iToolList.next();
if (tool.getTool().getId().equals("sakai.synoptic.announcement"))
{
hadAnnouncement = true;
if (!hasAnnouncement)
{
removeToolList.add(tool);// if Announcement tool isn't selected, remove the synotic Announcement
}
}
if (tool.getTool().getId().equals("sakai.synoptic.discussion"))
{
hadDiscussion = true;
if (!hasDiscussion)
{
removeToolList.add(tool);// if Discussion tool isn't selected, remove the synoptic Discussion
}
}
if (tool.getTool().getId().equals("sakai.synoptic.chat"))
{
hadChat = true;
if (!hasChat)
{
removeToolList.add(tool);// if Chat tool isn't selected, remove the synoptic Chat
}
}
}
// remove those synoptic tools
for (ListIterator rToolList = removeToolList.listIterator(); rToolList.hasNext(); )
{
page.removeTool((ToolConfiguration) rToolList.next());
}
}
}
else
{
//if Home is chosen and Home is not in wSetupPageList, add Home to site and wSetupPageList
page = site.addPage();
page.setTitle(rb.getString("java.home"));
wSetupHome.pageId = page.getId();
wSetupHome.pageTitle = page.getTitle();
wSetupHome.toolId = HOME_TOOL_ID;
wSetupPageList.add(wSetupHome);
//Add worksite information tool
ToolConfiguration tool = page.addTool();
Tool reg = ToolManager.getTool("sakai.iframe.site");
tool.setTool("sakai.iframe.site", reg);
tool.setTitle(rb.getString("java.workinfo"));
tool.setLayoutHints("0,0");
}
if (!SiteService.isUserSite(site.getId()))
{
//add synoptical tools to home tool in non-myworkspace site
try
{
if (hasAnnouncement && !hadAnnouncement)
{
//Add synoptic announcements tool
addSynopticTool(page, "sakai.synoptic.announcement", rb.getString("java.recann"), "0,1");
}
if (hasDiscussion && !hadDiscussion)
{
//Add synoptic discussion tool
addSynopticTool(page, "sakai.synoptic.discussion", rb.getString("java.recdisc"), "1,1");
}
if (hasChat&& !hadChat)
{
//Add synoptic chat tool
addSynopticTool(page, "sakai.synoptic.chat", rb.getString("java.recent"), "2,1");
}
if (hasAnnouncement || hasDiscussion || hasChat )
{
page.setLayout(SitePage.LAYOUT_DOUBLE_COL);
}
else
{
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
}
}
catch (Exception e)
{
M_log.warn("SiteAction.getFeatures Exception " + e.getMessage());
}
}
} // add Home
//if Home is in wSetupPageList and not chosen, remove Home feature from wSetupPageList and site
if (!homeInChosenList && homeInWSetupPageList)
{
//remove Home from wSetupPageList
WorksiteSetupPage removePage = new WorksiteSetupPage();
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext(); )
{
WorksiteSetupPage comparePage = (WorksiteSetupPage) i.next();
if(comparePage.getToolId().equals(HOME_TOOL_ID)) { removePage = comparePage; }
}
SitePage siteHome = site.getPage(removePage.getPageId());
site.removePage(siteHome);
wSetupPageList.remove(removePage);
}
//declare flags used in making decisions about whether to add, remove, or do nothing
boolean inChosenList;
boolean inWSetupPageList;
Hashtable newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
Hashtable wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES);
Hashtable newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
Hashtable wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS);
Set categories = new HashSet();
categories.add((String) state.getAttribute(STATE_SITE_TYPE));
Set toolRegistrationList = ToolManager.findTools(categories, null);
// first looking for any tool for removal
Vector removePageIds = new Vector();
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext(); )
{
wSetupPage = (WorksiteSetupPage)k.next();
String pageToolId = wSetupPage.getToolId();
// use page id + tool id for multiple News and Web Content tool
if (pageToolId.indexOf("sakai.news") != -1 || pageToolId.indexOf("sakai.iframe") != -1)
{
pageToolId = wSetupPage.getPageId() + pageToolId;
}
inChosenList = false;
for (ListIterator j = chosenList.listIterator(); j.hasNext(); )
{
String toolId = (String) j.next();
if(pageToolId.equals(toolId))
{
inChosenList = true;
}
}
if (!inChosenList)
{
removePageIds.add(wSetupPage.getPageId());
}
}
for (int i = 0; i < removePageIds.size(); i++)
{
//if the tool exists in the wSetupPageList, remove it from the site
String removeId = (String) removePageIds.get(i);
SitePage sitePage = site.getPage(removeId);
site.removePage(sitePage);
// and remove it from wSetupPageList
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext(); )
{
wSetupPage = (WorksiteSetupPage)k.next();
if (!wSetupPage.getPageId().equals(removeId))
{
wSetupPage = null;
}
}
if (wSetupPage != null)
{
wSetupPageList.remove(wSetupPage);
}
}
// then looking for any tool to add
for (ListIterator j = orderToolIds(state, (String) state.getAttribute(STATE_SITE_TYPE), chosenList).listIterator(); j.hasNext(); )
{
String toolId = (String) j.next();
//Is the tool in the wSetupPageList?
inWSetupPageList = false;
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext(); )
{
wSetupPage = (WorksiteSetupPage)k.next();
String pageToolId = wSetupPage.getToolId();
// use page Id + toolId for multiple News and Web Content tool
if (pageToolId.indexOf("sakai.news") != -1 || pageToolId.indexOf("sakai.iframe") != -1)
{
pageToolId = wSetupPage.getPageId() + pageToolId;
}
if(pageToolId.equals(toolId))
{
inWSetupPageList = true;
// but for News and Web Content tool, need to change the title
if (toolId.indexOf("sakai.news") != -1)
{
SitePage pEdit = (SitePage) site.getPage(wSetupPage.pageId);
pEdit.setTitle((String) newsTitles.get(toolId));
List toolList = pEdit.getTools();
for (ListIterator jTool = toolList.listIterator(); jTool.hasNext(); )
{
ToolConfiguration tool = (ToolConfiguration) jTool.next();
if (tool.getTool().getId().equals("sakai.news"))
{
// set News tool title
tool.setTitle((String) newsTitles.get(toolId));
// set News tool url
String urlString = (String) newsUrls.get(toolId);
try
{
URL url = new URL(urlString);
// update the tool config
tool.getPlacementConfig().setProperty("channel-url", (String) url.toExternalForm());
}
catch (MalformedURLException e)
{
addAlert(state, rb.getString("java.invurl")+" " + urlString + ". ");
}
}
}
}
else if (toolId.indexOf("sakai.iframe") != -1)
{
SitePage pEdit = (SitePage) site.getPage(wSetupPage.pageId);
pEdit.setTitle((String) wcTitles.get(toolId));
List toolList = pEdit.getTools();
for (ListIterator jTool = toolList.listIterator(); jTool.hasNext(); )
{
ToolConfiguration tool = (ToolConfiguration) jTool.next();
if (tool.getTool().getId().equals("sakai.iframe"))
{
// set Web Content tool title
tool.setTitle((String) wcTitles.get(toolId));
// set Web Content tool url
String wcUrl = StringUtil.trimToNull((String) wcUrls.get(toolId));
if (wcUrl != null && !wcUrl.equals(WEB_CONTENT_DEFAULT_URL))
{
// if url is not empty and not consists only of "http://"
tool.getPlacementConfig().setProperty("source", wcUrl);
}
}
}
}
}
}
if (inWSetupPageList)
{
// if the tool already in the list, do nothing so to save the option settings
}
else
{
// if in chosen list but not in wSetupPageList, add it to the site (one tool on a page)
// if Site Info tool is being newly added
if (toolId.equals("sakai.siteinfo"))
{
hasNewSiteInfo = true;
}
Tool toolRegFound = null;
for (Iterator i = toolRegistrationList.iterator(); i.hasNext(); )
{
Tool toolReg = (Tool) i.next();
if ((toolId.indexOf("assignment") != -1 && toolId.equals(toolReg.getId()))
|| (toolId.indexOf("assignment") == -1 && toolId.indexOf(toolReg.getId()) != -1))
{
toolRegFound = toolReg;
}
}
if (toolRegFound != null)
{
// we know such a tool, so add it
WorksiteSetupPage addPage = new WorksiteSetupPage();
SitePage page = site.addPage();
addPage.pageId = page.getId();
if (toolId.indexOf("sakai.news") != -1)
{
// set News tool title
page.setTitle((String) newsTitles.get(toolId));
}
else if (toolId.indexOf("sakai.iframe") != -1)
{
// set Web Content tool title
page.setTitle((String) wcTitles.get(toolId));
}
else
{
// other tools with default title
page.setTitle(toolRegFound.getTitle());
}
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool(toolRegFound.getId(), toolRegFound);
addPage.toolId = toolId;
wSetupPageList.add(addPage);
//set tool title
if (toolId.indexOf("sakai.news") != -1)
{
// set News tool title
tool.setTitle((String) newsTitles.get(toolId));
//set News tool url
String urlString = (String) newsUrls.get(toolId);
try
{
URL url = new URL(urlString);
// update the tool config
tool.getPlacementConfig().setProperty("channel-url", (String) url.toExternalForm());
}
catch(MalformedURLException e)
{
// display message
addAlert(state, "Invalid URL " + urlString + ". ");
// remove the page because of invalid url
site.removePage(page);
}
}
else if (toolId.indexOf("sakai.iframe") != -1)
{
// set Web Content tool title
tool.setTitle((String) wcTitles.get(toolId));
// set Web Content tool url
String wcUrl = StringUtil.trimToNull((String) wcUrls.get(toolId));
if (wcUrl != null && !wcUrl.equals(WEB_CONTENT_DEFAULT_URL))
{
// if url is not empty and not consists only of "http://"
tool.getPlacementConfig().setProperty("source", wcUrl);
}
}
else
{
tool.setTitle(toolRegFound.getTitle());
}
}
}
} // for
if (homeInChosenList)
{
//Order tools - move Home to the top - first find it
SitePage homePage = null;
pageList = site.getPages();
if (pageList != null && pageList.size() != 0)
{
for (ListIterator i = pageList.listIterator(); i.hasNext(); )
{
SitePage page = (SitePage)i.next();
if (rb.getString("java.home").equals(page.getTitle()))//if ("Home".equals(page.getTitle()))
{
homePage = page;
break;
}
}
}
// if found, move it
if (homePage != null)
{
// move home from it's index to the first position
int homePosition = pageList.indexOf(homePage);
for (int n = 0; n < homePosition; n++)
{
homePage.moveUp();
}
}
}
// if Site Info is newly added, more it to the last
if (hasNewSiteInfo)
{
SitePage siteInfoPage = null;
pageList = site.getPages();
String[] toolIds = {"sakai.siteinfo"};
if (pageList != null && pageList.size() != 0)
{
for (ListIterator i = pageList.listIterator(); siteInfoPage==null && i.hasNext(); )
{
SitePage page = (SitePage)i.next();
int s = page.getTools(toolIds).size();
if (s > 0)
{
siteInfoPage = page;
}
}
}
// if found, move it
if (siteInfoPage != null)
{
// move home from it's index to the first position
int siteInfoPosition = pageList.indexOf(siteInfoPage);
for (int n = siteInfoPosition; n<pageList.size(); n++)
{
siteInfoPage.moveDown();
}
}
}
// if there is no email tool chosen
if (!hasEmail)
{
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
//commit
commitSite(site);
} // getRevisedFeatures
/**
* getFeatures gets features for a new site
*
*/
private void getFeatures(ParameterParser params, SessionState state)
{
List idsSelected = new Vector();
boolean goToENWPage = false;
boolean homeSelected = false;
// Add new pages and tools, if any
if (params.getStrings ("selectedTools") == null)
{
addAlert(state, rb.getString("atleastonetool"));
}
else
{
List l = new ArrayList(Arrays.asList(params.getStrings ("selectedTools"))); // toolId's & titles of chosen tools
for (int i = 0; i < l.size(); i++)
{
String toolId = (String) l.get(i);
if (toolId.equals("sakai.mailbox") || toolId.indexOf("sakai.news") != -1 || toolId.indexOf("sakai.iframe") != -1)
{
goToENWPage = true;
}
else if (toolId.equals(HOME_TOOL_ID))
{
homeSelected = true;
}
idsSelected.add(toolId);
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(homeSelected));
}
String importString = params.getString("import");
if (importString!= null && importString.equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.setAttribute(STATE_IMPORT, Boolean.TRUE);
List importSites = new Vector();
if (params.getStrings("importSites") != null)
{
importSites = new ArrayList(Arrays.asList(params.getStrings("importSites")));
}
if (importSites.size() == 0)
{
addAlert(state, rb.getString("java.toimport")+" ");
}
else
{
Hashtable sites = new Hashtable();
for (int index = 0; index < importSites.size(); index ++)
{
try
{
Site s = SiteService.getSite((String) importSites.get(index));
if (!sites.containsKey(s))
{
sites.put(s, new Vector());
}
}
catch (IdUnusedException e)
{
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
}
else
{
state.removeAttribute(STATE_IMPORT);
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List of ToolRegistration toolId's
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (state.getAttribute(STATE_IMPORT) != null)
{
// go to import tool page
state.setAttribute(STATE_TEMPLATE_INDEX, "27");
}
else if (goToENWPage)
{
// go to the configuration page for Email Archive, News and Web Content tools
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
else
{
// go to edit access page
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
int totalSteps = 4;
if (state.getAttribute(STATE_SITE_TYPE) != null && ((String) state.getAttribute(STATE_SITE_TYPE)).equalsIgnoreCase("course"))
{
totalSteps = 5;
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null && state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
totalSteps++;
}
}
if (state.getAttribute(STATE_IMPORT) != null)
{
totalSteps++;
}
if (goToENWPage)
{
totalSteps++;
}
state.setAttribute(SITE_CREATE_TOTAL_STEPS, new Integer(totalSteps));
}
} // getFeatures
/**
* addFeatures adds features to a new site
*
*/
private void addFeatures(SessionState state)
{
List toolRegistrationList = (Vector)state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
Site site = getStateSite(state);
List pageList = new Vector();
int moves = 0;
boolean hasHome = false;
boolean hasAnnouncement = false;
boolean hasChat = false;
boolean hasDiscussion = false;
boolean hasSiteInfo = false;
List chosenList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// tools to be imported from other sites?
Hashtable importTools = null;
if (state.getAttribute(STATE_IMPORT_SITE_TOOL) != null)
{
importTools = (Hashtable) state.getAttribute(STATE_IMPORT_SITE_TOOL);
}
//for tools other than home
if (chosenList.contains(HOME_TOOL_ID))
{
// add home tool later
hasHome = true;
}
// order the id list
chosenList = orderToolIds(state, site.getType(), chosenList);
// titles for news tools
Hashtable newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
// urls for news tools
Hashtable newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
// titles for web content tools
Hashtable wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES);
// urls for web content tools
Hashtable wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS);
if (chosenList.size() > 0)
{
Tool toolRegFound = null;
for (ListIterator i = chosenList.listIterator(); i.hasNext(); )
{
String toolId = (String) i.next();
// find the tool in the tool registration list
toolRegFound = null;
for (int j = 0; j < toolRegistrationList.size() && toolRegFound == null; j++)
{
MyTool tool = (MyTool) toolRegistrationList.get(j);
if ((toolId.indexOf("assignment") != -1 && toolId.equals(tool.getId()))
|| (toolId.indexOf("assignment") == -1 && toolId.indexOf(tool.getId()) != -1))
{
toolRegFound = ToolManager.getTool(tool.getId());
}
}
if (toolRegFound != null)
{
if (toolId.indexOf("sakai.news") != -1)
{
// adding multiple news tool
String newsTitle = (String) newsTitles.get(toolId);
SitePage page = site.addPage();
page.setTitle(newsTitle); // the visible label on the tool menu
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool("sakai.news", ToolManager.getTool("sakai.news"));
tool.setTitle(newsTitle);
tool.setLayoutHints("0,0");
String urlString = (String) newsUrls.get(toolId);
//update the tool config
tool.getPlacementConfig().setProperty("channel-url", urlString);
}
else if (toolId.indexOf("sakai.iframe") != -1)
{
// adding multiple web content tool
String wcTitle = (String) wcTitles.get(toolId);
SitePage page = site.addPage();
page.setTitle(wcTitle); // the visible label on the tool menu
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool("sakai.iframe", ToolManager.getTool("sakai.iframe"));
tool.setTitle(wcTitle);
tool.setLayoutHints("0,0");
String wcUrl = StringUtil.trimToNull((String) wcUrls.get(toolId));
if (wcUrl != null && !wcUrl.equals(WEB_CONTENT_DEFAULT_URL))
{
// if url is not empty and not consists only of "http://"
tool.getPlacementConfig().setProperty("source", wcUrl);
}
}
else
{
SitePage page = site.addPage();
page.setTitle(toolRegFound.getTitle()); // the visible label on the tool menu
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool(toolRegFound.getId(), toolRegFound);
tool.setLayoutHints("0,0");
} // Other features
}
// booleans for synoptic views
if (toolId.equals("sakai.announcements"))
{
hasAnnouncement = true;
}
else if (toolId.equals("sakai.chat"))
{
hasChat = true;
}
else if (toolId.equals("sakai.discussion"))
{
hasDiscussion = true;
}
else if (toolId.equals("sakai.siteinfo"))
{
hasSiteInfo = true;
}
} // for
//import
importToolIntoSite(chosenList, importTools, site);
// add home tool
if (hasHome)
{
// Home is a special case, with several tools on the page. "home" is hard coded in chef_site-addRemoveFeatures.vm.
try
{
SitePage page = site.addPage();
page.setTitle(rb.getString("java.home")); // the visible label on the tool menu
if (hasAnnouncement || hasDiscussion || hasChat)
{
page.setLayout(SitePage.LAYOUT_DOUBLE_COL);
}
else
{
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
}
//Add worksite information tool
ToolConfiguration tool = page.addTool();
tool.setTool("sakai.iframe.site", ToolManager.getTool("sakai.iframe.site"));
tool.setTitle(rb.getString("java.workinfo"));
tool.setLayoutHints("0,0");
if (hasAnnouncement)
{
//Add synoptic announcements tool
tool = page.addTool();
tool.setTool("sakai.synoptic.announcement", ToolManager.getTool("sakai.synoptic.announcement"));
tool.setTitle(rb.getString("java.recann"));
tool.setLayoutHints("0,1");
}
if (hasDiscussion)
{
//Add synoptic announcements tool
tool = page.addTool();
tool.setTool("sakai.synoptic.discussion", ToolManager.getTool("sakai.synoptic.discussion"));
tool.setTitle("Recent Discussion Items");
tool.setLayoutHints("1,1");
}
if (hasChat)
{
//Add synoptic chat tool
tool = page.addTool();
tool.setTool("sakai.synoptic.chat", ToolManager.getTool("sakai.synoptic.chat"));
tool.setTitle("Recent Chat Messages");
tool.setLayoutHints("2,1");
}
}
catch (Exception e)
{
M_log.warn("SiteAction.getFeatures Exception " + e.getMessage());
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, Boolean.TRUE);
//Order tools - move Home to the top
pageList = site.getPages();
if(pageList != null && pageList.size() != 0)
{
for (ListIterator i = pageList.listIterator(); i.hasNext(); )
{
SitePage page = (SitePage)i.next();
if((page.getTitle()).equals(rb.getString("java.home")))
{
moves = pageList.indexOf(page);
for (int n = 0; n < moves; n++)
{
page.moveUp();
}
}
}
}
} // Home feature
// move Site Info tool, if selected, to the end of tool list
if (hasSiteInfo)
{
SitePage siteInfoPage = null;
pageList = site.getPages();
String[] toolIds = {"sakai.siteinfo"};
if (pageList != null && pageList.size() != 0)
{
for (ListIterator i = pageList.listIterator(); siteInfoPage==null && i.hasNext(); )
{
SitePage page = (SitePage)i.next();
int s = page.getTools(toolIds).size();
if (s > 0)
{
siteInfoPage = page;
}
}
}
//if found, move it
if (siteInfoPage != null)
{
// move home from it's index to the first position
int siteInfoPosition = pageList.indexOf(siteInfoPage);
for (int n = siteInfoPosition; n<pageList.size(); n++)
{
siteInfoPage.moveDown();
}
}
} // Site Info
}
// commit
commitSite(site);
} // addFeatures
// import tool content into site
private void importToolIntoSite(List toolIds, Hashtable importTools, Site site)
{
if (importTools != null)
{
// import resources first
boolean resourcesImported = false;
for (int i = 0; i < toolIds.size() && !resourcesImported; i++)
{
String toolId = (String) toolIds.get(i);
if (toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId))
{
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++)
{
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
String fromSiteCollectionId = ContentHostingService.getSiteCollection(fromSiteId);
String toSiteCollectionId = ContentHostingService.getSiteCollection(toSiteId);
transferCopyEntities(toolId, fromSiteCollectionId, toSiteCollectionId);
resourcesImported = true;
}
}
}
// ijmport other tools then
for (int i = 0; i < toolIds.size(); i++)
{
String toolId = (String) toolIds.get(i);
if (!toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId))
{
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++)
{
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
transferCopyEntities(toolId, fromSiteId, toSiteId);
}
}
}
}
} // importToolIntoSite
public void saveSiteStatus(SessionState state, boolean published)
{
Site site = getStateSite(state);
site.setPublished(published);
} // saveSiteStatus
public void commitSite(Site site, boolean published)
{
site.setPublished(published);
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
// TODO:
}
catch (PermissionException e)
{
// TODO:
}
} // commitSite
public void commitSite(Site site)
{
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
// TODO:
}
catch (PermissionException e)
{
// TODO:
}
}// commitSite
private boolean isValidDomain(String email)
{
String invalidEmailInIdAccountString = ServerConfigurationService.getString("invalidEmailInIdAccountString", null);
if(invalidEmailInIdAccountString != null) {
String[] invalidDomains = invalidEmailInIdAccountString.split(",");
for(int i = 0; i < invalidDomains.length; i++) {
String domain = invalidDomains[i].trim();
if(email.toLowerCase().indexOf(domain.toLowerCase()) != -1) {
return false;
}
}
}
return true;
}
private void checkAddParticipant(ParameterParser params, SessionState state)
{
// get the participants to be added
int i;
Vector pList = new Vector();
HashSet existingUsers = new HashSet();
Site site = null;
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
try
{
site = SiteService.getSite(siteId);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("java.specif") + " " + siteId);
}
//accept noEmailInIdAccounts and/or emailInIdAccount account names
String noEmailInIdAccounts = "";
String emailInIdAccounts = "";
//check that there is something with which to work
noEmailInIdAccounts = StringUtil.trimToNull((params.getString("noEmailInIdAccount")));
emailInIdAccounts = StringUtil.trimToNull(params.getString("emailInIdAccount"));
state.setAttribute("noEmailInIdAccountValue", noEmailInIdAccounts);
state.setAttribute("emailInIdAccountValue", emailInIdAccounts);
//if there is no uniquname or emailInIdAccount entered
if (noEmailInIdAccounts == null && emailInIdAccounts == null)
{
addAlert(state, rb.getString("java.guest"));
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
return;
}
String at = "@";
if (noEmailInIdAccounts != null)
{
// adding noEmailInIdAccounts
String[] noEmailInIdAccountArray = noEmailInIdAccounts.split("\r\n");
for (i = 0; i < noEmailInIdAccountArray.length; i++)
{
String noEmailInIdAccount = StringUtil.trimToNull(noEmailInIdAccountArray[i].replaceAll("[\t\r\n]",""));
//if there is some text, try to use it
if(noEmailInIdAccount != null)
{
//automaticially add emailInIdAccount account
Participant participant = new Participant();
try
{
User u = UserDirectoryService.getUserByEid(noEmailInIdAccount);
if (site != null && site.getUserRole(u.getId()) != null)
{
// user already exists in the site, cannot be added again
existingUsers.add(noEmailInIdAccount);
}
else
{
participant.name = u.getDisplayName();
participant.uniqname = noEmailInIdAccount;
pList.add(participant);
}
}
catch (UserNotDefinedException e)
{
addAlert(state, noEmailInIdAccount + " "+rb.getString("java.username")+" ");
}
}
}
} // noEmailInIdAccounts
if (emailInIdAccounts != null)
{
String[] emailInIdAccountArray = emailInIdAccounts.split("\r\n");
for (i = 0; i < emailInIdAccountArray.length; i++)
{
String emailInIdAccount = emailInIdAccountArray[i];
//if there is some text, try to use it
emailInIdAccount.replaceAll("[ \t\r\n]","");
//remove the trailing dots and empty space
while (emailInIdAccount.endsWith(".") || emailInIdAccount.endsWith(" "))
{
emailInIdAccount = emailInIdAccount.substring(0, emailInIdAccount.length() -1);
}
if(emailInIdAccount != null && emailInIdAccount.length() > 0)
{
String[] parts = emailInIdAccount.split(at);
if(emailInIdAccount.indexOf(at) == -1 )
{
// must be a valid email address
addAlert(state, emailInIdAccount + " "+rb.getString("java.emailaddress"));
}
else if((parts.length != 2) || (parts[0].length() == 0))
{
// must have both id and address part
addAlert(state, emailInIdAccount + " "+rb.getString("java.notemailid"));
}
else if (!Validator.checkEmailLocal(parts[0]))
{
addAlert(state, emailInIdAccount + " "+rb.getString("java.emailaddress") + rb.getString("java.theemail"));
}
else if (emailInIdAccount != null && !isValidDomain(emailInIdAccount))
{
// wrong string inside emailInIdAccount id
addAlert(state, emailInIdAccount + " "+rb.getString("java.emailaddress")+" ");
}
else
{
Participant participant = new Participant();
try
{
// if the emailInIdAccount user already exists
User u = UserDirectoryService.getUserByEid(emailInIdAccount);
if (site != null && site.getUserRole(u.getId()) != null)
{
// user already exists in the site, cannot be added again
existingUsers.add(emailInIdAccount);
}
else
{
participant.name = u.getDisplayName();
participant.uniqname = emailInIdAccount;
pList.add(participant);
}
}
catch (UserNotDefinedException e)
{
// if the emailInIdAccount user is not in the system yet
participant.name = emailInIdAccount;
participant.uniqname = emailInIdAccount; // TODO: what would the UDS case this name to? -ggolden
pList.add(participant);
}
}
} // if
} //
} // emailInIdAccounts
boolean same_role = true;
if (params.getString("same_role") == null)
{
addAlert(state, rb.getString("java.roletype")+" ");
}
else
{
same_role = params.getString("same_role").equals("true")?true:false;
state.setAttribute("form_same_role", new Boolean(same_role));
}
if (state.getAttribute(STATE_MESSAGE) != null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
}
else
{
if (same_role)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "19");
}
else
{
state.setAttribute(STATE_TEMPLATE_INDEX, "20");
}
}
// remove duplicate or existing user from participant list
pList=removeDuplicateParticipants(pList, state);
state.setAttribute(STATE_ADD_PARTICIPANTS, pList);
// if the add participant list is empty after above removal, stay in the current page
if (pList.size() == 0)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
}
// add alert for attempting to add existing site user(s)
if (!existingUsers.isEmpty())
{
int count = 0;
String accounts = "";
for (Iterator eIterator = existingUsers.iterator();eIterator.hasNext();)
{
if (count == 0)
{
accounts = (String) eIterator.next();
}
else
{
accounts = accounts + ", " + (String) eIterator.next();
}
count++;
}
addAlert(state, rb.getString("add.existingpart.1") + accounts + rb.getString("add.existingpart.2"));
}
return;
} // checkAddParticipant
private Vector removeDuplicateParticipants(List pList, SessionState state)
{
// check the uniqness of list member
Set s = new HashSet();
Set uniqnameSet = new HashSet();
Vector rv = new Vector();
for (int i = 0; i < pList.size(); i++)
{
Participant p = (Participant) pList.get(i);
if (!uniqnameSet.contains(p.getUniqname()))
{
// no entry for the account yet
rv.add(p);
uniqnameSet.add(p.getUniqname());
}
else
{
// found duplicates
s.add(p.getUniqname());
}
}
if (!s.isEmpty())
{
int count = 0;
String accounts = "";
for (Iterator i = s.iterator();i.hasNext();)
{
if (count == 0)
{
accounts = (String) i.next();
}
else
{
accounts = accounts + ", " + (String) i.next();
}
count++;
}
if (count == 1)
{
addAlert(state, rb.getString("add.duplicatedpart.single") + accounts + ".");
}
else
{
addAlert(state, rb.getString("add.duplicatedpart") + accounts + ".");
}
}
return rv;
}
public void doAdd_participant(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String siteTitle = getStateSite(state).getTitle();
String emailInIdAccountName = ServerConfigurationService.getString("emailInIdAccountName", "");
Hashtable selectedRoles = (Hashtable) state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
boolean notify = false;
if (state.getAttribute("form_selectedNotify") != null)
{
notify = ((Boolean) state.getAttribute("form_selectedNotify")).booleanValue();
}
boolean same_role = ((Boolean) state.getAttribute("form_same_role")).booleanValue();
Hashtable eIdRoles = new Hashtable();
List addParticipantList = (List) state.getAttribute(STATE_ADD_PARTICIPANTS);
for (int i = 0; i < addParticipantList.size(); i++)
{
Participant p = (Participant) addParticipantList.get(i);
String eId = p.getEid();
// role defaults to same role
String role = (String) state.getAttribute("form_selectedRole");
if (!same_role)
{
// if all added participants have different role
role = (String) selectedRoles.get(eId);
}
boolean noEmailInIdAccount = eId.indexOf(EMAIL_CHAR) == -1;
if(noEmailInIdAccount)
{
// if this is a noEmailInIdAccount
// update the hashtable
eIdRoles.put(eId, role);
}
else
{
// if this is an emailInIdAccount
try
{
UserDirectoryService.getUserByEid(eId);
}
catch (UserNotDefinedException e)
{
//if there is no such user yet, add the user
try
{
UserEdit uEdit = UserDirectoryService.addUser(null, eId);
//set email address
uEdit.setEmail(eId);
// set the guest user type
uEdit.setType("guest");
// set password to a positive random number
Random generator = new Random(System.currentTimeMillis());
Integer num = new Integer(generator.nextInt(Integer.MAX_VALUE));
if (num.intValue() < 0) num = new Integer(num.intValue() *-1);
String pw = num.toString();
uEdit.setPassword(pw);
// and save
UserDirectoryService.commitEdit(uEdit);
boolean notifyNewUserEmail = (ServerConfigurationService.getString("notifyNewUserEmail", Boolean.TRUE.toString())).equalsIgnoreCase(Boolean.TRUE.toString());
if (notifyNewUserEmail)
{
notifyNewUserEmail(uEdit.getEid(), uEdit.getEmail(), pw, siteTitle);
}
}
catch(UserIdInvalidException ee)
{
addAlert(state, emailInIdAccountName + " id " + eId + " "+rb.getString("java.isinval") );
M_log.warn(this + " UserDirectoryService addUser exception " + e.getMessage());
}
catch(UserAlreadyDefinedException ee)
{
addAlert(state, "The " + emailInIdAccountName + " " + eId + " " + rb.getString("java.beenused"));
M_log.warn(this + " UserDirectoryService addUser exception " + e.getMessage());
}
catch(UserPermissionException ee)
{
addAlert(state, rb.getString("java.haveadd")+ " " + eId);
M_log.warn(this + " UserDirectoryService addUser exception " + e.getMessage());
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
eIdRoles.put(eId, role);
}
}
}
// batch add and updates the successful added list
List addedParticipantEIds = addUsersRealm(state, eIdRoles, notify, false);
// update the not added user list
String notAddedNoEmailInIdAccounts = null;
String notAddedEmailInIdAccounts = null;
for (Iterator iEIds = eIdRoles.keySet().iterator(); iEIds.hasNext();)
{
String iEId = (String) iEIds.next();
if (!addedParticipantEIds.contains(iEId))
{
if (iEId.indexOf(EMAIL_CHAR) == -1)
{
// no email in eid
notAddedNoEmailInIdAccounts = notAddedNoEmailInIdAccounts.concat(iEId + "\n");
}
else
{
// email in eid
notAddedEmailInIdAccounts = notAddedEmailInIdAccounts.concat(iEId + "\n");
}
}
}
if (addedParticipantEIds.size() != 0 && (notAddedNoEmailInIdAccounts != null || notAddedEmailInIdAccounts != null))
{
// at lease one noEmailInIdAccount account or an emailInIdAccount account added, and there are also failures
addAlert(state, rb.getString("java.allusers"));
}
if (notAddedNoEmailInIdAccounts == null && notAddedEmailInIdAccounts == null)
{
// all account has been added successfully
removeAddParticipantContext(state);
}
else
{
state.setAttribute("noEmailInIdAccountValue", notAddedNoEmailInIdAccounts);
state.setAttribute("emailInIdAccountValue", notAddedEmailInIdAccounts);
}
if (state.getAttribute(STATE_MESSAGE) != null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "22");
}
else
{
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
return;
} // doAdd_participant
/**
* remove related state variable for adding participants
* @param state SessionState object
*/
private void removeAddParticipantContext(SessionState state)
{
// remove related state variables
state.removeAttribute("form_selectedRole");
state.removeAttribute("noEmailInIdAccountValue");
state.removeAttribute("emailInIdAccountValue");
state.removeAttribute("form_same_role");
state.removeAttribute("form_selectedNotify");
state.removeAttribute(STATE_ADD_PARTICIPANTS);
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
} // removeAddParticipantContext
/**
* Send an email to newly added user informing password
* @param newEmailInIdAccount
* @param emailId
* @param userName
* @param siteTitle
*/
private void notifyNewUserEmail(String userName, String newUserEmail, String newUserPassword, String siteTitle)
{
String from = ServerConfigurationService.getString("setup.request", null);
if (from == null)
{
M_log.warn(this + " - no 'setup.request' in configuration");
from = "postmaster@".concat(ServerConfigurationService.getServerName());
}
String productionSiteName = ServerConfigurationService.getString("ui.service", "");
String productionSiteUrl = ServerConfigurationService.getPortalUrl();
String to = newUserEmail;
String headerTo = newUserEmail;
String replyTo = newUserEmail;
String message_subject = productionSiteName + " "+rb.getString("java.newusernoti");
String content = "";
if (from != null && newUserEmail !=null)
{
StringBuffer buf = new StringBuffer();
buf.setLength(0);
// email body
buf.append(userName + ":\n\n");
buf.append(rb.getString("java.addedto")+" " + productionSiteName + " ("+ productionSiteUrl + ") ");
buf.append(rb.getString("java.simpleby")+" ");
buf.append(UserDirectoryService.getCurrentUser().getDisplayName() + ". \n\n");
buf.append(rb.getString("java.passwordis1")+"\n" + newUserPassword + "\n\n");
buf.append(rb.getString("java.passwordis2")+ "\n\n");
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo, replyTo, null);
}
} // notifyNewUserEmail
/**
* send email notification to added participant
*/
private void notifyAddedParticipant(boolean newEmailInIdAccount, String emailId, String userName, String siteTitle)
{
String from = ServerConfigurationService.getString("setup.request", null);
if (from == null)
{
M_log.warn(this + " - no 'setup.request' in configuration");
}
else
{
String productionSiteName = ServerConfigurationService.getString("ui.service", "");
String productionSiteUrl = ServerConfigurationService.getPortalUrl();
String emailInIdAccountUrl = ServerConfigurationService.getString("emailInIdAccount.url", null);
String to = emailId;
String headerTo = emailId;
String replyTo = emailId;
String message_subject = productionSiteName + " "+rb.getString("java.sitenoti");
String content = "";
StringBuffer buf = new StringBuffer();
buf.setLength(0);
// email body differs between newly added emailInIdAccount account and other users
buf.append(userName + ":\n\n");
buf.append(rb.getString("java.following")+" " + productionSiteName + " "+rb.getString("java.simplesite")+ "\n");
buf.append(siteTitle + "\n");
buf.append(rb.getString("java.simpleby")+" ");
buf.append(UserDirectoryService.getCurrentUser().getDisplayName() + ". \n\n");
if (newEmailInIdAccount)
{
buf.append(ServerConfigurationService.getString("emailInIdAccountInstru", "") + "\n");
if (emailInIdAccountUrl != null)
{
buf.append(rb.getString("java.togeta1") +"\n" + emailInIdAccountUrl + "\n");
buf.append(rb.getString("java.togeta2")+"\n\n");
}
buf.append(rb.getString("java.once")+" " + productionSiteName + ": \n");
buf.append(rb.getString("java.loginhow1")+" " + productionSiteName + ": " + productionSiteUrl + "\n");
buf.append(rb.getString("java.loginhow2")+"\n");
buf.append(rb.getString("java.loginhow3")+"\n");
}
else
{
buf.append(rb.getString("java.tolog")+"\n");
buf.append(rb.getString("java.loginhow1")+" " + productionSiteName + ": " + productionSiteUrl + "\n");
buf.append(rb.getString("java.loginhow2")+"\n");
buf.append(rb.getString("java.loginhow3u")+"\n");
}
buf.append(rb.getString("java.tabscreen"));
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo, replyTo, null);
} // if
} // notifyAddedParticipant
/*
* Given a list of user eids, add users to realm
* If the user account does not exist yet inside the user directory, assign role to it
* @return A list of eids for successfully added users
*/
private List addUsersRealm (SessionState state, Hashtable eIdRoles, boolean notify, boolean emailInIdAccount)
{
// return the list of user eids for successfully added user
List addedUserEIds = new Vector();
StringBuffer message = new StringBuffer();
if (eIdRoles != null && !eIdRoles.isEmpty())
{
// get the current site
Site sEdit = getStateSite(state);
if (sEdit != null)
{
// get realm object
String realmId = sEdit.getReference();
try
{
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId);
for (Iterator eIds = eIdRoles.keySet().iterator(); eIds.hasNext();)
{
String eId = (String) eIds.next();
String role = (String) eIdRoles.get(eId);
try
{
User user = UserDirectoryService.getUserByEid(eId);
if (AuthzGroupService.allowUpdate(realmId) || SiteService.allowUpdateSiteMembership(sEdit.getId()))
{
realmEdit.addMember(user.getId(), role, true, false);
addedUserEIds.add(eId);
// send notification
if (notify)
{
String emailId = user.getEmail();
String userName = user.getDisplayName();
// send notification email
notifyAddedParticipant(emailInIdAccount, emailId, userName, sEdit.getTitle());
}
}
}
catch (UserNotDefinedException e)
{
message.append(eId + " " +rb.getString("java.account")+" \n");
} // try
} // for
try
{
AuthzGroupService.save(realmEdit);
}
catch (GroupNotDefinedException ee)
{
message.append(rb.getString("java.realm") + realmId);
}
catch (AuthzPermissionException ee)
{
message.append(rb.getString("java.permeditsite") + realmId);
}
}
catch (GroupNotDefinedException eee)
{
message.append(rb.getString("java.realm") + realmId);
}
}
}
if (message.length() != 0)
{
addAlert(state, message.toString());
} // if
return addedUserEIds;
} // addUsersRealm
/**
* addNewSite is called when the site has enough information to create a new site
*
*/
private void addNewSite(ParameterParser params, SessionState state)
{
if(getStateSite(state) != null)
{
// There is a Site in state already, so use it rather than creating a new Site
return;
}
//If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
String id = StringUtil.trimToNull(siteInfo.getSiteId());
if (id == null)
{
//get id
id = IdManager.createUuid();
siteInfo.site_id = id;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (state.getAttribute(STATE_MESSAGE) == null)
{
try
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
Site site = SiteService.addSite(id, siteInfo.site_type);
String title = StringUtil.trimToNull(siteInfo.title);
String description = siteInfo.description;
setAppearance(state, site, siteInfo.iconUrl);
site.setDescription(description);
if (title != null)
{
site.setTitle(title);
}
site.setType(siteInfo.site_type);
ResourcePropertiesEdit rp = site.getPropertiesEdit();
site.setShortDescription(siteInfo.short_description);
site.setPubView(siteInfo.include);
site.setJoinable(siteInfo.joinable);
site.setJoinerRole(siteInfo.joinerRole);
site.setPublished(siteInfo.published);
// site contact information
rp.addProperty(PROP_SITE_CONTACT_NAME, siteInfo.site_contact_name);
rp.addProperty(PROP_SITE_CONTACT_EMAIL, siteInfo.site_contact_email);
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
//commit newly added site in order to enable related realm
commitSite(site);
}
catch (IdUsedException e)
{
addAlert(state, rb.getString("java.sitewithid")+" " + id + " "+rb.getString("java.exists"));
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("template-index"));
return;
}
catch (IdInvalidException e)
{
addAlert(state, rb.getString("java.thesiteid")+" " + id + " "+rb.getString("java.notvalid"));
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("template-index"));
return;
}
catch (PermissionException e)
{
addAlert(state, rb.getString("java.permission")+" " + id +".");
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("template-index"));
return;
}
}
} // addNewSite
/**
* Use the AuthzGroup Provider Id to build a Site tab
* @throws IdUnusedException
*
*/
private String getCourseTab(SessionState state, String id)
{
StringBuffer tab = new StringBuffer();
try
{
String courseName = CourseManagementService.getCourseName(id);
if (courseName != null && courseName.length() > 0)
{
tab.append(courseName);
return appendTermInSiteTitle(state, tab.toString());
}
}
catch (IdUnusedException ignore)
{
}
return "";
}// getCourseTab
private String appendTermInSiteTitle (SessionState state, String title)
{
//append term information into the tab in order to differenciate same course taught in different terms
if (state.getAttribute(STATE_TERM_SELECTED) != null)
{
Term t = (Term) state.getAttribute(STATE_TERM_SELECTED);
if (StringUtil.trimToNull(t.getListAbbreviation()) != null)
{
// use term abbreviation, if any
title = title.concat(" ").concat(t.getListAbbreviation());
}
else
{
// use term id
title = title.concat(" ").concat(t.getId());
}
}
return title;
} // appendTermInSiteTitle
/**
* %%% legacy properties, to be cleaned up
*
*/
private void sitePropertiesIntoState (SessionState state)
{
try
{
Site site = getStateSite(state);
SiteInfo siteInfo = new SiteInfo();
// set from site attributes
siteInfo.title = site.getTitle();
siteInfo.description = site.getDescription();
siteInfo.iconUrl = site.getIconUrl();
siteInfo.infoUrl = site.getInfoUrl();
siteInfo.joinable = site.isJoinable();
siteInfo.joinerRole = site.getJoinerRole();
siteInfo.published = site.isPublished();
siteInfo.include = site.isPubView();
siteInfo.short_description = site.getShortDescription();
state.setAttribute(STATE_SITE_TYPE, siteInfo.site_type);
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
catch (Exception e)
{
M_log.warn("SiteAction.sitePropertiesIntoState " + e.getMessage());
}
} // sitePropertiesIntoState
/**
* pageMatchesPattern returns true if a SitePage matches a WorkSite Setup pattern
*
*/
private boolean pageMatchesPattern (SessionState state, SitePage page)
{
List pageToolList = page.getTools();
// if no tools on the page, return false
if(pageToolList == null || pageToolList.size() == 0) { return false; }
//for the case where the page has one tool
ToolConfiguration toolConfiguration = (ToolConfiguration)pageToolList.get(0);
//don't compare tool properties, which may be changed using Options
List toolList = new Vector();
int count = pageToolList.size();
boolean match = false;
//check Worksite Setup Home pattern
if(page.getTitle()!=null && page.getTitle().equals(rb.getString("java.home")))
{
return true;
} // Home
else if(page.getTitle() != null && page.getTitle().equals(rb.getString("java.help")))
{
//if the count of tools on the page doesn't match, return false
if(count != 1) { return false;}
//if the page layout doesn't match, return false
if(page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return false; }
//if tooId isn't sakai.contactSupport, return false
if(!(toolConfiguration.getTool().getId()).equals("sakai.contactSupport")) { return false; }
return true;
} // Help
else if(page.getTitle() != null && page.getTitle().equals("Chat"))
{
//if the count of tools on the page doesn't match, return false
if(count != 1) { return false;}
//if the page layout doesn't match, return false
if(page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return false; }
//if the tool doesn't match, return false
if(!(toolConfiguration.getTool().getId()).equals("sakai.chat")) { return false; }
//if the channel doesn't match value for main channel, return false
String channel = toolConfiguration.getPlacementConfig().getProperty("channel");
if(channel == null) { return false; }
if(!(channel.equals(NULL_STRING))) { return false; }
return true;
} // Chat
else
{
//if the count of tools on the page doesn't match, return false
if(count != 1) { return false;}
//if the page layout doesn't match, return false
if(page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return false; }
toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
if(pageToolList != null || pageToolList.size() != 0)
{
//if tool attributes don't match, return false
match = false;
for (ListIterator i = toolList.listIterator(); i.hasNext(); )
{
MyTool tool = (MyTool) i.next();
if(toolConfiguration.getTitle() != null)
{
if(toolConfiguration.getTool() != null && toolConfiguration.getTool().getId().indexOf(tool.getId()) != -1) { match = true; }
}
}
if (!match) { return false; }
}
} // Others
return true;
} // pageMatchesPattern
/**
* siteToolsIntoState is the replacement for siteToolsIntoState_
* Make a list of pages and tools that match WorkSite Setup configurations into state
*/
private void siteToolsIntoState (SessionState state)
{
String wSetupTool = NULL_STRING;
List wSetupPageList = new Vector();
Site site = getStateSite(state);
List pageList = site.getPages();
//Put up tool lists filtered by category
String type = site.getType();
if (type == null)
{
if (SiteService.isUserSite(site.getId()))
{
type = "myworkspace";
}
else if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null)
{
// for those sites without type, use the tool set for default site type
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
}
List toolRegList = new Vector();
if (type != null)
{
Set categories = new HashSet();
categories.add(type);
Set toolRegistrations = ToolManager.findTools(categories, null);
SortedIterator i = new SortedIterator(toolRegistrations.iterator(), new ToolComparator());
for (;i.hasNext();)
{
// form a new Tool
Tool tr = (Tool) i.next();
MyTool newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = tr.getId();
newTool.description = tr.getDescription();
toolRegList.add(newTool);
}
}
if (toolRegList.size() == 0 && state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null)
{
// use default site type and try getting tools again
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
Set nCategories = new HashSet();
nCategories.add(type);
Set toolRegistrations = ToolManager.findTools(nCategories, null);
SortedIterator i = new SortedIterator(toolRegistrations.iterator(), new ToolComparator());
for (;i.hasNext();)
{
// form a new Tool
Tool tr = (Tool) i.next();
MyTool newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = tr.getId();
newTool.description = tr.getDescription();
toolRegList.add(newTool);
}
}
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolRegList);
state.setAttribute(STATE_SITE_TYPE, type);
if (type == null)
{
M_log.warn(this + ": - unknown STATE_SITE_TYPE");
}
else
{
state.setAttribute(STATE_SITE_TYPE, type);
}
boolean check_home = false;
boolean hasNews = false;
boolean hasWebContent = false;
int newsToolNum = 0;
int wcToolNum = 0;
Hashtable newsTitles = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcUrls = new Hashtable();
Vector idSelected = new Vector();
if (!((pageList == null) || (pageList.size() == 0)))
{
for (ListIterator i = pageList.listIterator(); i.hasNext(); )
{
SitePage page = (SitePage) i.next();
//collect the pages consistent with Worksite Setup patterns
if(pageMatchesPattern(state, page))
{
if(page.getTitle().equals(rb.getString("java.home")))
{
wSetupTool = HOME_TOOL_ID;
check_home = true;
}
else
{
List pageToolList = page.getTools();
wSetupTool = ((ToolConfiguration)pageToolList.get(0)).getTool().getId();
if (wSetupTool.indexOf("sakai.news") != -1)
{
String newsToolId = page.getId() + wSetupTool;
idSelected.add(newsToolId);
newsTitles.put(newsToolId, page.getTitle());
String channelUrl = ((ToolConfiguration)pageToolList.get(0)).getPlacementConfig().getProperty("channel-url");
newsUrls.put(newsToolId, channelUrl!=null?channelUrl:"");
newsToolNum++;
// insert the News tool into the list
hasNews = false;
int j = 0;
MyTool newTool = new MyTool();
newTool.title = NEWS_DEFAULT_TITLE;
newTool.id = newsToolId;
newTool.selected = false;
for (;j< toolRegList.size() && !hasNews; j++)
{
MyTool t = (MyTool) toolRegList.get(j);
if (t.getId().equals("sakai.news"))
{
hasNews = true;
newTool.description = t.getDescription();
}
}
if (hasNews)
{
toolRegList.add(j-1, newTool);
}
else
{
toolRegList.add(newTool);
}
}
else if ((wSetupTool).indexOf("sakai.iframe") != -1)
{
String wcToolId = page.getId() + wSetupTool;
idSelected.add(wcToolId);
wcTitles.put(wcToolId, page.getTitle());
String wcUrl = StringUtil.trimToNull(((ToolConfiguration)pageToolList.get(0)).getPlacementConfig().getProperty("source"));
if (wcUrl == null)
{
// if there is no source URL, seed it with the Web Content default URL
wcUrl = WEB_CONTENT_DEFAULT_URL;
}
wcUrls.put(wcToolId, wcUrl);
wcToolNum++;
MyTool newTool = new MyTool();
newTool.title = WEB_CONTENT_DEFAULT_TITLE;
newTool.id = wcToolId;
newTool.selected = false;
hasWebContent = false;
int j = 0;
for (;j< toolRegList.size() && !hasWebContent; j++)
{
MyTool t = (MyTool) toolRegList.get(j);
if (t.getId().equals("sakai.iframe"))
{
hasWebContent = true;
newTool.description = t.getDescription();
}
}
if (hasWebContent)
{
toolRegList.add(j-1, newTool);
}
else
{
toolRegList.add(newTool);
}
}
/*else if(wSetupTool.indexOf("sakai.syllabus") != -1)
{
//add only one instance of tool per site
if (!(idSelected.contains(wSetupTool)))
{
idSelected.add(wSetupTool);
}
}*/
else
{
idSelected.add(wSetupTool);
}
}
WorksiteSetupPage wSetupPage = new WorksiteSetupPage();
wSetupPage.pageId = page.getId();
wSetupPage.pageTitle = page.getTitle();
wSetupPage.toolId = wSetupTool;
wSetupPageList.add(wSetupPage);
}
}
}
newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE);
newsUrls.put("sakai.news", NEWS_DEFAULT_URL);
wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE);
wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL);
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolRegList);
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(check_home));
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idSelected); // List of ToolRegistration toolId's
state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST, idSelected); // List of ToolRegistration toolId's
state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME, Boolean.valueOf(check_home));
state.setAttribute(STATE_NEWS_TITLES, newsTitles);
state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles);
state.setAttribute(STATE_NEWS_URLS, newsUrls);
state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls);
state.setAttribute(STATE_WORKSITE_SETUP_PAGE_LIST, wSetupPageList);
} //siteToolsIntoState
/**
* reset the state variables used in edit tools mode
* @state The SessionState object
*/
private void removeEditToolState(SessionState state)
{
state.removeAttribute(STATE_TOOL_HOME_SELECTED);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // List of ToolRegistration toolId's
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // List of ToolRegistration toolId's
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_NEWS_TITLES);
state.removeAttribute(STATE_NEWS_URLS);
state.removeAttribute(STATE_WEB_CONTENT_TITLES);
state.removeAttribute(STATE_WEB_CONTENT_URLS);
state.removeAttribute(STATE_WORKSITE_SETUP_PAGE_LIST);
}
private List orderToolIds(SessionState state, String type, List toolIdList)
{
List rv = new Vector();
if (state.getAttribute(STATE_TOOL_HOME_SELECTED) != null
&& ((Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED)).booleanValue())
{
rv.add(HOME_TOOL_ID);
}
// look for null site type
if (type != null && toolIdList != null)
{
Set categories = new HashSet();
categories.add(type);
Set tools = ToolManager.findTools(categories, null);
SortedIterator i = new SortedIterator(tools.iterator(), new ToolComparator());
for (; i.hasNext(); )
{
String tool_id = ((Tool) i.next()).getId();
for (ListIterator j = toolIdList.listIterator(); j.hasNext(); )
{
String toolId = (String) j.next();
if(toolId.indexOf("assignment") != -1 && toolId.equals(tool_id)
|| toolId.indexOf("assignment") == -1 && toolId.indexOf(tool_id) != -1)
{
rv.add(toolId);
}
}
}
}
return rv;
} // orderToolIds
private void setupFormNamesAndConstants(SessionState state)
{
TimeBreakdown timeBreakdown = (TimeService.newTime ()).breakdownLocal ();
String mycopyright = COPYRIGHT_SYMBOL + " " + timeBreakdown.getYear () + ", " + UserDirectoryService.getCurrentUser().getDisplayName () + ". All Rights Reserved. ";
state.setAttribute (STATE_MY_COPYRIGHT, mycopyright);
state.setAttribute (STATE_SITE_INSTANCE_ID, null);
state.setAttribute (STATE_INITIALIZED, Boolean.TRUE.toString());
SiteInfo siteInfo = new SiteInfo();
Participant participant = new Participant();
participant.name = NULL_STRING;
participant.uniqname = NULL_STRING;
state.setAttribute(STATE_SITE_INFO, siteInfo);
state.setAttribute("form_participantToAdd", participant);
state.setAttribute(FORM_ADDITIONAL, NULL_STRING);
//legacy
state.setAttribute(FORM_HONORIFIC,"0");
state.setAttribute(FORM_REUSE, "0");
state.setAttribute(FORM_RELATED_CLASS, "0");
state.setAttribute(FORM_RELATED_PROJECT, "0");
state.setAttribute(FORM_INSTITUTION, "0");
//sundry form variables
state.setAttribute(FORM_PHONE,"");
state.setAttribute(FORM_EMAIL,"");
state.setAttribute(FORM_SUBJECT,"");
state.setAttribute(FORM_DESCRIPTION,"");
state.setAttribute(FORM_TITLE,"");
state.setAttribute(FORM_NAME,"");
state.setAttribute(FORM_SHORT_DESCRIPTION,"");
} // setupFormNamesAndConstants
/**
* Add these Unit affliates to sites in these
* Subject areas with Instructor role
*
*/
private void setupSubjectAffiliates(SessionState state)
{
Vector affiliates = new Vector();
List subjectList = new Vector();
List campusList = new Vector();
List uniqnameList = new Vector();
//get term information
if (ServerConfigurationService.getStrings("affiliatesubjects") != null)
{
subjectList = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("affiliatesubjects")));
}
if (ServerConfigurationService.getStrings("affiliatecampus") != null)
{
campusList = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("affiliatecampus")));
}
if (ServerConfigurationService.getStrings("affiliateuniqnames") != null)
{
uniqnameList = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("affiliateuniqnames")));
}
if (subjectList.size() > 0 && subjectList.size() == campusList.size() && subjectList.size() == uniqnameList.size())
{
for (int i=0; i < subjectList.size();i++)
{
String[] subjectFields = ((String) subjectList.get(i)).split(",");
String[] uniqnameFields = ((String) uniqnameList.get(i)).split(",");
String campus = (String) campusList.get(i);
for (int j=0; j < subjectFields.length; j++)
{
String subject = StringUtil.trimToZero(subjectFields[j]);
SubjectAffiliates affiliate = new SubjectAffiliates();
affiliate.setSubject(subject);
affiliate.setCampus(campus);
for (int k=0; k < uniqnameFields.length;k++)
{
affiliate.getUniqnames().add(StringUtil.trimToZero(uniqnameFields[k]));
}
affiliates.add(affiliate);
}
}
}
state.setAttribute(STATE_SUBJECT_AFFILIATES, affiliates);
} // setupSubjectAffiliates
/**
* setupSkins
*
*/
private void setupIcons(SessionState state)
{
List icons = new Vector();
String[] iconNames = null;
String[] iconUrls = null;
String[] iconSkins = null;
//get icon information
if (ServerConfigurationService.getStrings("iconNames") != null)
{
iconNames = ServerConfigurationService.getStrings("iconNames");
}
if (ServerConfigurationService.getStrings("iconUrls") != null)
{
iconUrls = ServerConfigurationService.getStrings("iconUrls");
}
if (ServerConfigurationService.getStrings("iconSkins") != null)
{
iconSkins = ServerConfigurationService.getStrings("iconSkins");
}
if ((iconNames != null) && (iconUrls != null) && (iconSkins != null) && (iconNames.length == iconUrls.length) && (iconNames.length == iconSkins.length))
{
for (int i = 0; i < iconNames.length; i++)
{
Icon s = new Icon(
StringUtil.trimToNull((String) iconNames[i]),
StringUtil.trimToNull((String) iconUrls[i]),
StringUtil.trimToNull((String) iconSkins[i]));
icons.add(s);
}
}
state.setAttribute(STATE_ICONS, icons);
}
private void setAppearance(SessionState state, Site edit, String iconUrl)
{
// set the icon
edit.setIconUrl(iconUrl);
if (iconUrl == null)
{
// this is the default case - no icon, no (default) skin
edit.setSkin(null);
return;
}
// if this icon is in the config appearance list, find a skin to set
List icons = (List) state.getAttribute(STATE_ICONS);
for (Iterator i = icons.iterator(); i.hasNext();)
{
Icon icon = (Icon) i.next();
if (!StringUtil.different(icon.getUrl(), iconUrl))
{
edit.setSkin(icon.getSkin());
return;
}
}
}
/**
* A dispatch funtion when selecting course features
*/
public void doAdd_features ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String option = params.getString("option");
if (option.equalsIgnoreCase("addNews"))
{
updateSelectedToolList(state, params, false);
insertTool(state, "sakai.news", STATE_NEWS_TITLES, NEWS_DEFAULT_TITLE, STATE_NEWS_URLS, NEWS_DEFAULT_URL, Integer.parseInt(params.getString("newsNum")));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
else if (option.equalsIgnoreCase("addWC"))
{
updateSelectedToolList(state, params, false);
insertTool(state, "sakai.iframe", STATE_WEB_CONTENT_TITLES, WEB_CONTENT_DEFAULT_TITLE, STATE_WEB_CONTENT_URLS, WEB_CONTENT_DEFAULT_URL, Integer.parseInt(params.getString("wcNum")));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
else if (option.equalsIgnoreCase("import"))
{
// import or not
updateSelectedToolList(state, params, false);
String importSites = params.getString("import");
if (importSites != null && importSites.equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.setAttribute(STATE_IMPORT, Boolean.TRUE);
if (importSites.equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.removeAttribute(STATE_IMPORT);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
}
}
else
{
state.removeAttribute(STATE_IMPORT);
}
}
else if (option.equalsIgnoreCase("continue"))
{
// continue
doContinue(data);
}
else if (option.equalsIgnoreCase("back"))
{
// back
doBack(data);
}
else if (option.equalsIgnoreCase("cancel"))
{
// cancel
doCancel_create(data);
}
} // doAdd_features
/**
* update the selected tool list
* @param params The ParameterParser object
* @param verifyData Need to verify input data or not
*/
private void updateSelectedToolList (SessionState state, ParameterParser params, boolean verifyData)
{
List selectedTools = new ArrayList(Arrays.asList(params.getStrings ("selectedTools")));
Hashtable titles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
Hashtable urls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
Hashtable wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES);
Hashtable wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS);
boolean has_home = false;
String emailId = null;
for (int i = 0; i < selectedTools.size(); i++)
{
String id = (String) selectedTools.get(i);
if (id.indexOf("sakai.news") != -1)
{
String title = StringUtil.trimToNull(params.getString("titlefor" + id));
if (title == null)
{
// if there is no input, make the title for news tool default to NEWS_DEFAULT_TITLE
title = NEWS_DEFAULT_TITLE;
}
titles.put(id, title);
String url = StringUtil.trimToNull(params.getString("urlfor" + id));
if (url == null)
{
// if there is no input, make the title for news tool default to NEWS_DEFAULT_URL
url = NEWS_DEFAULT_URL;
}
urls.put(id, url);
try
{
new URL(url);
}
catch (MalformedURLException e)
{
addAlert(state, rb.getString("java.invurl")+" " + url + ". ");
}
}
else if (id.indexOf("sakai.iframe") != -1)
{
String wcTitle = StringUtil.trimToNull(params.getString("titlefor" + id));
if (wcTitle == null)
{
// if there is no input, make the title for Web Content tool default to WEB_CONTENT_DEFAULT_TITLE
wcTitle = WEB_CONTENT_DEFAULT_TITLE;
}
wcTitles.put(id, wcTitle);
String wcUrl = StringUtil.trimToNull(params.getString("urlfor" + id));
if (wcUrl == null)
{
// if there is no input, make the title for Web Content tool default to WEB_CONTENT_DEFAULT_URL
wcUrl = WEB_CONTENT_DEFAULT_URL;
}
else
{
if ((wcUrl.length() > 0) && (!wcUrl.startsWith("/")) && (wcUrl.indexOf("://") == -1))
{
wcUrl = "http://" + wcUrl;
}
}
wcUrls.put(id, wcUrl);
}
else if (id.equalsIgnoreCase(HOME_TOOL_ID))
{
has_home = true;
}
else if (id.equalsIgnoreCase("sakai.mailbox"))
{
// if Email archive tool is selected, check the email alias
emailId = StringUtil.trimToNull(params.getString("emailId"));
if(verifyData)
{
if (emailId == null)
{
addAlert(state, rb.getString("java.emailarchive")+" ");
}
else
{
if (!Validator.checkEmailLocal(emailId))
{
addAlert(state, rb.getString("java.theemail"));
}
else
{
//check to see whether the alias has been used by other sites
try
{
String target = AliasService.getTarget(emailId);
if (target != null)
{
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null)
{
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
String channelReference = mailArchiveChannelReference(siteId);
if (!target.equals(channelReference))
{
// the email alias is not used by current site
addAlert(state, rb.getString("java.emailinuse")+" ");
}
}
else
{
addAlert(state, rb.getString("java.emailinuse")+" ");
}
}
}
catch (IdUnusedException ee){}
}
}
}
}
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(has_home));
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, emailId);
state.setAttribute(STATE_NEWS_TITLES, titles);
state.setAttribute(STATE_NEWS_URLS, urls);
state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles);
state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls);
} // updateSelectedToolList
/**
* find the tool in the tool list and insert another tool instance to the list
* @param state SessionState object
* @param toolId The id for the inserted tool
* @param stateTitlesVariable The titles
* @param defaultTitle The default title for the inserted tool
* @param stateUrlsVariable The urls
* @param defaultUrl The default url for the inserted tool
* @param insertTimes How many tools need to be inserted
*/
private void insertTool(SessionState state, String toolId, String stateTitlesVariable, String defaultTitle, String stateUrlsVariable, String defaultUrl, int insertTimes)
{
//the list of available tools
List toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
int toolListedTimes = 0;
int index = 0;
int insertIndex = 0;
while ( index < toolList.size())
{
MyTool tListed = (MyTool) toolList.get(index);
if (tListed.getId().indexOf(toolId) != -1 )
{
toolListedTimes++;
}
if (toolListedTimes > 0 && insertIndex == 0)
{
// update the insert index
insertIndex = index;
}
index ++;
}
List toolSelected = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// the titles
Hashtable titles = (Hashtable) state.getAttribute(stateTitlesVariable);
if (titles == null)
{
titles = new Hashtable();
}
// the urls
Hashtable urls = (Hashtable) state.getAttribute(stateUrlsVariable);
if (urls == null)
{
urls = new Hashtable();
}
// insert multiple tools
for (int i = 0; i < insertTimes; i++)
{
toolListedTimes = toolListedTimes + i;
toolSelected.add(toolId + toolListedTimes);
// We need to insert a specific tool entry only if all the specific tool entries have been selected
MyTool newTool = new MyTool();
newTool.title = defaultTitle;
newTool.id = toolId + toolListedTimes;
toolList.add(insertIndex, newTool);
titles.put(newTool.id, defaultTitle);
urls.put(newTool.id, defaultUrl);
}
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolList);
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolSelected);
state.setAttribute(stateTitlesVariable, titles);
state.setAttribute(stateUrlsVariable, urls);
} // insertTool
/**
*
* set selected participant role Hashtable
*/
private void setSelectedParticipantRoles(SessionState state)
{
List selectedUserIds = (List) state.getAttribute(STATE_SELECTED_USER_LIST);
List participantList = (List) state.getAttribute(STATE_PARTICIPANT_LIST);
List selectedParticipantList = new Vector();
Hashtable selectedParticipantRoles = new Hashtable();
if(!selectedUserIds.isEmpty() && participantList != null)
{
for (int i = 0; i < participantList.size(); i++)
{
String id= "";
Object o = (Object) participantList.get(i);
if (o.getClass().equals(Participant.class))
{
// get participant roles
id = ((Participant) o).getUniqname();
selectedParticipantRoles.put(id, ((Participant) o).getRole());
}
else if (o.getClass().equals(Student.class))
{
// get participant from roster role
id = ((Student) o).getUniqname();
selectedParticipantRoles.put(id, ((Student)o).getRole());
}
if (selectedUserIds.contains(id))
{
selectedParticipantList.add(participantList.get(i));
}
}
}
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, selectedParticipantRoles);
state.setAttribute(STATE_SELECTED_PARTICIPANTS, selectedParticipantList);
} // setSelectedParticipantRoles
/**
* the SiteComparator class
*/
private class SiteComparator
implements Comparator
{
/**
* the criteria
*/
String m_criterion = null;
String m_asc = null;
/**
* constructor
* @param criteria The sort criteria string
* @param asc The sort order string. TRUE_STRING if ascending; "false" otherwise.
*/
public SiteComparator (String criterion, String asc)
{
m_criterion = criterion;
m_asc = asc;
} // constructor
/**
* implementing the Comparator compare function
* @param o1 The first object
* @param o2 The second object
* @return The compare result. 1 is o1 < o2; -1 otherwise
*/
public int compare ( Object o1, Object o2)
{
int result = -1;
if(m_criterion==null) m_criterion = SORTED_BY_TITLE;
/************* for sorting site list *******************/
if (m_criterion.equals (SORTED_BY_TITLE))
{
// sorted by the worksite title
String s1 = ((Site) o1).getTitle();
String s2 = ((Site) o2).getTitle();
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_DESCRIPTION))
{
// sorted by the site short description
String s1 = ((Site) o1).getShortDescription();
String s2 = ((Site) o2).getShortDescription();
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_TYPE))
{
// sorted by the site type
String s1 = ((Site) o1).getType();
String s2 = ((Site) o2).getType();
result = compareString(s1, s2);
}
else if (m_criterion.equals (SortType.CREATED_BY_ASC.toString()))
{
// sorted by the site creator
String s1 = ((Site) o1).getProperties().getProperty("CHEF:creator");
String s2 = ((Site) o2).getProperties().getProperty("CHEF:creator");
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_STATUS))
{
// sort by the status, published or unpublished
int i1 = ((Site)o1).isPublished() ? 1 : 0;
int i2 = ((Site)o2).isPublished() ? 1 : 0;
if (i1 > i2)
{
result = 1;
}
else
{
result = -1;
}
}
else if (m_criterion.equals (SORTED_BY_JOINABLE))
{
// sort by whether the site is joinable or not
boolean b1 = ((Site)o1).isJoinable();
boolean b2 = ((Site)o2).isJoinable();
if (b1 == b2)
{
result = 0;
}
else if (b1 == true)
{
result = 1;
}
else
{
result = -1;
}
}
else if (m_criterion.equals (SORTED_BY_PARTICIPANT_NAME))
{
// sort by whether the site is joinable or not
String s1 = null;
if (o1.getClass().equals(Participant.class))
{
s1 = ((Participant) o1).getName();
}
String s2 = null;
if (o2.getClass().equals(Participant.class))
{
s2 = ((Participant) o2).getName();
}
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_PARTICIPANT_UNIQNAME))
{
// sort by whether the site is joinable or not
String s1 = null;
if (o1.getClass().equals(Participant.class))
{
s1 = ((Participant) o1).getUniqname();
}
String s2 = null;
if (o2.getClass().equals(Participant.class))
{
s2 = ((Participant) o2).getUniqname();
}
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_PARTICIPANT_ROLE))
{
String s1 = "";
if (o1.getClass().equals(Participant.class))
{
s1 = ((Participant) o1).getRole();
}
String s2 = "";
if (o2.getClass().equals(Participant.class))
{
s2 = ((Participant) o2).getRole();
}
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_PARTICIPANT_COURSE))
{
// sort by whether the site is joinable or not
String s1 = null;
if (o1.getClass().equals(Participant.class))
{
s1 = ((Participant) o1).getCourse();
}
String s2 = null;
if (o2.getClass().equals(Participant.class))
{
s2 = ((Participant) o2).getCourse();
}
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_PARTICIPANT_ID))
{
String s1 = null;
if (o1.getClass().equals(Participant.class))
{
s1 = ((Participant) o1).getRegId();
}
String s2 = null;
if (o2.getClass().equals(Participant.class))
{
s2 = ((Participant) o2).getRegId();
}
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_PARTICIPANT_CREDITS))
{
String s1 = null;
if (o1.getClass().equals(Participant.class))
{
s1 = ((Participant) o1).getCredits();
}
String s2 = null;
if (o2.getClass().equals(Participant.class))
{
s2 = ((Participant) o2).getCredits();
}
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_CREATION_DATE))
{
// sort by the site's creation date
Time t1 = null;
Time t2 = null;
// get the times
try
{
t1 = ((Site)o1).getProperties().getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
}
catch (EntityPropertyNotDefinedException e)
{
}
catch (EntityPropertyTypeException e)
{
}
try
{
t2 = ((Site)o2).getProperties().getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
}
catch (EntityPropertyNotDefinedException e)
{
}
catch (EntityPropertyTypeException e)
{
}
if (t1==null)
{
result = -1;
}
else if (t2==null)
{
result = 1;
}
else if (t1.before (t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criterion.equals (rb.getString("group.title")))
{
// sorted by the group title
String s1 = ((Group) o1).getTitle();
String s2 = ((Group) o2).getTitle();
result = compareString(s1, s2);
}
else if (m_criterion.equals (rb.getString("group.number")))
{
// sorted by the group title
int n1 = ((Group) o1).getMembers().size();
int n2 = ((Group) o2).getMembers().size();
result = (n1 > n2)?1:-1;
}
else if (m_criterion.equals (SORTED_BY_MEMBER_NAME))
{
// sorted by the member name
String s1 = null;
String s2 = null;
try
{
s1 = UserDirectoryService.getUser(((Member) o1).getUserId()).getSortName();
}
catch(Exception ignore)
{
}
try
{
s2 = UserDirectoryService.getUser(((Member) o2).getUserId()).getSortName();
}
catch (Exception ignore)
{
}
result = compareString(s1, s2);
}
if(m_asc == null) m_asc = Boolean.TRUE.toString ();
// sort ascending or descending
if (m_asc.equals (Boolean.FALSE.toString ()))
{
result = -result;
}
return result;
} // compare
private int compareString(String s1, String s2) {
int result;
if (s1==null && s2==null)
{
result = 0;
}
else if (s2==null)
{
result = 1;
}
else if (s1==null)
{
result = -1;
}
else
{
result = s1.compareToIgnoreCase (s2);
}
return result;
}
} //SiteComparator
private class ToolComparator
implements Comparator
{
/**
* implementing the Comparator compare function
* @param o1 The first object
* @param o2 The second object
* @return The compare result. 1 is o1 < o2; 0 is o1.equals(o2); -1 otherwise
*/
public int compare ( Object o1, Object o2)
{
try
{
return ((Tool) o1).getTitle().compareTo(((Tool) o2).getTitle());
}
catch (Exception e)
{
}
return -1;
} // compare
} //ToolComparator
public class Icon
{
protected String m_name = null;
protected String m_url = null;
protected String m_skin = null;
public Icon(String name, String url, String skin)
{
m_name = name;
m_url = url;
m_skin = skin;
}
public String getName() { return m_name; }
public String getUrl() { return m_url; }
public String getSkin() { return m_skin; }
}
// a utility class for form select options
public class IdAndText
{
public int id;
public String text;
public int getId() { return id;}
public String getText() { return text;}
} // IdAndText
// a utility class for working with ToolConfigurations and ToolRegistrations
// %%% convert featureList from IdAndText to Tool so getFeatures item.id = chosen-feature.id is a direct mapping of data
public class MyTool
{
public String id = NULL_STRING;
public String title = NULL_STRING;
public String description = NULL_STRING;
public boolean selected = false;
public String getId() { return id; }
public String getTitle() { return title; }
public String getDescription() { return description; }
public boolean getSelected() { return selected; }
}
/*
* WorksiteSetupPage is a utility class for working with site pages configured by Worksite Setup
*
*/
public class WorksiteSetupPage
{
public String pageId = NULL_STRING;
public String pageTitle = NULL_STRING;
public String toolId = NULL_STRING;
public String getPageId() { return pageId; }
public String getPageTitle() { return pageTitle; }
public String getToolId() { return toolId; }
} // WorksiteSetupPage
/**
* Participant in site access roles
*
*/
public class Participant
{
public String name = NULL_STRING;
// Note: uniqname is really a user ID
public String uniqname = NULL_STRING;
public String role = NULL_STRING;
/** role from provider */
public String providerRole = NULL_STRING;
/** The member credits */
protected String credits = NULL_STRING;
/** The course */
public String course = NULL_STRING;
/** The section */
public String section = NULL_STRING;
/** The regestration id */
public String regId = NULL_STRING;
/** removeable if not from provider */
public boolean removeable = true;
public String getName() {return name; }
public String getUniqname() {return uniqname; }
public String getRole() { return role; } // cast to Role
public String getProviderRole() { return providerRole; }
public boolean isRemoveable(){return removeable;}
// extra info from provider
public String getCredits(){return credits;} // getCredits
public String getCourse(){return course;} // getCourse
public String getSection(){return section;} // getSection
public String getRegId(){return regId;} // getRegId
/**
* Access the user eid, if we can find it - fall back to the id if not.
* @return The user eid.
*/
public String getEid()
{
try
{
return UserDirectoryService.getUserEid(uniqname);
}
catch (UserNotDefinedException e)
{
return uniqname;
}
}
/**
* Access the user display id, if we can find it - fall back to the id if not.
* @return The user display id.
*/
public String getDisplayId()
{
try
{
User user = UserDirectoryService.getUser(uniqname);
return user.getDisplayId();
}
catch (UserNotDefinedException e)
{
return uniqname;
}
}
} // Participant
/**
* Student in roster
*
*/
public class Student
{
public String name = NULL_STRING;
public String uniqname = NULL_STRING;
public String id = NULL_STRING;
public String level = NULL_STRING;
public String credits = NULL_STRING;
public String role = NULL_STRING;
public String course = NULL_STRING;
public String section = NULL_STRING;
public String getName() {return name; }
public String getUniqname() {return uniqname; }
public String getId() { return id; }
public String getLevel() { return level; }
public String getCredits() { return credits; }
public String getRole() { return role; }
public String getCourse() { return course; }
public String getSection() { return section; }
} // Student
public class SiteInfo
{
public String site_id = NULL_STRING; // getId of Resource
public String external_id = NULL_STRING; // if matches site_id connects site with U-M course information
public String site_type = "";
public String iconUrl = NULL_STRING;
public String infoUrl = NULL_STRING;
public boolean joinable = false;
public String joinerRole = NULL_STRING;
public String title = NULL_STRING; // the short name of the site
public String short_description = NULL_STRING; // the short (20 char) description of the site
public String description = NULL_STRING; // the longer description of the site
public String additional = NULL_STRING; // additional information on crosslists, etc.
public boolean published = false;
public boolean include = true; // include the site in the Sites index; default is true.
public String site_contact_name = NULL_STRING; // site contact name
public String site_contact_email = NULL_STRING; // site contact email
public String getSiteId() {return site_id;}
public String getSiteType() { return site_type; }
public String getTitle() { return title; }
public String getDescription() { return description; }
public String getIconUrl() { return iconUrl; }
public String getInfoUrll() { return infoUrl; }
public boolean getJoinable() {return joinable; }
public String getJoinerRole() {return joinerRole; }
public String getAdditional() { return additional; }
public boolean getPublished() { return published; }
public boolean getInclude() {return include;}
public String getSiteContactName() {return site_contact_name; }
public String getSiteContactEmail() {return site_contact_email; }
} // SiteInfo
//dissertation tool related
/**
* doFinish_grad_tools is called when creation of a Grad Tools site is confirmed
*/
public void doFinish_grad_tools ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
//set up for the coming template
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString ("continue"));
int index = Integer.valueOf(params.getString ("template-index")).intValue();
actionForTemplate("continue", index, params, state);
//add the pre-configured Grad Tools tools to a new site
addGradToolsFeatures(state);
// TODO: hard coding this frame id is fragile, portal dependent, and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
resetPaging(state);
}// doFinish_grad_tools
/**
* addGradToolsFeatures adds features to a new Grad Tools student site
*
*/
private void addGradToolsFeatures(SessionState state)
{
Site edit = null;
Site template = null;
//get a unique id
String id = IdManager.createUuid();
//get the Grad Tools student site template
try
{
template = SiteService.getSite(SITE_GTS_TEMPLATE);
}
catch (Exception e)
{
if(Log.isWarnEnabled())
M_log.warn("addGradToolsFeatures template " + e);
}
if(template != null)
{
//create a new site based on the template
try
{
edit = SiteService.addSite(id, template);
}
catch(Exception e)
{
if(Log.isWarnEnabled())
M_log.warn("addGradToolsFeatures add/edit site " + e);
}
//set the tab, etc.
if(edit != null)
{
SiteInfo siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
edit.setShortDescription(siteInfo.short_description);
edit.setTitle(siteInfo.title);
edit.setPublished(true);
edit.setPubView(false);
edit.setType(SITE_TYPE_GRADTOOLS_STUDENT);
//ResourcePropertiesEdit rpe = edit.getPropertiesEdit();
try
{
SiteService.save(edit);
}
catch(Exception e)
{
if(Log.isWarnEnabled())
M_log.warn("addGradToolsFeartures commitEdit " + e);
}
//now that the site and realm exist, we can set the email alias
//set the GradToolsStudent site alias as: gradtools-uniqname@servername
String alias = "gradtools-" + SessionManager.getCurrentSessionUserId();
String channelReference = mailArchiveChannelReference(id);
try
{
AliasService.setAlias(alias, channelReference);
}
catch (IdUsedException ee)
{
addAlert(state, rb.getString("java.alias")+" " + alias + " "+rb.getString("java.exists"));
}
catch (IdInvalidException ee)
{
addAlert(state, rb.getString("java.alias")+" " + alias + " "+rb.getString("java.isinval"));
}
catch (PermissionException ee)
{
M_log.warn(SessionManager.getCurrentSessionUserId() + " does not have permission to add alias. ");
}
}
}
} // addGradToolsFeatures
/**
* handle with add site options
*
*/
public void doAdd_site_option ( RunData data )
{
String option = data.getParameters().getString("option");
if (option.equals("finish"))
{
doFinish(data);
}
else if (option.equals("cancel"))
{
doCancel_create(data);
}
else if (option.equals("back"))
{
doBack(data);
}
} // doAdd_site_option
/**
* handle with duplicate site options
*
*/
public void doDuplicate_site_option ( RunData data )
{
String option = data.getParameters().getString("option");
if (option.equals("duplicate"))
{
doContinue(data);
}
else if (option.equals("cancel"))
{
doCancel(data);
}
else if (option.equals("finish"))
{
doContinue(data);
}
} // doDuplicate_site_option
/**
* Special check against the Dissertation service, which might not be here...
* @return
*/
protected boolean isGradToolsCandidate(String userId)
{
// DissertationService.isCandidate(userId) - but the hard way
Object service = ComponentManager.get("org.sakaiproject.api.app.dissertation.DissertationService");
if (service == null) return false;
// the method signature
Class[] signature = new Class[1];
signature[0] = String.class;
// the method name
String methodName = "isCandidate";
// find a method of this class with this name and signature
try
{
Method method = service.getClass().getMethod(methodName, signature);
// the parameters
Object[] args = new Object[1];
args[0] = userId;
// make the call
Boolean rv = (Boolean) method.invoke(service, args);
return rv.booleanValue();
}
catch (Throwable t)
{
}
return false;
}
/**
* User has a Grad Tools student site
* @return
*/
protected boolean hasGradToolsStudentSite(String userId)
{
boolean has = false;
int n = 0;
try
{
n = SiteService.countSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
SITE_TYPE_GRADTOOLS_STUDENT, null, null);
if(n > 0)
has = true;
}
catch(Exception e)
{
if(Log.isWarnEnabled())
M_log.warn("hasGradToolsStudentSite " + e);
}
return has;
}//hasGradToolsStudentSite
/**
* Get the mail archive channel reference for the main container placement for this site.
* @param siteId The site id.
* @return The mail archive channel reference for this site.
*/
protected String mailArchiveChannelReference(String siteId)
{
MailArchiveService m = (org.sakaiproject.mailarchive.api.MailArchiveService) ComponentManager.get("org.sakaiproject.mailarchive.api.MailArchiveService");
if (m != null)
{
return m.channelReference(siteId, SiteService.MAIN_CONTAINER);
}
else
{
return "";
}
}
/**
* Transfer a copy of all entites from another context for any entity producer that claims this tool id.
*
* @param toolId
* The tool id.
* @param fromContext
* The context to import from.
* @param toContext
* The context to import into.
*/
protected void transferCopyEntities(String toolId, String fromContext, String toContext)
{
// TODO: used to offer to resources first - why? still needed? -ggolden
// offer to all EntityProducers
for (Iterator i = EntityManager.getEntityProducers().iterator(); i.hasNext();)
{
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer)
{
try
{
EntityTransferrer et = (EntityTransferrer) ep;
// if this producer claims this tool id
if (ArrayUtil.contains(et.myToolIds(), toolId))
{
et.transferCopyEntities(fromContext, toContext, new Vector());
}
}
catch (Throwable t)
{
M_log.warn("Error encountered while asking EntityTransfer to transferCopyEntities from: " + fromContext
+ " to: " + toContext, t);
}
}
}
}
/**
* @return Get a list of all tools that support the import (transfer copy) option
*/
protected Set importTools()
{
HashSet rv = new HashSet();
// offer to all EntityProducers
for (Iterator i = EntityManager.getEntityProducers().iterator(); i.hasNext();)
{
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer)
{
EntityTransferrer et = (EntityTransferrer) ep;
String[] tools = et.myToolIds();
if (tools != null)
{
for (int t = 0; t < tools.length; t++)
{
rv.add(tools[t]);
}
}
}
}
return rv;
}
/**
* @param state
* @return Get a list of all tools that should be included as options for import
*/
protected List getToolsAvailableForImport(SessionState state)
{
// The Web Content and News tools do not follow the standard rules for import
// Even if the current site does not contain the tool, News and WC will be
// an option if the imported site contains it
boolean displayWebContent = false;
boolean displayNews = false;
Set importSites = ((Hashtable)state.getAttribute(STATE_IMPORT_SITES)).keySet();
Iterator sitesIter = importSites.iterator();
while (sitesIter.hasNext())
{
Site site = (Site)sitesIter.next();
if (site.getToolForCommonId("sakai.iframe") != null)
displayWebContent = true;
if (site.getToolForCommonId("sakai.news") != null)
displayNews = true;
}
List toolsOnImportList = (List)state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
if (displayWebContent && !toolsOnImportList.contains("sakai.iframe"))
toolsOnImportList.add("sakai.iframe");
if (displayNews && !toolsOnImportList.contains("sakai.news"))
toolsOnImportList.add("sakai.news");
return toolsOnImportList;
}
}
| true | true | private String buildContextForTemplate (int index, VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
String realmId = "";
String site_type = "";
String sortedBy = "";
String sortedAsc = "";
ParameterParser params = data.getParameters ();
context.put("tlang",rb);
context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
else
{
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
// Lists used in more than one template
// Access
List roles = new Vector();
// the hashtables for News and Web Content tools
Hashtable newsTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable wcUrls = new Hashtable();
List toolRegistrationList = new Vector();
List toolRegistrationSelectedList = new Vector();
ResourceProperties siteProperties = null;
// for showing site creation steps
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null)
{
context.put("totalSteps", state.getAttribute(SITE_CREATE_TOTAL_STEPS));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null)
{
context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP));
}
String hasGradSites = ServerConfigurationService.getString("withDissertation", Boolean.FALSE.toString());
Site site = getStateSite(state);
switch (index)
{
case 0:
/* buildContextForTemplate chef_site-list.vm
*
*/
// site types
List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);
//make sure auto-updates are enabled
Hashtable views = new Hashtable();
if (SecurityService.isSuperUser())
{
views.put(rb.getString("java.allmy"), rb.getString("java.allmy"));
views.put(rb.getString("java.my") + " " + rb.getString("java.sites"), rb.getString("java.my"));
for(int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++)
{
String type = (String) sTypes.get(sTypeIndex);
views.put(type + " " + rb.getString("java.sites"), type);
}
if (hasGradSites.equalsIgnoreCase("true"))
{
views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb.getString("java.gradtools"));
}
if(state.getAttribute(STATE_VIEW_SELECTED) == null)
{
state.setAttribute(STATE_VIEW_SELECTED, rb.getString("java.allmy"));
}
context.put("superUser", Boolean.TRUE);
}
else
{
context.put("superUser", Boolean.FALSE);
views.put(rb.getString("java.allmy"), rb.getString("java.allmy"));
// if there is a GradToolsStudent choice inside
boolean remove = false;
if (hasGradSites.equalsIgnoreCase("true"))
{
try
{
//the Grad Tools site option is only presented to GradTools Candidates
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
//am I a grad student?
if (!isGradToolsCandidate(userId))
{
// not a gradstudent
remove = true;
}
}
catch(Exception e)
{
remove = true;
}
}
else
{
// not support for dissertation sites
remove=true;
}
//do not show this site type in views
//sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT));
for(int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++)
{
String type = (String) sTypes.get(sTypeIndex);
if(!type.equals(SITE_TYPE_GRADTOOLS_STUDENT))
{
views.put(type + " "+rb.getString("java.sites"), type);
}
}
if (!remove)
{
views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb.getString("java.gradtools"));
}
//default view
if(state.getAttribute(STATE_VIEW_SELECTED) == null)
{
state.setAttribute(STATE_VIEW_SELECTED, rb.getString("java.allmy"));
}
}
context.put("views", views);
if(state.getAttribute(STATE_VIEW_SELECTED) != null)
{
context.put("viewSelected", (String) state.getAttribute(STATE_VIEW_SELECTED));
}
String search = (String) state.getAttribute(STATE_SEARCH);
context.put("search_term", search);
sortedBy = (String) state.getAttribute (SORTED_BY);
if (sortedBy == null)
{
state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
sortedBy = SortType.TITLE_ASC.toString();
}
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if (sortedAsc == null)
{
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
String portalUrl = ServerConfigurationService.getPortalUrl();
context.put("portalUrl", portalUrl);
List sites = prepPage(state);
state.setAttribute(STATE_SITES, sites);
context.put("sites", sites);
context.put("totalPageNumber", new Integer(totalPageNumber(state)));
context.put("searchString", state.getAttribute(STATE_SEARCH));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
// put the service in the context (used for allow update calls on each site)
context.put("service", SiteService.getInstance());
context.put("sortby_title", SortType.TITLE_ASC.toString());
context.put("sortby_type", SortType.TYPE_ASC.toString());
context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
// top menu bar
Menu bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null))
{
bar.add( new MenuEntry(rb.getString("java.new"), "doNew_site"));
}
bar.add( new MenuEntry(rb.getString("java.revise"), null, true, MenuItem.CHECKED_NA, "doGet_site", "sitesForm"));
bar.add( new MenuEntry(rb.getString("java.delete"), null, true, MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm"));
context.put("menu", bar);
// default to be no pageing
context.put("paged", Boolean.FALSE);
Menu bar2 = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
// add the search commands
addSearchMenus(bar2, state);
context.put("menu2", bar2);
pagingInfoToContext(state, context);
return (String)getContext(data).get("template") + TEMPLATE[0];
case 1:
/* buildContextForTemplate chef_site-type.vm
*
*/
if (hasGradSites.equalsIgnoreCase("true"))
{
context.put("withDissertation", Boolean.TRUE);
try
{
//the Grad Tools site option is only presented to UM grad students
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
//am I a UM grad student?
Boolean isGradStudent = new Boolean(isGradToolsCandidate(userId));
context.put("isGradStudent", isGradStudent);
//if I am a UM grad student, do I already have a Grad Tools site?
boolean noGradToolsSite = true;
if(hasGradToolsStudentSite(userId))
noGradToolsSite = false;
context.put("noGradToolsSite", new Boolean(noGradToolsSite));
}
catch(Exception e)
{
if(Log.isWarnEnabled())
{
M_log.warn("buildContextForTemplate chef_site-type.vm " + e);
}
}
}
else
{
context.put("withDissertation", Boolean.FALSE);
}
List types = (List) state.getAttribute(STATE_SITE_TYPES);
context.put("siteTypes", types);
// put selected/default site type into context
if (siteInfo.site_type != null && siteInfo.site_type.length() >0)
{
context.put("typeSelected", siteInfo.site_type);
}
else if (types.size() > 0)
{
context.put("typeSelected", types.get(0));
}
List termsForSiteCreation = getAvailableTerms();
if (termsForSiteCreation.size() > 0)
{
context.put("termList", termsForSiteCreation);
}
if (state.getAttribute(STATE_TERM_SELECTED) != null)
{
context.put("selectedTerm", state.getAttribute(STATE_TERM_SELECTED));
}
return (String)getContext(data).get("template") + TEMPLATE[1];
case 2:
/* buildContextForTemplate chef_site-newSiteInformation.vm
*
*/
context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES));
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("titleEditableSiteType", state.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", siteType);
if (siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put ("manualAddNumber", new Integer(number - 1));
context.put ("manualAddFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("back", "37");
}
else
{
context.put("back", "36");
}
context.put ("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null)
{
context.put("selectedIcon", siteInfo.getIconUrl());
}
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null)
{
context.put(FORM_ICON_URL, siteInfo.iconUrl);
}
context.put ("back", "1");
}
context.put (FORM_TITLE,siteInfo.title);
context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description);
context.put (FORM_DESCRIPTION,siteInfo.description);
// defalt the site contact person to the site creator
if (siteInfo.site_contact_name.equals(NULL_STRING) && siteInfo.site_contact_email.equals(NULL_STRING))
{
User user = UserDirectoryService.getCurrentUser();
siteInfo.site_contact_name = user.getDisplayName();
siteInfo.site_contact_email = user.getEmail();
}
context.put("form_site_contact_name", siteInfo.site_contact_name);
context.put("form_site_contact_email", siteInfo.site_contact_email);
// those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[2];
case 3:
/* buildContextForTemplate chef_site-newSiteFeatures.vm
*
*/
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType!=null && siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
}
context.put("defaultTools", ServerConfigurationService.getToolsRequired(siteType));
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// If this is the first time through, check for tools
// which should be selected by default.
List defaultSelectedTools = ServerConfigurationService.getDefaultTools(siteType);
if (toolRegistrationSelectedList == null) {
toolRegistrationSelectedList = new Vector(defaultSelectedTools);
}
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST) ); // %%% use ToolRegistrations for template list
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
// The "Home" tool checkbox needs special treatment to be selected by
// default.
Boolean checkHome = (Boolean)state.getAttribute(STATE_TOOL_HOME_SELECTED);
if (checkHome == null) {
if ((defaultSelectedTools != null) && defaultSelectedTools.contains(HOME_TOOL_ID)) {
checkHome = Boolean.TRUE;
}
}
context.put("check_home", checkHome);
//titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
//titles for web content tools
context.put("wcTitles", state.getAttribute(STATE_WEB_CONTENT_TITLES));
//urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
//urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put("sites", SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null));
context.put("import", state.getAttribute(STATE_IMPORT));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[3];
case 4:
/* buildContextForTemplate chef_site-addRemoveFeatures.vm
*
*/
context.put("SiteTitle", site.getTitle());
String type = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("defaultTools", ServerConfigurationService.getToolsRequired(type));
boolean myworkspace_site = false;
//Put up tool lists filtered by category
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes.contains(type))
{
myworkspace_site = false;
}
if (SiteService.isUserSite(site.getId()) || (type!=null && type.equalsIgnoreCase("myworkspace")))
{
myworkspace_site = true;
type="myworkspace";
}
context.put ("myworkspace_site", new Boolean(myworkspace_site));
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST));
//titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
//titles for web content tools
context.put("wcTitles", state.getAttribute(STATE_WEB_CONTENT_TITLES));
//urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
//urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
//get the email alias when an Email Archive tool has been selected
String channelReference = mailArchiveChannelReference(site.getId());
List aliases = AliasService.getAliases(channelReference, 1, 1);
if (aliases.size() > 0)
{
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases.get(0)).getId());
}
else
{
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null)
{
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService.getServerName());
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[4];
case 5:
/* buildContextForTemplate chef_site-addParticipant.vm
*
*/
context.put("title", site.getTitle());
roles = getRoles(state);
context.put("roles", roles);
// Note that (for now) these strings are in both sakai.properties and sitesetupgeneric.properties
context.put("noEmailInIdAccountName", ServerConfigurationService.getString("noEmailInIdAccountName"));
context.put("noEmailInIdAccountLabel", ServerConfigurationService.getString("noEmailInIdAccountLabel"));
context.put("emailInIdAccountName", ServerConfigurationService.getString("emailInIdAccountName"));
context.put("emailInIdAccountLabel", ServerConfigurationService.getString("emailInIdAccountLabel"));
if(state.getAttribute("noEmailInIdAccountValue")!=null)
{
context.put("noEmailInIdAccountValue", (String)state.getAttribute("noEmailInIdAccountValue"));
}
if(state.getAttribute("emailInIdAccountValue")!=null)
{
context.put("emailInIdAccountValue", (String)state.getAttribute("emailInIdAccountValue"));
}
if(state.getAttribute("form_same_role") != null)
{
context.put("form_same_role", ((Boolean) state.getAttribute("form_same_role")).toString());
}
else
{
context.put("form_same_role", Boolean.TRUE.toString());
}
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[5];
case 6:
/* buildContextForTemplate chef_site-removeParticipants.vm
*
*/
context.put("title", site.getTitle());
realmId = SiteService.siteReference(site.getId());
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
try
{
List removeableList = (List) state.getAttribute(STATE_REMOVEABLE_USER_LIST);
List removeableParticipants = new Vector();
for (int k = 0; k < removeableList.size(); k++)
{
User user = UserDirectoryService.getUser((String) removeableList.get(k));
Participant participant = new Participant();
participant.name = user.getSortName();
participant.uniqname = user.getId();
Role r = realm.getUserRole(user.getId());
if (r != null)
{
participant.role = r.getId();
}
removeableParticipants.add(participant);
}
context.put("removeableList", removeableParticipants);
}
catch (UserNotDefinedException ee)
{
}
}
catch (GroupNotDefinedException e)
{
}
context.put("backIndex", "18");
return (String)getContext(data).get("template") + TEMPLATE[6];
case 7:
/* buildContextForTemplate chef_site-changeRoles.vm
*
*/
context.put("same_role", state.getAttribute(STATE_CHANGEROLE_SAMEROLE));
roles = getRoles(state);
context.put("roles", roles);
context.put("currentRole", state.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
context.put("participantSelectedList", state.getAttribute(STATE_SELECTED_PARTICIPANTS));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("siteTitle", site.getTitle());
return (String)getContext(data).get("template") + TEMPLATE[7];
case 8:
/* buildContextForTemplate chef_site-siteDeleteConfirm.vm
*
*/
String site_title = NULL_STRING;
String[] removals = (String[]) state.getAttribute(STATE_SITE_REMOVALS);
List remove = new Vector();
String user = SessionManager.getCurrentSessionUserId();
String workspace = SiteService.getUserSiteId(user);
if( removals != null && removals.length != 0 )
{
for (int i = 0; i < removals.length; i++ )
{
String id = (String) removals[i];
if(!(id.equals(workspace)))
{
try
{
site_title = SiteService.getSite(id).getTitle();
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.doSite_delete_confirmed - IdUnusedException " + id);
addAlert(state, rb.getString("java.sitewith")+" " + id + " "+rb.getString("java.couldnt")+" ");
}
if(SiteService.allowRemoveSite(id))
{
try
{
Site removeSite = SiteService.getSite(id);
remove.add(removeSite);
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException");
}
}
else
{
addAlert(state, site_title + " "+rb.getString("java.couldntdel") + " ");
}
}
else
{
addAlert(state, rb.getString("java.yourwork"));
}
}
if(remove.size() == 0)
{
addAlert(state, rb.getString("java.click"));
}
}
context.put("removals", remove);
return (String)getContext(data).get("template") + TEMPLATE[8];
case 9:
/* buildContextForTemplate chef_site-publishUnpublish.vm
*
*/
context.put("publish", Boolean.valueOf(((SiteInfo)state.getAttribute(STATE_SITE_INFO)).getPublished()));
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[9];
case 10:
/* buildContextForTemplate chef_site-newSiteConfirm.vm
*
*/
siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put ("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put ("manualAddNumber", new Integer(number - 1));
context.put ("manualAddFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put ("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null)
{
context.put("selectedIcon", siteInfo.getIconUrl());
}
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType!=null && siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null)
{
context.put("iconUrl", siteInfo.iconUrl);
}
}
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("siteContactName", siteInfo.site_contact_name);
context.put("siteContactEmail", siteInfo.site_contact_email);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use Tool
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
context.put("include", new Boolean(siteInfo.include));
context.put("published", new Boolean(siteInfo.published));
context.put("joinable", new Boolean(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
context.put("newsTitles", (Hashtable) state.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES));
// back to edit access page
context.put("back", "18");
context.put("importSiteTools", state.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("siteService", SiteService.getInstance());
// those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[10];
case 11:
/* buildContextForTemplate chef_site-newSitePublishUnpublish.vm
*
*/
return (String)getContext(data).get("template") + TEMPLATE[11];
case 12:
/* buildContextForTemplate chef_site-siteInfo-list.vm
*
*/
context.put("userDirectoryService", UserDirectoryService.getInstance());
try
{
siteProperties = site.getProperties();
siteType = site.getType();
if (siteType != null)
{
state.setAttribute(STATE_SITE_TYPE, siteType);
}
boolean isMyWorkspace = false;
if (SiteService.isUserSite(site.getId()))
{
if (SiteService.getSiteUserId(site.getId()).equals(SessionManager.getCurrentSessionUserId()))
{
isMyWorkspace = true;
context.put("siteUserId", SiteService.getSiteUserId(site.getId()));
}
}
context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));
String siteId = site.getId();
if (state.getAttribute(STATE_ICONS)!= null)
{
List skins = (List)state.getAttribute(STATE_ICONS);
for (int i = 0; i < skins.size(); i++)
{
Icon s = (Icon)skins.get(i);
if(!StringUtil.different(s.getUrl(), site.getIconUrl()))
{
context.put("siteUnit", s.getName());
break;
}
}
}
context.put("siteIcon", site.getIconUrl());
context.put("siteTitle", site.getTitle());
context.put("siteDescription", site.getDescription());
context.put("siteJoinable", new Boolean(site.isJoinable()));
if(site.isPublished())
{
context.put("published", Boolean.TRUE);
}
else
{
context.put("published", Boolean.FALSE);
context.put("owner", site.getCreatedBy().getSortName());
}
Time creationTime = site.getCreatedTime();
if (creationTime != null)
{
context.put("siteCreationDate", creationTime.toStringLocalFull());
}
boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));
boolean allowUpdateGroupMembership = SiteService.allowUpdateGroupMembership(siteId);
context.put("allowUpdateGroupMembership", Boolean.valueOf(allowUpdateGroupMembership));
boolean allowUpdateSiteMembership = SiteService.allowUpdateSiteMembership(siteId);
context.put("allowUpdateSiteMembership", Boolean.valueOf(allowUpdateSiteMembership));
if (allowUpdateSite)
{
// top menu bar
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace)
{
b.add( new MenuEntry(rb.getString("java.editsite"), "doMenu_edit_site_info"));
}
b.add( new MenuEntry(rb.getString("java.edittools"), "doMenu_edit_site_tools"));
if (!isMyWorkspace
&& (ServerConfigurationService.getString("wsetup.group.support") == ""
|| ServerConfigurationService.getString("wsetup.group.support").equalsIgnoreCase(Boolean.TRUE.toString())))
{
// show the group toolbar unless configured to not support group
b.add( new MenuEntry(rb.getString("java.group"), "doMenu_group"));
}
if (!isMyWorkspace)
{
List gradToolsSiteTypes = (List) state.getAttribute(GRADTOOLS_SITE_TYPES);
boolean isGradToolSite = false;
if (siteType != null && gradToolsSiteTypes.contains(siteType))
{
isGradToolSite = true;
}
if (siteType == null
|| siteType != null && !isGradToolSite)
{
// hide site access for GRADTOOLS type of sites
b.add( new MenuEntry(rb.getString("java.siteaccess"), "doMenu_edit_site_access"));
}
b.add( new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant"));
if (siteType != null && siteType.equals("course"))
{
b.add( new MenuEntry(rb.getString("java.editc"), "doMenu_siteInfo_editClass"));
}
if (siteType == null || siteType != null && !isGradToolSite)
{
// hide site duplicate and import for GRADTOOLS type of sites
b.add( new MenuEntry(rb.getString("java.duplicate"), "doMenu_siteInfo_duplicate"));
List updatableSites = SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null);
// import link should be visible even if only one site
if (updatableSites.size() > 0)
{
b.add( new MenuEntry(rb.getString("java.import"), "doMenu_siteInfo_import"));
// a configuration param for showing/hiding import from file choice
String importFromFile = ServerConfigurationService.getString("site.setup.import.file", Boolean.TRUE.toString());
if (importFromFile.equalsIgnoreCase("true"))
{
//htripath: June 4th added as per Kris and changed desc of above
b.add(new MenuEntry(rb.getString("java.importFile"), "doAttachmentsMtrlFrmFile"));
}
}
}
}
// if the page order helper is available, not stealthed and not hidden, show the link
if (ToolManager.getTool("sakai-site-pageorder-helper") != null
&& !ServerConfigurationService
.getString("[email protected]")
.contains("sakai-site-pageorder-helper")
&& !ServerConfigurationService
.getString("[email protected]")
.contains("sakai-site-pageorder-helper"))
{
b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper"));
}
context.put("menu", b);
}
if (allowUpdateGroupMembership)
{
// show Manage Groups menu
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace
&& (ServerConfigurationService.getString("wsetup.group.support") == ""
|| ServerConfigurationService.getString("wsetup.group.support").equalsIgnoreCase(Boolean.TRUE.toString())))
{
// show the group toolbar unless configured to not support group
b.add( new MenuEntry(rb.getString("java.group"), "doMenu_group"));
}
context.put("menu", b);
}
if (allowUpdateSiteMembership)
{
// show add participant menu
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace)
{
// show the Add Participant menu
b.add( new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant"));
}
context.put("menu", b);
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
// editing from worksite setup tool
context.put("fromWSetup", Boolean.TRUE);
if (state.getAttribute(STATE_PREV_SITE) != null)
{
context.put("prevSite", state.getAttribute(STATE_PREV_SITE));
}
if (state.getAttribute(STATE_NEXT_SITE) != null)
{
context.put("nextSite", state.getAttribute(STATE_NEXT_SITE));
}
}
else
{
context.put("fromWSetup", Boolean.FALSE);
}
//allow view roster?
boolean allowViewRoster = SiteService.allowViewRoster(siteId);
if (allowViewRoster)
{
context.put("viewRoster", Boolean.TRUE);
}
else
{
context.put("viewRoster", Boolean.FALSE);
}
//set participant list
if (allowUpdateSite || allowViewRoster || allowUpdateSiteMembership)
{
List participants = new Vector();
participants = getParticipantList(state);
sortedBy = (String) state.getAttribute (SORTED_BY);
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if(sortedBy==null)
{
state.setAttribute(SORTED_BY, SORTED_BY_PARTICIPANT_NAME);
sortedBy = SORTED_BY_PARTICIPANT_NAME;
}
if (sortedAsc==null)
{
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
Iterator sortedParticipants = null;
if (sortedBy != null)
{
sortedParticipants = new SortedIterator (participants.iterator (), new SiteComparator (sortedBy, sortedAsc));
participants.clear();
while (sortedParticipants.hasNext())
{
participants.add(sortedParticipants.next());
}
}
context.put("participantListSize", new Integer(participants.size()));
context.put("participantList", prepPage(state));
pagingInfoToContext(state, context);
}
context.put("include", Boolean.valueOf(site.isPubView()));
// site contact information
String contactName = siteProperties.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null)
{
User u = site.getCreatedBy();
String email = u.getEmail();
if (email != null)
{
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
if (contactName != null)
{
context.put("contactName", contactName);
}
if (contactEmail != null)
{
context.put("contactEmail", contactEmail);
}
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
List providerCourseList = getProviderCourseList(StringUtil.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null)
{
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
context.put("providerCourseList", providerCourseList);
}
String manualCourseListString = site.getProperties().getProperty(PROP_SITE_REQUEST_COURSE);
if (manualCourseListString != null)
{
List manualCourseList = new Vector();
if (manualCourseListString.indexOf("+") != -1)
{
manualCourseList = new ArrayList(Arrays.asList(manualCourseListString.split("\\+")));
}
else
{
manualCourseList.add(manualCourseListString);
}
state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList);
context.put("manualCourseList", manualCourseList);
}
context.put("term", siteProperties.getProperty(PROP_SITE_TERM));
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
}
catch (Exception e)
{
M_log.warn(this + " site info list: " + e.toString());
}
roles = getRoles(state);
context.put("roles", roles);
// will have the choice to active/inactive user or not
String activeInactiveUser = ServerConfigurationService.getString("activeInactiveUser", Boolean.FALSE.toString());
if (activeInactiveUser.equalsIgnoreCase("true"))
{
context.put("activeInactiveUser", Boolean.TRUE);
// put realm object into context
realmId = SiteService.siteReference(site.getId());
try
{
context.put("realm", AuthzGroupService.getAuthzGroup(realmId));
}
catch (GroupNotDefinedException e)
{
M_log.warn(this + " IdUnusedException " + realmId);
}
}
else
{
context.put("activeInactiveUser", Boolean.FALSE);
}
context.put("groupsWithMember", site.getGroupsWithMember(UserDirectoryService.getCurrentUser().getId()));
return (String)getContext(data).get("template") + TEMPLATE[12];
case 13:
/* buildContextForTemplate chef_site-siteInfo-editInfo.vm
*
*/
siteProperties = site.getProperties();
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("titleEditableSiteType", state.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", site.getType());
List terms = CourseManagementService.getTerms();
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("skins", state.getAttribute(STATE_ICONS));
if (state.getAttribute(FORM_SITEINFO_SKIN) != null)
{
context.put("selectedIcon",state.getAttribute(FORM_SITEINFO_SKIN));
}
else if (site.getIconUrl() != null)
{
context.put("selectedIcon",site.getIconUrl());
}
if (terms != null && terms.size() >0)
{
context.put("termList", terms);
}
if (state.getAttribute(FORM_SITEINFO_TERM) == null)
{
String currentTerm = site.getProperties().getProperty(PROP_SITE_TERM);
if (currentTerm != null)
{
state.setAttribute(FORM_SITEINFO_TERM, currentTerm);
}
}
if (state.getAttribute(FORM_SITEINFO_TERM) != null)
{
context.put("selectedTerm", state.getAttribute(FORM_SITEINFO_TERM));
}
}
else
{
context.put("isCourseSite", Boolean.FALSE);
if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null && StringUtil.trimToNull(site.getIconUrl()) != null)
{
state.setAttribute(FORM_SITEINFO_ICON_URL, site.getIconUrl());
}
if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null)
{
context.put("iconUrl", state.getAttribute(FORM_SITEINFO_ICON_URL));
}
}
context.put("description", state.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("short_description", state.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("form_site_contact_name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("form_site_contact_email", state.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
//Display of appearance icon/url list with course site based on
// "disable.course.site.skin.selection" value set with sakai.properties file.
if ((ServerConfigurationService.getString("disable.course.site.skin.selection")).equals("true")){
context.put("disableCourseSelection", Boolean.TRUE);
}
return (String)getContext(data).get("template") + TEMPLATE[13];
case 14:
/* buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm
*
*/
siteProperties = site.getProperties();
siteType = (String)state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM));
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
context.put("oTitle", site.getTitle());
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("description", state.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("oDescription", site.getDescription());
context.put("short_description", state.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("oShort_description", site.getShortDescription());
context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN));
context.put("oSkin", site.getIconUrl());
context.put("skins", state.getAttribute(STATE_ICONS));
context.put("oIcon", site.getIconUrl());
context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL));
context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE));
context.put("oInclude", Boolean.valueOf(site.isPubView()));
context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("oName", siteProperties.getProperty(PROP_SITE_CONTACT_NAME));
context.put("email", state.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
context.put("oEmail", siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL));
return (String)getContext(data).get("template") + TEMPLATE[14];
case 15:
/* buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm
*
*/
context.put("title", site.getTitle());
site_type = (String)state.getAttribute(STATE_SITE_TYPE);
myworkspace_site = false;
if (SiteService.isUserSite(site.getId()))
{
if (SiteService.getSiteUserId(site.getId()).equals(SessionManager.getCurrentSessionUserId()))
{
myworkspace_site = true;
site_type = "myworkspace";
}
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("selectedTools", orderToolIds(state, (String) state.getAttribute(STATE_SITE_TYPE), (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)));
context.put("oldSelectedTools", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("oldSelectedHome", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME));
context.put("continueIndex", "12");
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null)
{
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService.getServerName());
context.put("newsTitles", (Hashtable) state.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES));
if (fromENWModifyView(state))
{
context.put("back", "26");
}
else
{
context.put("back", "4");
}
return (String)getContext(data).get("template") + TEMPLATE[15];
case 16:
/* buildContextForTemplate chef_site-publishUnpublish-sendEmail.vm
*
*/
context.put("title", site.getTitle());
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String)getContext(data).get("template") + TEMPLATE[16];
case 17:
/* buildContextForTemplate chef_site-publishUnpublish-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("continueIndex", "12");
SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (sInfo.getPublished())
{
context.put("publish", Boolean.TRUE);
context.put("backIndex", "16");
}
else
{
context.put("publish", Boolean.FALSE);
context.put("backIndex", "9");
}
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String)getContext(data).get("template") + TEMPLATE[17];
case 18:
/* buildContextForTemplate chef_siteInfo-editAccess.vm
*
*/
List publicChangeableSiteTypes = (List) state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
List unJoinableSiteTypes = (List) state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);
if (site != null)
{
//editing existing site
context.put("site", site);
siteType = state.getAttribute(STATE_SITE_TYPE)!=null?(String)state.getAttribute(STATE_SITE_TYPE):null;
if ( siteType != null
&& publicChangeableSiteTypes.contains(siteType))
{
context.put ("publicChangeable", Boolean.TRUE);
}
else
{
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(site.isPubView()));
if ( siteType != null && !unJoinableSiteTypes.contains(siteType))
{
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
if (state.getAttribute(STATE_JOINABLE) == null)
{
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site.isJoinable()));
}
if (state.getAttribute(STATE_JOINERROLE) == null
|| state.getAttribute(STATE_JOINABLE) != null && ((Boolean) state.getAttribute(STATE_JOINABLE)).booleanValue())
{
state.setAttribute(STATE_JOINERROLE, site.getJoinerRole());
}
if (state.getAttribute(STATE_JOINABLE) != null)
{
context.put("joinable", state.getAttribute(STATE_JOINABLE));
}
if (state.getAttribute(STATE_JOINERROLE) != null)
{
context.put("joinerRole", state.getAttribute(STATE_JOINERROLE));
}
}
else
{
//site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
context.put("roles", getRoles(state));
context.put("back", "12");
}
else
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if ( siteInfo.site_type != null
&& publicChangeableSiteTypes.contains(siteInfo.site_type))
{
context.put ("publicChangeable", Boolean.TRUE);
}
else
{
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(siteInfo.getInclude()));
context.put("published", Boolean.valueOf(siteInfo.getPublished()));
if ( siteInfo.site_type != null && !unJoinableSiteTypes.contains(siteInfo.site_type))
{
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
}
else
{
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
// use the type's template, if defined
String realmTemplate = "!site.template";
if (siteInfo.site_type != null)
{
realmTemplate = realmTemplate + "." + siteInfo.site_type;
}
try
{
AuthzGroup r = AuthzGroupService.getAuthzGroup(realmTemplate);
context.put("roles", r.getRoles());
}
catch (GroupNotDefinedException e)
{
try
{
AuthzGroup rr = AuthzGroupService.getAuthzGroup("!site.template");
context.put("roles", rr.getRoles());
}
catch (GroupNotDefinedException ee)
{
}
}
// new site, go to confirmation page
context.put("continue", "10");
if (fromENWModifyView(state))
{
context.put("back", "26");
}
else if (state.getAttribute(STATE_IMPORT) != null)
{
context.put("back", "27");
}
else
{
context.put("back", "3");
}
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType!=null && siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
}
}
return (String)getContext(data).get("template") + TEMPLATE[18];
case 19:
/* buildContextForTemplate chef_site-addParticipant-sameRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("participantList", state.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("form_selectedRole", state.getAttribute("form_selectedRole"));
return (String)getContext(data).get("template") + TEMPLATE[19];
case 20:
/* buildContextForTemplate chef_site-addParticipant-differentRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("participantList", state.getAttribute(STATE_ADD_PARTICIPANTS));
return (String)getContext(data).get("template") + TEMPLATE[20];
case 21:
/* buildContextForTemplate chef_site-addParticipant-notification.vm
*
*/
context.put("title", site.getTitle());
context.put("sitePublished", Boolean.valueOf(site.isPublished()));
if (state.getAttribute("form_selectedNotify") == null)
{
state.setAttribute("form_selectedNotify", Boolean.FALSE);
}
context.put("notify", state.getAttribute("form_selectedNotify"));
boolean same_role = state.getAttribute("form_same_role")==null?true:((Boolean) state.getAttribute("form_same_role")).booleanValue();
if (same_role)
{
context.put("backIndex", "19");
}
else
{
context.put("backIndex", "20");
}
return (String)getContext(data).get("template") + TEMPLATE[21];
case 22:
/* buildContextForTemplate chef_site-addParticipant-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("participants", state.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("notify", state.getAttribute("form_selectedNotify"));
context.put("roles", getRoles(state));
context.put("same_role", state.getAttribute("form_same_role"));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("selectedRole", state.getAttribute("form_selectedRole"));
return (String)getContext(data).get("template") + TEMPLATE[22];
case 23:
/* buildContextForTemplate chef_siteInfo-editAccess-globalAccess.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
if (state.getAttribute("form_joinable") == null)
{
state.setAttribute("form_joinable", new Boolean(site.isJoinable()));
}
context.put("form_joinable", state.getAttribute("form_joinable"));
if (state.getAttribute("form_joinerRole") == null)
{
state.setAttribute("form_joinerRole", site.getJoinerRole());
}
context.put("form_joinerRole", state.getAttribute("form_joinerRole"));
return (String)getContext(data).get("template") + TEMPLATE[23];
case 24:
/* buildContextForTemplate chef_siteInfo-editAccess-globalAccess-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("form_joinable", state.getAttribute("form_joinable"));
context.put("form_joinerRole", state.getAttribute("form_joinerRole"));
return (String)getContext(data).get("template") + TEMPLATE[24];
case 25:
/* buildContextForTemplate chef_changeRoles-confirm.vm
*
*/
Boolean sameRole = (Boolean) state.getAttribute(STATE_CHANGEROLE_SAMEROLE);
context.put("sameRole", sameRole);
if (sameRole.booleanValue())
{
// same role
context.put("currentRole", state.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
}
else
{
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
roles = getRoles(state);
context.put("roles", roles);
context.put("participantSelectedList", state.getAttribute(STATE_SELECTED_PARTICIPANTS));
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) != null)
{
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
context.put("siteTitle", site.getTitle());
return (String)getContext(data).get("template") + TEMPLATE[25];
case 26:
/* buildContextForTemplate chef_site-modifyENW.vm
*
*/
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean existingSite = site != null? true:false;
if (existingSite)
{
// revising a existing site's tool
context.put("existingSite", Boolean.TRUE);
context.put("back", "4");
context.put("continue", "15");
context.put("function", "eventSubmit_doAdd_remove_features");
}
else
{
// new site
context.put("existingSite", Boolean.FALSE);
context.put("function", "eventSubmit_doAdd_features");
if (state.getAttribute(STATE_IMPORT) != null)
{
context.put("back", "27");
}
else
{
// new site, go to edit access page
context.put("back", "3");
}
context.put("continue", "18");
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
String emailId = (String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
if (emailId != null)
{
context.put("emailId", emailId);
}
//titles for news tools
newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
if (newsTitles == null)
{
newsTitles = new Hashtable();
newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE);
state.setAttribute(STATE_NEWS_TITLES, newsTitles);
}
context.put("newsTitles", newsTitles);
//urls for news tools
newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
if (newsUrls == null)
{
newsUrls = new Hashtable();
newsUrls.put("sakai.news", NEWS_DEFAULT_URL);
state.setAttribute(STATE_NEWS_URLS, newsUrls);
}
context.put("newsUrls", newsUrls);
// titles for web content tools
wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES);
if (wcTitles == null)
{
wcTitles = new Hashtable();
wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE);
state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles);
}
context.put("wcTitles", wcTitles);
//URLs for web content tools
wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS);
if (wcUrls == null)
{
wcUrls = new Hashtable();
wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL);
state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls);
}
context.put("wcUrls", wcUrls);
context.put("serverName", ServerConfigurationService.getServerName());
context.put("oldSelectedTools", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
return (String)getContext(data).get("template") + TEMPLATE[26];
case 27:
/* buildContextForTemplate chef_site-importSites.vm
*
*/
existingSite = site != null? true:false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (existingSite)
{
// revising a existing site's tool
context.put("continue", "12");
context.put("back", "28");
context.put("totalSteps", "2");
context.put("step", "2");
context.put("currentSite", site);
}
else
{
// new site, go to edit access page
context.put("back", "3");
if (fromENWModifyView(state))
{
context.put("continue", "26");
}
else
{
context.put("continue", "18");
}
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put ("selectedTools", orderToolIds(state, site_type, getToolsAvailableForImport(state))); // String toolId's
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
return (String)getContext(data).get("template") + TEMPLATE[27];
case 28:
/* buildContextForTemplate chef_siteinfo-import.vm
*
*/
context.put("currentSite", site);
context.put("importSiteList", state.getAttribute(STATE_IMPORT_SITES));
context.put("sites", SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null));
return (String)getContext(data).get("template") + TEMPLATE[28];
case 29:
/* buildContextForTemplate chef_siteinfo-duplicate.vm
*
*/
context.put("siteTitle", site.getTitle());
String sType = site.getType();
if (sType != null && sType.equals("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("currentTermId", site.getProperties().getProperty(PROP_SITE_TERM));
context.put("termList", getAvailableTerms());
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
if (state.getAttribute(SITE_DUPLICATED) == null)
{
context.put("siteDuplicated", Boolean.FALSE);
}
else
{
context.put("siteDuplicated", Boolean.TRUE);
context.put("duplicatedName", state.getAttribute(SITE_DUPLICATED_NAME));
}
return (String)getContext(data).get("template") + TEMPLATE[29];
case 36:
/*
* buildContextForTemplate chef_site-newSiteCourse.vm
*/
if (site != null)
{
context.put("site", site);
context.put("siteTitle", site.getTitle());
terms = CourseManagementService.getTerms();
if (terms != null && terms.size() >0)
{
context.put("termList", terms);
}
List providerCourseList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
context.put("providerCourseList", providerCourseList);
context.put("manualCourseList", state.getAttribute(SITE_MANUAL_COURSE_LIST));
Term t = (Term) state.getAttribute(STATE_TERM_SELECTED);
context.put ("term", t);
if (t != null)
{
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
List courses = CourseManagementService.getInstructorCourses(userId, t.getYear(), t.getTerm());
if (courses != null && courses.size() > 0)
{
Vector notIncludedCourse = new Vector();
// remove included sites
for (Iterator i = courses.iterator(); i.hasNext(); )
{
Course c = (Course) i.next();
if (!providerCourseList.contains(c.getId()))
{
notIncludedCourse.add(c);
}
}
state.setAttribute(STATE_TERM_COURSE_LIST, notIncludedCourse);
}
else
{
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
}
// step number used in UI
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1"));
}
else
{
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if(state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
context.put("selectedManualCourse", Boolean.TRUE);
}
context.put ("term", (Term) state.getAttribute(STATE_TERM_SELECTED));
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
context.put("backIndex", "1");
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
context.put("backIndex", "");
}
context.put("termCourseList", (List) state.getAttribute(STATE_TERM_COURSE_LIST));
return (String)getContext(data).get("template") + TEMPLATE[36];
case 37:
/*
* buildContextForTemplate chef_site-newSiteCourseManual.vm
*/
if (site != null)
{
context.put("site", site);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
}
buildInstructorSectionsList(state, params, context);
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("form_requiredFieldsSizes", CourseManagementService.getCourseIdRequiredFieldsSizes());
context.put("form_additional", siteInfo.additional);
context.put("form_title", siteInfo.title);
context.put("form_description", siteInfo.description);
context.put("noEmailInIdAccountName", ServerConfigurationService.getString("noEmailInIdAccountName", ""));
context.put("value_uniqname", state.getAttribute(STATE_SITE_QUEST_UNIQNAME));
int number = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put("currentNumber", new Integer(number));
}
context.put("currentNumber", new Integer(number));
context.put("listSize", new Integer(number-1));
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
List l = (List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
context.put ("selectedProviderCourse", l);
context.put("size", new Integer(l.size()-1));
}
if (site != null)
{
context.put("back", "36");
}
else
{
if (state.getAttribute(STATE_AUTO_ADD) != null)
{
context.put("autoAdd", Boolean.TRUE);
context.put("back", "36");
}
else
{
context.put("back", "1");
}
}
context.put("isFutureTerm", state.getAttribute(STATE_FUTURE_TERM_SELECTED));
context.put("weeksAhead", ServerConfigurationService.getString("roster.available.weeks.before.term.start", "0"));
return (String)getContext(data).get("template") + TEMPLATE[37];
case 42:
/* buildContextForTemplate chef_site-gradtoolsConfirm.vm
*
*/
siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
toolRegistrationList = (Vector) state.getAttribute(STATE_PROJECT_TOOL_LIST);
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, toolRegistrationList ); // %%% use Tool
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
context.put("include", new Boolean(siteInfo.include));
return (String)getContext(data).get("template") + TEMPLATE[42];
case 43:
/* buildContextForTemplate chef_siteInfo-editClass.vm
*
*/
bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null))
{
bar.add( new MenuEntry(rb.getString("java.addclasses"), "doMenu_siteInfo_addClass"));
}
context.put("menu", bar);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
return (String)getContext(data).get("template") + TEMPLATE[43];
case 44:
/* buildContextForTemplate chef_siteInfo-addCourseConfirm.vm
*
*/
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
context.put("providerAddCourses", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int addNumber = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue() -1;
context.put("manualAddNumber", new Integer(addNumber));
context.put("requestFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("backIndex", "37");
}
else
{
context.put("backIndex", "36");
}
//those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[44];
//htripath - import materials from classic
case 45:
/* buildContextForTemplate chef_siteInfo-importMtrlMaster.vm
*
*/
return (String)getContext(data).get("template") + TEMPLATE[45];
case 46:
/* buildContextForTemplate chef_siteInfo-importMtrlCopy.vm
*
*/
// this is for list display in listbox
context.put("allZipSites", state.getAttribute(ALL_ZIP_IMPORT_SITES));
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
//zip file
//context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME));
return (String)getContext(data).get("template") + TEMPLATE[46];
case 47:
/* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[47];
case 48:
/* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[48];
case 49:
/* buildContextForTemplate chef_siteInfo-group.vm
*
*/
context.put("site", site);
bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowUpdateSite(site.getId()) || SiteService.allowUpdateGroupMembership(site.getId()))
{
bar.add( new MenuEntry(rb.getString("java.new"), "doGroup_new"));
}
context.put("menu", bar);
// the group list
sortedBy = (String) state.getAttribute (SORTED_BY);
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
// only show groups created by WSetup tool itself
Collection groups = (Collection) site.getGroups();
List groupsByWSetup = new Vector();
for(Iterator gIterator = groups.iterator(); gIterator.hasNext();)
{
Group gNext = (Group) gIterator.next();
String gProp = gNext.getProperties().getProperty(GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString()))
{
groupsByWSetup.add(gNext);
}
}
if (sortedBy != null && sortedAsc != null)
{
context.put("groups", new SortedIterator (groupsByWSetup.iterator (), new SiteComparator (sortedBy, sortedAsc)));
}
return (String)getContext(data).get("template") + TEMPLATE[49];
case 50:
/* buildContextForTemplate chef_siteInfo-groupedit.vm
*
*/
Group g = getStateGroup(state);
if (g != null)
{
context.put("group", g);
context.put("newgroup", Boolean.FALSE);
}
else
{
context.put("newgroup", Boolean.TRUE);
}
if (state.getAttribute(STATE_GROUP_TITLE) != null)
{
context.put("title", state.getAttribute(STATE_GROUP_TITLE));
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null)
{
context.put("description", state.getAttribute(STATE_GROUP_DESCRIPTION));
}
Iterator siteMembers = new SortedIterator (getParticipantList(state).iterator (), new SiteComparator (SORTED_BY_PARTICIPANT_NAME, Boolean.TRUE.toString()));
if (siteMembers != null && siteMembers.hasNext())
{
context.put("generalMembers", siteMembers);
}
Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
if (state.getAttribute(STATE_GROUP_MEMBERS) != null)
{
context.put("groupMembers", new SortedIterator(groupMembersSet.iterator(), new SiteComparator (SORTED_BY_MEMBER_NAME, Boolean.TRUE.toString())));
}
context.put("groupMembersClone", groupMembersSet);
context.put("userDirectoryService", UserDirectoryService.getInstance());
return (String)getContext(data).get("template") + TEMPLATE[50];
case 51:
/* buildContextForTemplate chef_siteInfo-groupDeleteConfirm.vm
*
*/
context.put("site", site);
context.put("removeGroupIds", new ArrayList(Arrays.asList((String[])state.getAttribute(STATE_GROUP_REMOVE))));
return (String)getContext(data).get("template") + TEMPLATE[51];
}
// should never be reached
return (String)getContext(data).get("template") + TEMPLATE[0];
} // buildContextForTemplate
| private String buildContextForTemplate (int index, VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
String realmId = "";
String site_type = "";
String sortedBy = "";
String sortedAsc = "";
ParameterParser params = data.getParameters ();
context.put("tlang",rb);
context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
else
{
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
// Lists used in more than one template
// Access
List roles = new Vector();
// the hashtables for News and Web Content tools
Hashtable newsTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable wcUrls = new Hashtable();
List toolRegistrationList = new Vector();
List toolRegistrationSelectedList = new Vector();
ResourceProperties siteProperties = null;
// for showing site creation steps
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null)
{
context.put("totalSteps", state.getAttribute(SITE_CREATE_TOTAL_STEPS));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null)
{
context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP));
}
String hasGradSites = ServerConfigurationService.getString("withDissertation", Boolean.FALSE.toString());
Site site = getStateSite(state);
switch (index)
{
case 0:
/* buildContextForTemplate chef_site-list.vm
*
*/
// site types
List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);
//make sure auto-updates are enabled
Hashtable views = new Hashtable();
if (SecurityService.isSuperUser())
{
views.put(rb.getString("java.allmy"), rb.getString("java.allmy"));
views.put(rb.getString("java.my") + " " + rb.getString("java.sites"), rb.getString("java.my"));
for(int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++)
{
String type = (String) sTypes.get(sTypeIndex);
views.put(type + " " + rb.getString("java.sites"), type);
}
if (hasGradSites.equalsIgnoreCase("true"))
{
views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb.getString("java.gradtools"));
}
if(state.getAttribute(STATE_VIEW_SELECTED) == null)
{
state.setAttribute(STATE_VIEW_SELECTED, rb.getString("java.allmy"));
}
context.put("superUser", Boolean.TRUE);
}
else
{
context.put("superUser", Boolean.FALSE);
views.put(rb.getString("java.allmy"), rb.getString("java.allmy"));
// if there is a GradToolsStudent choice inside
boolean remove = false;
if (hasGradSites.equalsIgnoreCase("true"))
{
try
{
//the Grad Tools site option is only presented to GradTools Candidates
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
//am I a grad student?
if (!isGradToolsCandidate(userId))
{
// not a gradstudent
remove = true;
}
}
catch(Exception e)
{
remove = true;
}
}
else
{
// not support for dissertation sites
remove=true;
}
//do not show this site type in views
//sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT));
for(int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++)
{
String type = (String) sTypes.get(sTypeIndex);
if(!type.equals(SITE_TYPE_GRADTOOLS_STUDENT))
{
views.put(type + " "+rb.getString("java.sites"), type);
}
}
if (!remove)
{
views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb.getString("java.gradtools"));
}
//default view
if(state.getAttribute(STATE_VIEW_SELECTED) == null)
{
state.setAttribute(STATE_VIEW_SELECTED, rb.getString("java.allmy"));
}
}
context.put("views", views);
if(state.getAttribute(STATE_VIEW_SELECTED) != null)
{
context.put("viewSelected", (String) state.getAttribute(STATE_VIEW_SELECTED));
}
String search = (String) state.getAttribute(STATE_SEARCH);
context.put("search_term", search);
sortedBy = (String) state.getAttribute (SORTED_BY);
if (sortedBy == null)
{
state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
sortedBy = SortType.TITLE_ASC.toString();
}
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if (sortedAsc == null)
{
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
String portalUrl = ServerConfigurationService.getPortalUrl();
context.put("portalUrl", portalUrl);
List sites = prepPage(state);
state.setAttribute(STATE_SITES, sites);
context.put("sites", sites);
context.put("totalPageNumber", new Integer(totalPageNumber(state)));
context.put("searchString", state.getAttribute(STATE_SEARCH));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
// put the service in the context (used for allow update calls on each site)
context.put("service", SiteService.getInstance());
context.put("sortby_title", SortType.TITLE_ASC.toString());
context.put("sortby_type", SortType.TYPE_ASC.toString());
context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
// top menu bar
Menu bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null))
{
bar.add( new MenuEntry(rb.getString("java.new"), "doNew_site"));
}
bar.add( new MenuEntry(rb.getString("java.revise"), null, true, MenuItem.CHECKED_NA, "doGet_site", "sitesForm"));
bar.add( new MenuEntry(rb.getString("java.delete"), null, true, MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm"));
context.put("menu", bar);
// default to be no pageing
context.put("paged", Boolean.FALSE);
Menu bar2 = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
// add the search commands
addSearchMenus(bar2, state);
context.put("menu2", bar2);
pagingInfoToContext(state, context);
return (String)getContext(data).get("template") + TEMPLATE[0];
case 1:
/* buildContextForTemplate chef_site-type.vm
*
*/
if (hasGradSites.equalsIgnoreCase("true"))
{
context.put("withDissertation", Boolean.TRUE);
try
{
//the Grad Tools site option is only presented to UM grad students
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
//am I a UM grad student?
Boolean isGradStudent = new Boolean(isGradToolsCandidate(userId));
context.put("isGradStudent", isGradStudent);
//if I am a UM grad student, do I already have a Grad Tools site?
boolean noGradToolsSite = true;
if(hasGradToolsStudentSite(userId))
noGradToolsSite = false;
context.put("noGradToolsSite", new Boolean(noGradToolsSite));
}
catch(Exception e)
{
if(Log.isWarnEnabled())
{
M_log.warn("buildContextForTemplate chef_site-type.vm " + e);
}
}
}
else
{
context.put("withDissertation", Boolean.FALSE);
}
List types = (List) state.getAttribute(STATE_SITE_TYPES);
context.put("siteTypes", types);
// put selected/default site type into context
if (siteInfo.site_type != null && siteInfo.site_type.length() >0)
{
context.put("typeSelected", siteInfo.site_type);
}
else if (types.size() > 0)
{
context.put("typeSelected", types.get(0));
}
List termsForSiteCreation = getAvailableTerms();
if (termsForSiteCreation.size() > 0)
{
context.put("termList", termsForSiteCreation);
}
if (state.getAttribute(STATE_TERM_SELECTED) != null)
{
context.put("selectedTerm", state.getAttribute(STATE_TERM_SELECTED));
}
return (String)getContext(data).get("template") + TEMPLATE[1];
case 2:
/* buildContextForTemplate chef_site-newSiteInformation.vm
*
*/
context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES));
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("titleEditableSiteType", state.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", siteType);
if (siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put ("manualAddNumber", new Integer(number - 1));
context.put ("manualAddFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("back", "37");
}
else
{
context.put("back", "36");
}
context.put ("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null)
{
context.put("selectedIcon", siteInfo.getIconUrl());
}
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null)
{
context.put(FORM_ICON_URL, siteInfo.iconUrl);
}
context.put ("back", "1");
}
context.put (FORM_TITLE,siteInfo.title);
context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description);
context.put (FORM_DESCRIPTION,siteInfo.description);
// defalt the site contact person to the site creator
if (siteInfo.site_contact_name.equals(NULL_STRING) && siteInfo.site_contact_email.equals(NULL_STRING))
{
User user = UserDirectoryService.getCurrentUser();
siteInfo.site_contact_name = user.getDisplayName();
siteInfo.site_contact_email = user.getEmail();
}
context.put("form_site_contact_name", siteInfo.site_contact_name);
context.put("form_site_contact_email", siteInfo.site_contact_email);
// those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[2];
case 3:
/* buildContextForTemplate chef_site-newSiteFeatures.vm
*
*/
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType!=null && siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
}
context.put("defaultTools", ServerConfigurationService.getToolsRequired(siteType));
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// If this is the first time through, check for tools
// which should be selected by default.
List defaultSelectedTools = ServerConfigurationService.getDefaultTools(siteType);
if (toolRegistrationSelectedList == null) {
toolRegistrationSelectedList = new Vector(defaultSelectedTools);
}
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST) ); // %%% use ToolRegistrations for template list
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
// The "Home" tool checkbox needs special treatment to be selected by
// default.
Boolean checkHome = (Boolean)state.getAttribute(STATE_TOOL_HOME_SELECTED);
if (checkHome == null) {
if ((defaultSelectedTools != null) && defaultSelectedTools.contains(HOME_TOOL_ID)) {
checkHome = Boolean.TRUE;
}
}
context.put("check_home", checkHome);
//titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
//titles for web content tools
context.put("wcTitles", state.getAttribute(STATE_WEB_CONTENT_TITLES));
//urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
//urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put("sites", SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null));
context.put("import", state.getAttribute(STATE_IMPORT));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[3];
case 4:
/* buildContextForTemplate chef_site-addRemoveFeatures.vm
*
*/
context.put("SiteTitle", site.getTitle());
String type = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("defaultTools", ServerConfigurationService.getToolsRequired(type));
boolean myworkspace_site = false;
//Put up tool lists filtered by category
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes.contains(type))
{
myworkspace_site = false;
}
if (SiteService.isUserSite(site.getId()) || (type!=null && type.equalsIgnoreCase("myworkspace")))
{
myworkspace_site = true;
type="myworkspace";
}
context.put ("myworkspace_site", new Boolean(myworkspace_site));
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST));
//titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
//titles for web content tools
context.put("wcTitles", state.getAttribute(STATE_WEB_CONTENT_TITLES));
//urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
//urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
//get the email alias when an Email Archive tool has been selected
String channelReference = mailArchiveChannelReference(site.getId());
List aliases = AliasService.getAliases(channelReference, 1, 1);
if (aliases.size() > 0)
{
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases.get(0)).getId());
}
else
{
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null)
{
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService.getServerName());
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[4];
case 5:
/* buildContextForTemplate chef_site-addParticipant.vm
*
*/
context.put("title", site.getTitle());
roles = getRoles(state);
context.put("roles", roles);
// Note that (for now) these strings are in both sakai.properties and sitesetupgeneric.properties
context.put("noEmailInIdAccountName", ServerConfigurationService.getString("noEmailInIdAccountName"));
context.put("noEmailInIdAccountLabel", ServerConfigurationService.getString("noEmailInIdAccountLabel"));
context.put("emailInIdAccountName", ServerConfigurationService.getString("emailInIdAccountName"));
context.put("emailInIdAccountLabel", ServerConfigurationService.getString("emailInIdAccountLabel"));
if(state.getAttribute("noEmailInIdAccountValue")!=null)
{
context.put("noEmailInIdAccountValue", (String)state.getAttribute("noEmailInIdAccountValue"));
}
if(state.getAttribute("emailInIdAccountValue")!=null)
{
context.put("emailInIdAccountValue", (String)state.getAttribute("emailInIdAccountValue"));
}
if(state.getAttribute("form_same_role") != null)
{
context.put("form_same_role", ((Boolean) state.getAttribute("form_same_role")).toString());
}
else
{
context.put("form_same_role", Boolean.TRUE.toString());
}
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[5];
case 6:
/* buildContextForTemplate chef_site-removeParticipants.vm
*
*/
context.put("title", site.getTitle());
realmId = SiteService.siteReference(site.getId());
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
try
{
List removeableList = (List) state.getAttribute(STATE_REMOVEABLE_USER_LIST);
List removeableParticipants = new Vector();
for (int k = 0; k < removeableList.size(); k++)
{
User user = UserDirectoryService.getUser((String) removeableList.get(k));
Participant participant = new Participant();
participant.name = user.getSortName();
participant.uniqname = user.getId();
Role r = realm.getUserRole(user.getId());
if (r != null)
{
participant.role = r.getId();
}
removeableParticipants.add(participant);
}
context.put("removeableList", removeableParticipants);
}
catch (UserNotDefinedException ee)
{
}
}
catch (GroupNotDefinedException e)
{
}
context.put("backIndex", "18");
return (String)getContext(data).get("template") + TEMPLATE[6];
case 7:
/* buildContextForTemplate chef_site-changeRoles.vm
*
*/
context.put("same_role", state.getAttribute(STATE_CHANGEROLE_SAMEROLE));
roles = getRoles(state);
context.put("roles", roles);
context.put("currentRole", state.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
context.put("participantSelectedList", state.getAttribute(STATE_SELECTED_PARTICIPANTS));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("siteTitle", site.getTitle());
return (String)getContext(data).get("template") + TEMPLATE[7];
case 8:
/* buildContextForTemplate chef_site-siteDeleteConfirm.vm
*
*/
String site_title = NULL_STRING;
String[] removals = (String[]) state.getAttribute(STATE_SITE_REMOVALS);
List remove = new Vector();
String user = SessionManager.getCurrentSessionUserId();
String workspace = SiteService.getUserSiteId(user);
if( removals != null && removals.length != 0 )
{
for (int i = 0; i < removals.length; i++ )
{
String id = (String) removals[i];
if(!(id.equals(workspace)))
{
try
{
site_title = SiteService.getSite(id).getTitle();
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.doSite_delete_confirmed - IdUnusedException " + id);
addAlert(state, rb.getString("java.sitewith")+" " + id + " "+rb.getString("java.couldnt")+" ");
}
if(SiteService.allowRemoveSite(id))
{
try
{
Site removeSite = SiteService.getSite(id);
remove.add(removeSite);
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException");
}
}
else
{
addAlert(state, site_title + " "+rb.getString("java.couldntdel") + " ");
}
}
else
{
addAlert(state, rb.getString("java.yourwork"));
}
}
if(remove.size() == 0)
{
addAlert(state, rb.getString("java.click"));
}
}
context.put("removals", remove);
return (String)getContext(data).get("template") + TEMPLATE[8];
case 9:
/* buildContextForTemplate chef_site-publishUnpublish.vm
*
*/
context.put("publish", Boolean.valueOf(((SiteInfo)state.getAttribute(STATE_SITE_INFO)).getPublished()));
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[9];
case 10:
/* buildContextForTemplate chef_site-newSiteConfirm.vm
*
*/
siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put ("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put ("manualAddNumber", new Integer(number - 1));
context.put ("manualAddFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put ("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null)
{
context.put("selectedIcon", siteInfo.getIconUrl());
}
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType!=null && siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null)
{
context.put("iconUrl", siteInfo.iconUrl);
}
}
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("siteContactName", siteInfo.site_contact_name);
context.put("siteContactEmail", siteInfo.site_contact_email);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use Tool
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
context.put("include", new Boolean(siteInfo.include));
context.put("published", new Boolean(siteInfo.published));
context.put("joinable", new Boolean(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
context.put("newsTitles", (Hashtable) state.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES));
// back to edit access page
context.put("back", "18");
context.put("importSiteTools", state.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("siteService", SiteService.getInstance());
// those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[10];
case 11:
/* buildContextForTemplate chef_site-newSitePublishUnpublish.vm
*
*/
return (String)getContext(data).get("template") + TEMPLATE[11];
case 12:
/* buildContextForTemplate chef_site-siteInfo-list.vm
*
*/
context.put("userDirectoryService", UserDirectoryService.getInstance());
try
{
siteProperties = site.getProperties();
siteType = site.getType();
if (siteType != null)
{
state.setAttribute(STATE_SITE_TYPE, siteType);
}
boolean isMyWorkspace = false;
if (SiteService.isUserSite(site.getId()))
{
if (SiteService.getSiteUserId(site.getId()).equals(SessionManager.getCurrentSessionUserId()))
{
isMyWorkspace = true;
context.put("siteUserId", SiteService.getSiteUserId(site.getId()));
}
}
context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));
String siteId = site.getId();
if (state.getAttribute(STATE_ICONS)!= null)
{
List skins = (List)state.getAttribute(STATE_ICONS);
for (int i = 0; i < skins.size(); i++)
{
Icon s = (Icon)skins.get(i);
if(!StringUtil.different(s.getUrl(), site.getIconUrl()))
{
context.put("siteUnit", s.getName());
break;
}
}
}
context.put("siteIcon", site.getIconUrl());
context.put("siteTitle", site.getTitle());
context.put("siteDescription", site.getDescription());
context.put("siteJoinable", new Boolean(site.isJoinable()));
if(site.isPublished())
{
context.put("published", Boolean.TRUE);
}
else
{
context.put("published", Boolean.FALSE);
context.put("owner", site.getCreatedBy().getSortName());
}
Time creationTime = site.getCreatedTime();
if (creationTime != null)
{
context.put("siteCreationDate", creationTime.toStringLocalFull());
}
boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));
boolean allowUpdateGroupMembership = SiteService.allowUpdateGroupMembership(siteId);
context.put("allowUpdateGroupMembership", Boolean.valueOf(allowUpdateGroupMembership));
boolean allowUpdateSiteMembership = SiteService.allowUpdateSiteMembership(siteId);
context.put("allowUpdateSiteMembership", Boolean.valueOf(allowUpdateSiteMembership));
if (allowUpdateSite)
{
// top menu bar
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace)
{
b.add( new MenuEntry(rb.getString("java.editsite"), "doMenu_edit_site_info"));
}
b.add( new MenuEntry(rb.getString("java.edittools"), "doMenu_edit_site_tools"));
if (!isMyWorkspace
&& (ServerConfigurationService.getString("wsetup.group.support") == ""
|| ServerConfigurationService.getString("wsetup.group.support").equalsIgnoreCase(Boolean.TRUE.toString())))
{
// show the group toolbar unless configured to not support group
b.add( new MenuEntry(rb.getString("java.group"), "doMenu_group"));
}
if (!isMyWorkspace)
{
List gradToolsSiteTypes = (List) state.getAttribute(GRADTOOLS_SITE_TYPES);
boolean isGradToolSite = false;
if (siteType != null && gradToolsSiteTypes.contains(siteType))
{
isGradToolSite = true;
}
if (siteType == null
|| siteType != null && !isGradToolSite)
{
// hide site access for GRADTOOLS type of sites
b.add( new MenuEntry(rb.getString("java.siteaccess"), "doMenu_edit_site_access"));
}
b.add( new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant"));
if (siteType != null && siteType.equals("course"))
{
b.add( new MenuEntry(rb.getString("java.editc"), "doMenu_siteInfo_editClass"));
}
if (siteType == null || siteType != null && !isGradToolSite)
{
// hide site duplicate and import for GRADTOOLS type of sites
b.add( new MenuEntry(rb.getString("java.duplicate"), "doMenu_siteInfo_duplicate"));
List updatableSites = SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null);
// import link should be visible even if only one site
if (updatableSites.size() > 0)
{
b.add( new MenuEntry(rb.getString("java.import"), "doMenu_siteInfo_import"));
// a configuration param for showing/hiding import from file choice
String importFromFile = ServerConfigurationService.getString("site.setup.import.file", Boolean.TRUE.toString());
if (importFromFile.equalsIgnoreCase("true"))
{
//htripath: June 4th added as per Kris and changed desc of above
b.add(new MenuEntry(rb.getString("java.importFile"), "doAttachmentsMtrlFrmFile"));
}
}
}
}
// if the page order helper is available, not stealthed and not hidden, show the link
if (ToolManager.getTool("sakai-site-pageorder-helper") != null
&& !ServerConfigurationService
.getString("[email protected]")
.contains("sakai-site-pageorder-helper")
&& !ServerConfigurationService
.getString("[email protected]")
.contains("sakai-site-pageorder-helper"))
{
b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper"));
}
context.put("menu", b);
}
if (allowUpdateGroupMembership)
{
// show Manage Groups menu
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace
&& (ServerConfigurationService.getString("wsetup.group.support") == ""
|| ServerConfigurationService.getString("wsetup.group.support").equalsIgnoreCase(Boolean.TRUE.toString())))
{
// show the group toolbar unless configured to not support group
b.add( new MenuEntry(rb.getString("java.group"), "doMenu_group"));
}
context.put("menu", b);
}
if (allowUpdateSiteMembership)
{
// show add participant menu
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace)
{
// show the Add Participant menu
b.add( new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant"));
}
context.put("menu", b);
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
// editing from worksite setup tool
context.put("fromWSetup", Boolean.TRUE);
if (state.getAttribute(STATE_PREV_SITE) != null)
{
context.put("prevSite", state.getAttribute(STATE_PREV_SITE));
}
if (state.getAttribute(STATE_NEXT_SITE) != null)
{
context.put("nextSite", state.getAttribute(STATE_NEXT_SITE));
}
}
else
{
context.put("fromWSetup", Boolean.FALSE);
}
//allow view roster?
boolean allowViewRoster = SiteService.allowViewRoster(siteId);
if (allowViewRoster)
{
context.put("viewRoster", Boolean.TRUE);
}
else
{
context.put("viewRoster", Boolean.FALSE);
}
//set participant list
if (allowUpdateSite || allowViewRoster || allowUpdateSiteMembership)
{
List participants = new Vector();
participants = getParticipantList(state);
sortedBy = (String) state.getAttribute (SORTED_BY);
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if(sortedBy==null)
{
state.setAttribute(SORTED_BY, SORTED_BY_PARTICIPANT_NAME);
sortedBy = SORTED_BY_PARTICIPANT_NAME;
}
if (sortedAsc==null)
{
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
Iterator sortedParticipants = null;
if (sortedBy != null)
{
sortedParticipants = new SortedIterator (participants.iterator (), new SiteComparator (sortedBy, sortedAsc));
participants.clear();
while (sortedParticipants.hasNext())
{
participants.add(sortedParticipants.next());
}
}
context.put("participantListSize", new Integer(participants.size()));
context.put("participantList", prepPage(state));
pagingInfoToContext(state, context);
}
context.put("include", Boolean.valueOf(site.isPubView()));
// site contact information
String contactName = siteProperties.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null)
{
User u = site.getCreatedBy();
String email = u.getEmail();
if (email != null)
{
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
if (contactName != null)
{
context.put("contactName", contactName);
}
if (contactEmail != null)
{
context.put("contactEmail", contactEmail);
}
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
List providerCourseList = getProviderCourseList(StringUtil.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null)
{
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
context.put("providerCourseList", providerCourseList);
}
String manualCourseListString = site.getProperties().getProperty(PROP_SITE_REQUEST_COURSE);
if (manualCourseListString != null)
{
List manualCourseList = new Vector();
if (manualCourseListString.indexOf("+") != -1)
{
manualCourseList = new ArrayList(Arrays.asList(manualCourseListString.split("\\+")));
}
else
{
manualCourseList.add(manualCourseListString);
}
state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList);
context.put("manualCourseList", manualCourseList);
}
context.put("term", siteProperties.getProperty(PROP_SITE_TERM));
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
}
catch (Exception e)
{
M_log.warn(this + " site info list: " + e.toString());
}
roles = getRoles(state);
context.put("roles", roles);
// will have the choice to active/inactive user or not
String activeInactiveUser = ServerConfigurationService.getString("activeInactiveUser", Boolean.FALSE.toString());
if (activeInactiveUser.equalsIgnoreCase("true"))
{
context.put("activeInactiveUser", Boolean.TRUE);
// put realm object into context
realmId = SiteService.siteReference(site.getId());
try
{
context.put("realm", AuthzGroupService.getAuthzGroup(realmId));
}
catch (GroupNotDefinedException e)
{
M_log.warn(this + " IdUnusedException " + realmId);
}
}
else
{
context.put("activeInactiveUser", Boolean.FALSE);
}
context.put("groupsWithMember", site.getGroupsWithMember(UserDirectoryService.getCurrentUser().getId()));
return (String)getContext(data).get("template") + TEMPLATE[12];
case 13:
/* buildContextForTemplate chef_site-siteInfo-editInfo.vm
*
*/
siteProperties = site.getProperties();
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("titleEditableSiteType", state.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", site.getType());
List terms = CourseManagementService.getTerms();
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("skins", state.getAttribute(STATE_ICONS));
if (state.getAttribute(FORM_SITEINFO_SKIN) != null)
{
context.put("selectedIcon",state.getAttribute(FORM_SITEINFO_SKIN));
}
else if (site.getIconUrl() != null)
{
context.put("selectedIcon",site.getIconUrl());
}
if (terms != null && terms.size() >0)
{
context.put("termList", terms);
}
if (state.getAttribute(FORM_SITEINFO_TERM) == null)
{
String currentTerm = site.getProperties().getProperty(PROP_SITE_TERM);
if (currentTerm != null)
{
state.setAttribute(FORM_SITEINFO_TERM, currentTerm);
}
}
if (state.getAttribute(FORM_SITEINFO_TERM) != null)
{
context.put("selectedTerm", state.getAttribute(FORM_SITEINFO_TERM));
}
}
else
{
context.put("isCourseSite", Boolean.FALSE);
if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null && StringUtil.trimToNull(site.getIconUrl()) != null)
{
state.setAttribute(FORM_SITEINFO_ICON_URL, site.getIconUrl());
}
if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null)
{
context.put("iconUrl", state.getAttribute(FORM_SITEINFO_ICON_URL));
}
}
context.put("description", state.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("short_description", state.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("form_site_contact_name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("form_site_contact_email", state.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
//Display of appearance icon/url list with course site based on
// "disable.course.site.skin.selection" value set with sakai.properties file.
if ((ServerConfigurationService.getString("disable.course.site.skin.selection")).equals("true")){
context.put("disableCourseSelection", Boolean.TRUE);
}
return (String)getContext(data).get("template") + TEMPLATE[13];
case 14:
/* buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm
*
*/
siteProperties = site.getProperties();
siteType = (String)state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM));
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
context.put("oTitle", site.getTitle());
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("description", state.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("oDescription", site.getDescription());
context.put("short_description", state.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("oShort_description", site.getShortDescription());
context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN));
context.put("oSkin", site.getIconUrl());
context.put("skins", state.getAttribute(STATE_ICONS));
context.put("oIcon", site.getIconUrl());
context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL));
context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE));
context.put("oInclude", Boolean.valueOf(site.isPubView()));
context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("oName", siteProperties.getProperty(PROP_SITE_CONTACT_NAME));
context.put("email", state.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
context.put("oEmail", siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL));
return (String)getContext(data).get("template") + TEMPLATE[14];
case 15:
/* buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm
*
*/
context.put("title", site.getTitle());
site_type = (String)state.getAttribute(STATE_SITE_TYPE);
myworkspace_site = false;
if (SiteService.isUserSite(site.getId()))
{
if (SiteService.getSiteUserId(site.getId()).equals(SessionManager.getCurrentSessionUserId()))
{
myworkspace_site = true;
site_type = "myworkspace";
}
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("selectedTools", orderToolIds(state, (String) state.getAttribute(STATE_SITE_TYPE), (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)));
context.put("oldSelectedTools", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("oldSelectedHome", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME));
context.put("continueIndex", "12");
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null)
{
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService.getServerName());
context.put("newsTitles", (Hashtable) state.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES));
if (fromENWModifyView(state))
{
context.put("back", "26");
}
else
{
context.put("back", "4");
}
return (String)getContext(data).get("template") + TEMPLATE[15];
case 16:
/* buildContextForTemplate chef_site-publishUnpublish-sendEmail.vm
*
*/
context.put("title", site.getTitle());
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String)getContext(data).get("template") + TEMPLATE[16];
case 17:
/* buildContextForTemplate chef_site-publishUnpublish-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("continueIndex", "12");
SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (sInfo.getPublished())
{
context.put("publish", Boolean.TRUE);
context.put("backIndex", "16");
}
else
{
context.put("publish", Boolean.FALSE);
context.put("backIndex", "9");
}
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String)getContext(data).get("template") + TEMPLATE[17];
case 18:
/* buildContextForTemplate chef_siteInfo-editAccess.vm
*
*/
List publicChangeableSiteTypes = (List) state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
List unJoinableSiteTypes = (List) state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);
if (site != null)
{
//editing existing site
context.put("site", site);
siteType = state.getAttribute(STATE_SITE_TYPE)!=null?(String)state.getAttribute(STATE_SITE_TYPE):null;
if ( siteType != null
&& publicChangeableSiteTypes.contains(siteType))
{
context.put ("publicChangeable", Boolean.TRUE);
}
else
{
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(site.isPubView()));
if ( siteType != null && !unJoinableSiteTypes.contains(siteType))
{
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
if (state.getAttribute(STATE_JOINABLE) == null)
{
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site.isJoinable()));
}
if (state.getAttribute(STATE_JOINERROLE) == null
|| state.getAttribute(STATE_JOINABLE) != null && ((Boolean) state.getAttribute(STATE_JOINABLE)).booleanValue())
{
state.setAttribute(STATE_JOINERROLE, site.getJoinerRole());
}
if (state.getAttribute(STATE_JOINABLE) != null)
{
context.put("joinable", state.getAttribute(STATE_JOINABLE));
}
if (state.getAttribute(STATE_JOINERROLE) != null)
{
context.put("joinerRole", state.getAttribute(STATE_JOINERROLE));
}
}
else
{
//site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
context.put("roles", getRoles(state));
context.put("back", "12");
}
else
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if ( siteInfo.site_type != null
&& publicChangeableSiteTypes.contains(siteInfo.site_type))
{
context.put ("publicChangeable", Boolean.TRUE);
}
else
{
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(siteInfo.getInclude()));
context.put("published", Boolean.valueOf(siteInfo.getPublished()));
if ( siteInfo.site_type != null && !unJoinableSiteTypes.contains(siteInfo.site_type))
{
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
}
else
{
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
// use the type's template, if defined
String realmTemplate = "!site.template";
if (siteInfo.site_type != null)
{
realmTemplate = realmTemplate + "." + siteInfo.site_type;
}
try
{
AuthzGroup r = AuthzGroupService.getAuthzGroup(realmTemplate);
context.put("roles", r.getRoles());
}
catch (GroupNotDefinedException e)
{
try
{
AuthzGroup rr = AuthzGroupService.getAuthzGroup("!site.template");
context.put("roles", rr.getRoles());
}
catch (GroupNotDefinedException ee)
{
}
}
// new site, go to confirmation page
context.put("continue", "10");
if (fromENWModifyView(state))
{
context.put("back", "26");
}
else if (state.getAttribute(STATE_IMPORT) != null)
{
context.put("back", "27");
}
else
{
context.put("back", "3");
}
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType!=null && siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
}
}
return (String)getContext(data).get("template") + TEMPLATE[18];
case 19:
/* buildContextForTemplate chef_site-addParticipant-sameRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("participantList", state.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("form_selectedRole", state.getAttribute("form_selectedRole"));
return (String)getContext(data).get("template") + TEMPLATE[19];
case 20:
/* buildContextForTemplate chef_site-addParticipant-differentRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("participantList", state.getAttribute(STATE_ADD_PARTICIPANTS));
return (String)getContext(data).get("template") + TEMPLATE[20];
case 21:
/* buildContextForTemplate chef_site-addParticipant-notification.vm
*
*/
context.put("title", site.getTitle());
context.put("sitePublished", Boolean.valueOf(site.isPublished()));
if (state.getAttribute("form_selectedNotify") == null)
{
state.setAttribute("form_selectedNotify", Boolean.FALSE);
}
context.put("notify", state.getAttribute("form_selectedNotify"));
boolean same_role = state.getAttribute("form_same_role")==null?true:((Boolean) state.getAttribute("form_same_role")).booleanValue();
if (same_role)
{
context.put("backIndex", "19");
}
else
{
context.put("backIndex", "20");
}
return (String)getContext(data).get("template") + TEMPLATE[21];
case 22:
/* buildContextForTemplate chef_site-addParticipant-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("participants", state.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("notify", state.getAttribute("form_selectedNotify"));
context.put("roles", getRoles(state));
context.put("same_role", state.getAttribute("form_same_role"));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("selectedRole", state.getAttribute("form_selectedRole"));
return (String)getContext(data).get("template") + TEMPLATE[22];
case 23:
/* buildContextForTemplate chef_siteInfo-editAccess-globalAccess.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
if (state.getAttribute("form_joinable") == null)
{
state.setAttribute("form_joinable", new Boolean(site.isJoinable()));
}
context.put("form_joinable", state.getAttribute("form_joinable"));
if (state.getAttribute("form_joinerRole") == null)
{
state.setAttribute("form_joinerRole", site.getJoinerRole());
}
context.put("form_joinerRole", state.getAttribute("form_joinerRole"));
return (String)getContext(data).get("template") + TEMPLATE[23];
case 24:
/* buildContextForTemplate chef_siteInfo-editAccess-globalAccess-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("form_joinable", state.getAttribute("form_joinable"));
context.put("form_joinerRole", state.getAttribute("form_joinerRole"));
return (String)getContext(data).get("template") + TEMPLATE[24];
case 25:
/* buildContextForTemplate chef_changeRoles-confirm.vm
*
*/
Boolean sameRole = (Boolean) state.getAttribute(STATE_CHANGEROLE_SAMEROLE);
context.put("sameRole", sameRole);
if (sameRole.booleanValue())
{
// same role
context.put("currentRole", state.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
}
else
{
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
roles = getRoles(state);
context.put("roles", roles);
context.put("participantSelectedList", state.getAttribute(STATE_SELECTED_PARTICIPANTS));
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) != null)
{
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
context.put("siteTitle", site.getTitle());
return (String)getContext(data).get("template") + TEMPLATE[25];
case 26:
/* buildContextForTemplate chef_site-modifyENW.vm
*
*/
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean existingSite = site != null? true:false;
if (existingSite)
{
// revising a existing site's tool
context.put("existingSite", Boolean.TRUE);
context.put("back", "4");
context.put("continue", "15");
context.put("function", "eventSubmit_doAdd_remove_features");
}
else
{
// new site
context.put("existingSite", Boolean.FALSE);
context.put("function", "eventSubmit_doAdd_features");
if (state.getAttribute(STATE_IMPORT) != null)
{
context.put("back", "27");
}
else
{
// new site, go to edit access page
context.put("back", "3");
}
context.put("continue", "18");
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
String emailId = (String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
if (emailId != null)
{
context.put("emailId", emailId);
}
//titles for news tools
newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
if (newsTitles == null)
{
newsTitles = new Hashtable();
newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE);
state.setAttribute(STATE_NEWS_TITLES, newsTitles);
}
context.put("newsTitles", newsTitles);
//urls for news tools
newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
if (newsUrls == null)
{
newsUrls = new Hashtable();
newsUrls.put("sakai.news", NEWS_DEFAULT_URL);
state.setAttribute(STATE_NEWS_URLS, newsUrls);
}
context.put("newsUrls", newsUrls);
// titles for web content tools
wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES);
if (wcTitles == null)
{
wcTitles = new Hashtable();
wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE);
state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles);
}
context.put("wcTitles", wcTitles);
//URLs for web content tools
wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS);
if (wcUrls == null)
{
wcUrls = new Hashtable();
wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL);
state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls);
}
context.put("wcUrls", wcUrls);
context.put("serverName", ServerConfigurationService.getServerName());
context.put("oldSelectedTools", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
return (String)getContext(data).get("template") + TEMPLATE[26];
case 27:
/* buildContextForTemplate chef_site-importSites.vm
*
*/
existingSite = site != null? true:false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (existingSite)
{
// revising a existing site's tool
context.put("continue", "12");
context.put("back", "28");
context.put("totalSteps", "2");
context.put("step", "2");
context.put("currentSite", site);
}
else
{
// new site, go to edit access page
context.put("back", "3");
if (fromENWModifyView(state))
{
context.put("continue", "26");
}
else
{
context.put("continue", "18");
}
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put ("selectedTools", orderToolIds(state, site_type, getToolsAvailableForImport(state))); // String toolId's
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
return (String)getContext(data).get("template") + TEMPLATE[27];
case 28:
/* buildContextForTemplate chef_siteinfo-import.vm
*
*/
context.put("currentSite", site);
context.put("importSiteList", state.getAttribute(STATE_IMPORT_SITES));
context.put("sites", SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null));
return (String)getContext(data).get("template") + TEMPLATE[28];
case 29:
/* buildContextForTemplate chef_siteinfo-duplicate.vm
*
*/
context.put("siteTitle", site.getTitle());
String sType = site.getType();
if (sType != null && sType.equals("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("currentTermId", site.getProperties().getProperty(PROP_SITE_TERM));
context.put("termList", getAvailableTerms());
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
if (state.getAttribute(SITE_DUPLICATED) == null)
{
context.put("siteDuplicated", Boolean.FALSE);
}
else
{
context.put("siteDuplicated", Boolean.TRUE);
context.put("duplicatedName", state.getAttribute(SITE_DUPLICATED_NAME));
}
return (String)getContext(data).get("template") + TEMPLATE[29];
case 36:
/*
* buildContextForTemplate chef_site-newSiteCourse.vm
*/
if (site != null)
{
context.put("site", site);
context.put("siteTitle", site.getTitle());
terms = CourseManagementService.getTerms();
if (terms != null && terms.size() >0)
{
context.put("termList", terms);
}
List providerCourseList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
context.put("providerCourseList", providerCourseList);
context.put("manualCourseList", state.getAttribute(SITE_MANUAL_COURSE_LIST));
Term t = (Term) state.getAttribute(STATE_TERM_SELECTED);
context.put ("term", t);
if (t != null)
{
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
List courses = CourseManagementService.getInstructorCourses(userId, t.getYear(), t.getTerm());
if (courses != null && courses.size() > 0)
{
Vector notIncludedCourse = new Vector();
// remove included sites
for (Iterator i = courses.iterator(); i.hasNext(); )
{
Course c = (Course) i.next();
if (!providerCourseList.contains(c.getId()))
{
notIncludedCourse.add(c);
}
}
state.setAttribute(STATE_TERM_COURSE_LIST, notIncludedCourse);
}
else
{
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
}
// step number used in UI
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1"));
}
else
{
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if(state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
context.put("selectedManualCourse", Boolean.TRUE);
}
context.put ("term", (Term) state.getAttribute(STATE_TERM_SELECTED));
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
context.put("backIndex", "1");
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
context.put("backIndex", "");
}
context.put("termCourseList", (List) state.getAttribute(STATE_TERM_COURSE_LIST));
return (String)getContext(data).get("template") + TEMPLATE[36];
case 37:
/*
* buildContextForTemplate chef_site-newSiteCourseManual.vm
*/
if (site != null)
{
context.put("site", site);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
}
buildInstructorSectionsList(state, params, context);
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("form_requiredFieldsSizes", CourseManagementService.getCourseIdRequiredFieldsSizes());
context.put("form_additional", siteInfo.additional);
context.put("form_title", siteInfo.title);
context.put("form_description", siteInfo.description);
context.put("noEmailInIdAccountName", ServerConfigurationService.getString("noEmailInIdAccountName", ""));
context.put("value_uniqname", state.getAttribute(STATE_SITE_QUEST_UNIQNAME));
int number = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put("currentNumber", new Integer(number));
}
context.put("currentNumber", new Integer(number));
context.put("listSize", new Integer(number-1));
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
List l = (List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
context.put ("selectedProviderCourse", l);
context.put("size", new Integer(l.size()-1));
}
if (site != null)
{
context.put("back", "36");
}
else
{
if (state.getAttribute(STATE_AUTO_ADD) != null)
{
context.put("autoAdd", Boolean.TRUE);
context.put("back", "36");
}
else
{
context.put("back", "1");
}
}
context.put("isFutureTerm", state.getAttribute(STATE_FUTURE_TERM_SELECTED));
context.put("weeksAhead", ServerConfigurationService.getString("roster.available.weeks.before.term.start", "0"));
return (String)getContext(data).get("template") + TEMPLATE[37];
case 42:
/* buildContextForTemplate chef_site-gradtoolsConfirm.vm
*
*/
siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
toolRegistrationList = (Vector) state.getAttribute(STATE_PROJECT_TOOL_LIST);
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, toolRegistrationList ); // %%% use Tool
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
context.put("include", new Boolean(siteInfo.include));
return (String)getContext(data).get("template") + TEMPLATE[42];
case 43:
/* buildContextForTemplate chef_siteInfo-editClass.vm
*
*/
bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null))
{
bar.add( new MenuEntry(rb.getString("java.addclasses"), "doMenu_siteInfo_addClass"));
}
context.put("menu", bar);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
return (String)getContext(data).get("template") + TEMPLATE[43];
case 44:
/* buildContextForTemplate chef_siteInfo-addCourseConfirm.vm
*
*/
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
context.put("providerAddCourses", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int addNumber = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue() -1;
context.put("manualAddNumber", new Integer(addNumber));
context.put("requestFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("backIndex", "37");
}
else
{
context.put("backIndex", "36");
}
//those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[44];
//htripath - import materials from classic
case 45:
/* buildContextForTemplate chef_siteInfo-importMtrlMaster.vm
*
*/
return (String)getContext(data).get("template") + TEMPLATE[45];
case 46:
/* buildContextForTemplate chef_siteInfo-importMtrlCopy.vm
*
*/
// this is for list display in listbox
context.put("allZipSites", state.getAttribute(ALL_ZIP_IMPORT_SITES));
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
//zip file
//context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME));
return (String)getContext(data).get("template") + TEMPLATE[46];
case 47:
/* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[47];
case 48:
/* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[48];
case 49:
/* buildContextForTemplate chef_siteInfo-group.vm
*
*/
context.put("site", site);
bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowUpdateSite(site.getId()) || SiteService.allowUpdateGroupMembership(site.getId()))
{
bar.add( new MenuEntry(rb.getString("editgroup.new"), "doGroup_new"));
}
context.put("menu", bar);
// the group list
sortedBy = (String) state.getAttribute (SORTED_BY);
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
// only show groups created by WSetup tool itself
Collection groups = (Collection) site.getGroups();
List groupsByWSetup = new Vector();
for(Iterator gIterator = groups.iterator(); gIterator.hasNext();)
{
Group gNext = (Group) gIterator.next();
String gProp = gNext.getProperties().getProperty(GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString()))
{
groupsByWSetup.add(gNext);
}
}
if (sortedBy != null && sortedAsc != null)
{
context.put("groups", new SortedIterator (groupsByWSetup.iterator (), new SiteComparator (sortedBy, sortedAsc)));
}
return (String)getContext(data).get("template") + TEMPLATE[49];
case 50:
/* buildContextForTemplate chef_siteInfo-groupedit.vm
*
*/
Group g = getStateGroup(state);
if (g != null)
{
context.put("group", g);
context.put("newgroup", Boolean.FALSE);
}
else
{
context.put("newgroup", Boolean.TRUE);
}
if (state.getAttribute(STATE_GROUP_TITLE) != null)
{
context.put("title", state.getAttribute(STATE_GROUP_TITLE));
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null)
{
context.put("description", state.getAttribute(STATE_GROUP_DESCRIPTION));
}
Iterator siteMembers = new SortedIterator (getParticipantList(state).iterator (), new SiteComparator (SORTED_BY_PARTICIPANT_NAME, Boolean.TRUE.toString()));
if (siteMembers != null && siteMembers.hasNext())
{
context.put("generalMembers", siteMembers);
}
Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
if (state.getAttribute(STATE_GROUP_MEMBERS) != null)
{
context.put("groupMembers", new SortedIterator(groupMembersSet.iterator(), new SiteComparator (SORTED_BY_MEMBER_NAME, Boolean.TRUE.toString())));
}
context.put("groupMembersClone", groupMembersSet);
context.put("userDirectoryService", UserDirectoryService.getInstance());
return (String)getContext(data).get("template") + TEMPLATE[50];
case 51:
/* buildContextForTemplate chef_siteInfo-groupDeleteConfirm.vm
*
*/
context.put("site", site);
context.put("removeGroupIds", new ArrayList(Arrays.asList((String[])state.getAttribute(STATE_GROUP_REMOVE))));
return (String)getContext(data).get("template") + TEMPLATE[51];
}
// should never be reached
return (String)getContext(data).get("template") + TEMPLATE[0];
} // buildContextForTemplate
|
diff --git a/org.eclipse.stem.ui.diseasemodels/src/org/eclipse/stem/diseasemodels/standard/presentation/DiseasemodelsEditorAdvisor.java b/org.eclipse.stem.ui.diseasemodels/src/org/eclipse/stem/diseasemodels/standard/presentation/DiseasemodelsEditorAdvisor.java
index c6ef5e22..8e1744e8 100644
--- a/org.eclipse.stem.ui.diseasemodels/src/org/eclipse/stem/diseasemodels/standard/presentation/DiseasemodelsEditorAdvisor.java
+++ b/org.eclipse.stem.ui.diseasemodels/src/org/eclipse/stem/diseasemodels/standard/presentation/DiseasemodelsEditorAdvisor.java
@@ -1,592 +1,595 @@
package org.eclipse.stem.diseasemodels.standard.presentation;
/*******************************************************************************
* Copyright (c) 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.io.File;
import java.util.Arrays;
import java.util.List;
import org.eclipse.emf.common.ui.URIEditorInput;
import org.eclipse.emf.common.ui.action.WorkbenchWindowActionDelegate;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.common.util.UniqueEList;
import org.eclipse.emf.edit.ui.action.LoadResourceAction;
import org.eclipse.emf.edit.ui.util.EditUIUtil;
import org.eclipse.stem.diseasemodels.standard.presentation.DiseasemodelsEditorPlugin;
import org.eclipse.stem.core.common.presentation.CommonEditor;
import org.eclipse.stem.core.graph.presentation.GraphEditor;
import org.eclipse.stem.core.model.presentation.ModelEditor;
import org.eclipse.stem.core.scenario.presentation.ScenarioEditor;
import org.eclipse.stem.definitions.labels.presentation.LabelsEditor;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
//import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IFolderLayout;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ContributionItemFactory;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.application.IWorkbenchConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchAdvisor;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
/**
* Customized {@link WorkbenchAdvisor} for the RCP application.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public final class DiseasemodelsEditorAdvisor extends WorkbenchAdvisor {
/**
* The default file extension filters for use in dialogs.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final String[] FILE_EXTENSION_FILTERS = getFileExtensionFilters();
/**
* Returns the default file extension filters. This method should only be used to initialize {@link #FILE_EXTENSION_FILTERS}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
private static String[] getFileExtensionFilters() {
List<String> result = new UniqueEList<String>();
result.addAll(StandardEditor.FILE_EXTENSION_FILTERS);
return result.toArray(new String[0]);
}
/**
* This looks up a string in the plugin's plugin.properties file.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static String getString(String key) {
return DiseasemodelsEditorPlugin.INSTANCE.getString(key);
}
/**
* This looks up a string in plugin.properties, making a substitution.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static String getString(String key, Object s1) {
return org.eclipse.stem.diseasemodels.standard.presentation.DiseasemodelsEditorPlugin.INSTANCE.getString(key, new Object [] { s1 });
}
/**
* RCP's application
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class Application implements IApplication {
/**
* @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object start(IApplicationContext context) throws Exception {
WorkbenchAdvisor workbenchAdvisor = new DiseasemodelsEditorAdvisor();
Display display = PlatformUI.createDisplay();
try {
int returnCode = PlatformUI.createAndRunWorkbench(display, workbenchAdvisor);
if (returnCode == PlatformUI.RETURN_RESTART) {
return IApplication.EXIT_RESTART;
}
else {
return IApplication.EXIT_OK;
}
}
finally {
display.dispose();
}
}
/**
* @see org.eclipse.equinox.app.IApplication#stop()
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void stop() {
// Do nothing.
}
}
/**
* RCP's perspective
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class Perspective implements IPerspectiveFactory {
/**
* Perspective ID
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final String ID_PERSPECTIVE = "org.eclipse.stem.diseasemodels.standard.presentation.DiseasemodelsEditorAdvisorPerspective"; //$NON-NLS-1$
/**
* @see org.eclipse.ui.IPerspectiveFactory#createInitialLayout(org.eclipse.ui.IPageLayout)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createInitialLayout(IPageLayout layout) {
layout.setEditorAreaVisible(true);
layout.addPerspectiveShortcut(ID_PERSPECTIVE);
IFolderLayout right = layout.createFolder("right", IPageLayout.RIGHT, (float)0.66, layout.getEditorArea()); //$NON-NLS-1$
right.addView(IPageLayout.ID_OUTLINE);
IFolderLayout bottonRight = layout.createFolder("bottonRight", IPageLayout.BOTTOM, (float)0.60, "right"); //$NON-NLS-1$ //$NON-NLS-2$
bottonRight.addView(IPageLayout.ID_PROP_SHEET);
}
}
/**
* RCP's window advisor
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class WindowAdvisor extends WorkbenchWindowAdvisor {
/**
* @see WorkbenchWindowAdvisor#WorkbenchWindowAdvisor(org.eclipse.ui.application.IWorkbenchWindowConfigurer)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WindowAdvisor(IWorkbenchWindowConfigurer configurer) {
super(configurer);
}
/**
* @see org.eclipse.ui.application.WorkbenchWindowAdvisor#preWindowOpen()
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void preWindowOpen() {
IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
configurer.setInitialSize(new Point(600, 450));
configurer.setShowCoolBar(false);
configurer.setShowStatusLine(true);
configurer.setTitle(getString("_UI_Application_title")); //$NON-NLS-1$
}
/**
* @see org.eclipse.ui.application.WorkbenchWindowAdvisor#createActionBarAdvisor(org.eclipse.ui.application.IActionBarConfigurer)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer) {
return new WindowActionBarAdvisor(configurer);
}
}
/**
* RCP's action bar advisor
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class WindowActionBarAdvisor extends ActionBarAdvisor {
/**
* @see ActionBarAdvisor#ActionBarAdvisor(org.eclipse.ui.application.IActionBarConfigurer)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WindowActionBarAdvisor(IActionBarConfigurer configurer) {
super(configurer);
}
/**
* @see org.eclipse.ui.application.ActionBarAdvisor#fillMenuBar(org.eclipse.jface.action.IMenuManager)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void fillMenuBar(IMenuManager menuBar) {
IWorkbenchWindow window = getActionBarConfigurer().getWindowConfigurer().getWindow();
menuBar.add(createFileMenu(window));
menuBar.add(createEditMenu(window));
menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
menuBar.add(createWindowMenu(window));
menuBar.add(createHelpMenu(window));
}
/**
* Creates the 'File' menu.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IMenuManager createFileMenu(IWorkbenchWindow window) {
IMenuManager menu = new MenuManager(getString("_UI_Menu_File_label"), //$NON-NLS-1$
IWorkbenchActionConstants.M_FILE);
menu.add(new GroupMarker(IWorkbenchActionConstants.FILE_START));
IMenuManager newMenu = new MenuManager(getString("_UI_Menu_New_label"), "new"); //$NON-NLS-1$ //$NON-NLS-2$
newMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(newMenu);
menu.add(new Separator());
menu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(new Separator());
addToMenuAndRegister(menu, ActionFactory.CLOSE.create(window));
addToMenuAndRegister(menu, ActionFactory.CLOSE_ALL.create(window));
menu.add(new Separator());
addToMenuAndRegister(menu, ActionFactory.SAVE.create(window));
addToMenuAndRegister(menu, ActionFactory.SAVE_AS.create(window));
addToMenuAndRegister(menu, ActionFactory.SAVE_ALL.create(window));
menu.add(new Separator());
addToMenuAndRegister(menu, ActionFactory.QUIT.create(window));
menu.add(new GroupMarker(IWorkbenchActionConstants.FILE_END));
return menu;
}
/**
* Creates the 'Edit' menu.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IMenuManager createEditMenu(IWorkbenchWindow window) {
IMenuManager menu = new MenuManager(getString("_UI_Menu_Edit_label"), //$NON-NLS-1$
IWorkbenchActionConstants.M_EDIT);
menu.add(new GroupMarker(IWorkbenchActionConstants.EDIT_START));
addToMenuAndRegister(menu, ActionFactory.UNDO.create(window));
addToMenuAndRegister(menu, ActionFactory.REDO.create(window));
menu.add(new GroupMarker(IWorkbenchActionConstants.UNDO_EXT));
menu.add(new Separator());
addToMenuAndRegister(menu, ActionFactory.CUT.create(window));
addToMenuAndRegister(menu, ActionFactory.COPY.create(window));
addToMenuAndRegister(menu, ActionFactory.PASTE.create(window));
menu.add(new GroupMarker(IWorkbenchActionConstants.CUT_EXT));
menu.add(new Separator());
addToMenuAndRegister(menu, ActionFactory.DELETE.create(window));
addToMenuAndRegister(menu, ActionFactory.SELECT_ALL.create(window));
menu.add(new Separator());
menu.add(new GroupMarker(IWorkbenchActionConstants.ADD_EXT));
menu.add(new GroupMarker(IWorkbenchActionConstants.EDIT_END));
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
return menu;
}
/**
* Creates the 'Window' menu.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IMenuManager createWindowMenu(IWorkbenchWindow window) {
IMenuManager menu = new MenuManager(getString("_UI_Menu_Window_label"), //$NON-NLS-1$
IWorkbenchActionConstants.M_WINDOW);
addToMenuAndRegister(menu, ActionFactory.OPEN_NEW_WINDOW.create(window));
menu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(ContributionItemFactory.OPEN_WINDOWS.create(window));
return menu;
}
/**
* Creates the 'Help' menu.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IMenuManager createHelpMenu(IWorkbenchWindow window) {
IMenuManager menu = new MenuManager(getString("_UI_Menu_Help_label"), IWorkbenchActionConstants.M_HELP); //$NON-NLS-1$
// Welcome or intro page would go here
// Help contents would go here
// Tips and tricks page would go here
menu.add(new GroupMarker(IWorkbenchActionConstants.HELP_START));
menu.add(new GroupMarker(IWorkbenchActionConstants.HELP_END));
menu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
return menu;
}
/**
* Adds the specified action to the given menu and also registers the action with the
* action bar configurer, in order to activate its key binding.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addToMenuAndRegister(IMenuManager menuManager, IAction action) {
menuManager.add(action);
getActionBarConfigurer().registerGlobalAction(action);
}
}
/**
* About action for the RCP application.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class AboutAction extends WorkbenchWindowActionDelegate {
/**
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void run(IAction action) {
MessageDialog.openInformation(getWindow().getShell(), getString("_UI_About_title"), //$NON-NLS-1$
getString("_UI_About_text")); //$NON-NLS-1$
}
}
/**
* Open action for the objects from the Diseasemodels model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class OpenAction extends WorkbenchWindowActionDelegate {
/**
* Opens the editors for the files selected using the file dialog.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void run(IAction action) {
String[] filePaths = openFilePathDialog(getWindow().getShell(), SWT.OPEN, null);
if (filePaths.length > 0) {
openEditor(getWindow().getWorkbench(), URI.createFileURI(filePaths[0]));
}
}
}
/**
* Open URI action for the objects from the Diseasemodels model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class OpenURIAction extends WorkbenchWindowActionDelegate {
/**
* Opens the editors for the files selected using the LoadResourceDialog.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void run(IAction action) {
LoadResourceAction.LoadResourceDialog loadResourceDialog = new LoadResourceAction.LoadResourceDialog(getWindow().getShell());
if (Window.OK == loadResourceDialog.open()) {
for (URI uri : loadResourceDialog.getURIs()) {
openEditor(getWindow().getWorkbench(), uri);
}
}
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static String[] openFilePathDialog(Shell shell, int style, String[] fileExtensionFilters) {
return openFilePathDialog(shell, style, fileExtensionFilters, (style & SWT.OPEN) != 0, (style & SWT.OPEN) != 0, (style & SWT.SAVE) != 0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static String[] openFilePathDialog(Shell shell, int style, String[] fileExtensionFilters, boolean includeGroupFilter, boolean includeAllFilter, boolean addExtension) {
FileDialog fileDialog = new FileDialog(shell, style);
if (fileExtensionFilters == null) {
fileExtensionFilters = FILE_EXTENSION_FILTERS;
}
// If requested, augment the file extension filters by adding a group of all the other filters (*.ext1;*.ext2;...)
// at the beginning and/or an all files wildcard (*.*) at the end.
//
includeGroupFilter &= fileExtensionFilters.length > 1;
int offset = includeGroupFilter ? 1 : 0;
if (includeGroupFilter || includeAllFilter) {
int size = fileExtensionFilters.length + offset + (includeAllFilter ? 1 : 0);
String[] allFilters = new String[size];
StringBuilder group = includeGroupFilter ? new StringBuilder() : null;
for (int i = 0; i < fileExtensionFilters.length; i++) {
if (includeGroupFilter) {
if (i != 0) {
group.append(';');
}
group.append(fileExtensionFilters[i]);
}
allFilters[i + offset] = fileExtensionFilters[i];
}
if (includeGroupFilter) {
allFilters[0] = group.toString();
}
if (includeAllFilter) {
allFilters[allFilters.length - 1] = "*.*"; //$NON-NLS-1$
}
fileDialog.setFilterExtensions(allFilters);
}
else {
fileDialog.setFilterExtensions(fileExtensionFilters);
}
fileDialog.open();
String[] filenames = fileDialog.getFileNames();
String[] result = new String[filenames.length];
String path = fileDialog.getFilterPath() + File.separator;
String extension = null;
// If extension adding requested, get the dotted extension corresponding to the selected filter.
//
if (addExtension) {
int i = fileDialog.getFilterIndex();
if (i != -1 && (!includeAllFilter || i != fileExtensionFilters.length)) {
i = includeGroupFilter && i == 0 ? 0 : i - offset;
String filter = fileExtensionFilters[i];
int dot = filter.lastIndexOf('.');
if (dot == 1 && filter.charAt(0) == '*') {
extension = filter.substring(dot);
}
}
}
// Build the result by adding the selected path and, if needed, auto-appending the extension.
//
for (int i = 0; i < filenames.length; i++) {
String filename = path + filenames[i];
if (extension != null) {
int dot = filename.lastIndexOf('.');
+ StringBuilder str = new StringBuilder(filename);
if (dot == -1 || !Arrays.asList(fileExtensionFilters).contains("*" + filename.substring(dot))) //$NON-NLS-1$
{
- filename += extension;
+ str.append(extension);
+ //filename += extension;
}
+ filename = str.toString();
}
result[i] = filename;
}
return result;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static boolean openEditor(IWorkbench workbench, URI uri) {
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
IWorkbenchPage page = workbenchWindow.getActivePage();
IEditorDescriptor editorDescriptor = EditUIUtil.getDefaultEditor(uri, null);
if (editorDescriptor == null) {
MessageDialog.openError(
workbenchWindow.getShell(),
getString("_UI_Error_title"), //$NON-NLS-1$
getString("_WARN_No_Editor", uri.lastSegment())); //$NON-NLS-1$
return false;
}
else {
try {
page.openEditor(new URIEditorInput(uri), editorDescriptor.getId());
}
catch (PartInitException exception) {
MessageDialog.openError(
workbenchWindow.getShell(),
getString("_UI_OpenEditorError_label"), //$NON-NLS-1$
exception.getMessage());
return false;
}
}
return true;
}
/**
* @see org.eclipse.ui.application.WorkbenchAdvisor#getInitialWindowPerspectiveId()
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getInitialWindowPerspectiveId() {
return Perspective.ID_PERSPECTIVE;
}
/**
* @see org.eclipse.ui.application.WorkbenchAdvisor#initialize(org.eclipse.ui.application.IWorkbenchConfigurer)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void initialize(IWorkbenchConfigurer configurer) {
super.initialize(configurer);
configurer.setSaveAndRestore(true);
}
/**
* @see org.eclipse.ui.application.WorkbenchAdvisor#createWorkbenchWindowAdvisor(org.eclipse.ui.application.IWorkbenchWindowConfigurer)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
return new WindowAdvisor(configurer);
}
}
| false | true | public static String[] openFilePathDialog(Shell shell, int style, String[] fileExtensionFilters, boolean includeGroupFilter, boolean includeAllFilter, boolean addExtension) {
FileDialog fileDialog = new FileDialog(shell, style);
if (fileExtensionFilters == null) {
fileExtensionFilters = FILE_EXTENSION_FILTERS;
}
// If requested, augment the file extension filters by adding a group of all the other filters (*.ext1;*.ext2;...)
// at the beginning and/or an all files wildcard (*.*) at the end.
//
includeGroupFilter &= fileExtensionFilters.length > 1;
int offset = includeGroupFilter ? 1 : 0;
if (includeGroupFilter || includeAllFilter) {
int size = fileExtensionFilters.length + offset + (includeAllFilter ? 1 : 0);
String[] allFilters = new String[size];
StringBuilder group = includeGroupFilter ? new StringBuilder() : null;
for (int i = 0; i < fileExtensionFilters.length; i++) {
if (includeGroupFilter) {
if (i != 0) {
group.append(';');
}
group.append(fileExtensionFilters[i]);
}
allFilters[i + offset] = fileExtensionFilters[i];
}
if (includeGroupFilter) {
allFilters[0] = group.toString();
}
if (includeAllFilter) {
allFilters[allFilters.length - 1] = "*.*"; //$NON-NLS-1$
}
fileDialog.setFilterExtensions(allFilters);
}
else {
fileDialog.setFilterExtensions(fileExtensionFilters);
}
fileDialog.open();
String[] filenames = fileDialog.getFileNames();
String[] result = new String[filenames.length];
String path = fileDialog.getFilterPath() + File.separator;
String extension = null;
// If extension adding requested, get the dotted extension corresponding to the selected filter.
//
if (addExtension) {
int i = fileDialog.getFilterIndex();
if (i != -1 && (!includeAllFilter || i != fileExtensionFilters.length)) {
i = includeGroupFilter && i == 0 ? 0 : i - offset;
String filter = fileExtensionFilters[i];
int dot = filter.lastIndexOf('.');
if (dot == 1 && filter.charAt(0) == '*') {
extension = filter.substring(dot);
}
}
}
// Build the result by adding the selected path and, if needed, auto-appending the extension.
//
for (int i = 0; i < filenames.length; i++) {
String filename = path + filenames[i];
if (extension != null) {
int dot = filename.lastIndexOf('.');
if (dot == -1 || !Arrays.asList(fileExtensionFilters).contains("*" + filename.substring(dot))) //$NON-NLS-1$
{
filename += extension;
}
}
result[i] = filename;
}
return result;
}
| public static String[] openFilePathDialog(Shell shell, int style, String[] fileExtensionFilters, boolean includeGroupFilter, boolean includeAllFilter, boolean addExtension) {
FileDialog fileDialog = new FileDialog(shell, style);
if (fileExtensionFilters == null) {
fileExtensionFilters = FILE_EXTENSION_FILTERS;
}
// If requested, augment the file extension filters by adding a group of all the other filters (*.ext1;*.ext2;...)
// at the beginning and/or an all files wildcard (*.*) at the end.
//
includeGroupFilter &= fileExtensionFilters.length > 1;
int offset = includeGroupFilter ? 1 : 0;
if (includeGroupFilter || includeAllFilter) {
int size = fileExtensionFilters.length + offset + (includeAllFilter ? 1 : 0);
String[] allFilters = new String[size];
StringBuilder group = includeGroupFilter ? new StringBuilder() : null;
for (int i = 0; i < fileExtensionFilters.length; i++) {
if (includeGroupFilter) {
if (i != 0) {
group.append(';');
}
group.append(fileExtensionFilters[i]);
}
allFilters[i + offset] = fileExtensionFilters[i];
}
if (includeGroupFilter) {
allFilters[0] = group.toString();
}
if (includeAllFilter) {
allFilters[allFilters.length - 1] = "*.*"; //$NON-NLS-1$
}
fileDialog.setFilterExtensions(allFilters);
}
else {
fileDialog.setFilterExtensions(fileExtensionFilters);
}
fileDialog.open();
String[] filenames = fileDialog.getFileNames();
String[] result = new String[filenames.length];
String path = fileDialog.getFilterPath() + File.separator;
String extension = null;
// If extension adding requested, get the dotted extension corresponding to the selected filter.
//
if (addExtension) {
int i = fileDialog.getFilterIndex();
if (i != -1 && (!includeAllFilter || i != fileExtensionFilters.length)) {
i = includeGroupFilter && i == 0 ? 0 : i - offset;
String filter = fileExtensionFilters[i];
int dot = filter.lastIndexOf('.');
if (dot == 1 && filter.charAt(0) == '*') {
extension = filter.substring(dot);
}
}
}
// Build the result by adding the selected path and, if needed, auto-appending the extension.
//
for (int i = 0; i < filenames.length; i++) {
String filename = path + filenames[i];
if (extension != null) {
int dot = filename.lastIndexOf('.');
StringBuilder str = new StringBuilder(filename);
if (dot == -1 || !Arrays.asList(fileExtensionFilters).contains("*" + filename.substring(dot))) //$NON-NLS-1$
{
str.append(extension);
//filename += extension;
}
filename = str.toString();
}
result[i] = filename;
}
return result;
}
|
diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/StubArtifactResolver.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/StubArtifactResolver.java
index c1eade0..b0ed149 100644
--- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/StubArtifactResolver.java
+++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/StubArtifactResolver.java
@@ -1,188 +1,188 @@
package org.apache.maven.plugin.testing.stubs;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.plugin.testing.ArtifactStubFactory;
/**
* Stub resolver. The constructor allows the specification of the exception to throw so that handling can be tested too.
*
* @author <a href="mailto:[email protected]">Brian Fox</a>
* @version $Id: $
*/
public class StubArtifactResolver
implements ArtifactResolver
{
boolean throwArtifactResolutionException;
boolean throwArtifactNotFoundException;
ArtifactStubFactory factory;
/**
* Default constructor
*
* @param factory
* @param throwArtifactResolutionException
* @param throwArtifactNotFoundException
*/
public StubArtifactResolver( ArtifactStubFactory factory, boolean throwArtifactResolutionException,
boolean throwArtifactNotFoundException )
{
this.throwArtifactNotFoundException = throwArtifactNotFoundException;
this.throwArtifactResolutionException = throwArtifactResolutionException;
this.factory = factory;
}
/*
* Creates dummy file and sets it in the artifact to simulate resolution
* (non-Javadoc)
*
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolve(org.apache.maven.artifact.Artifact,
* java.util.List,
* org.apache.maven.artifact.repository.ArtifactRepository)
*/
public void resolve( Artifact artifact, List remoteRepositories, ArtifactRepository localRepository )
throws ArtifactResolutionException, ArtifactNotFoundException
{
if ( !this.throwArtifactNotFoundException && !this.throwArtifactResolutionException )
{
try
{
if ( factory != null )
{
- factory.setArtifactFile( artifact );
+ factory.setArtifactFile( artifact, factory.getWorkingDir() );
}
}
catch ( IOException e )
{
throw new ArtifactResolutionException( "IOException: " + e.getMessage(), artifact, e );
}
}
else
{
if ( throwArtifactResolutionException )
{
throw new ArtifactResolutionException( "Catch!", artifact );
}
throw new ArtifactNotFoundException( "Catch!", artifact );
}
}
/**
* @return <code>null</code>.
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolveTransitively(java.util.Set, org.apache.maven.artifact.Artifact, java.util.List, org.apache.maven.artifact.repository.ArtifactRepository, org.apache.maven.artifact.metadata.ArtifactMetadataSource)
*/
public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact,
List remoteRepositories, ArtifactRepository localRepository,
ArtifactMetadataSource source )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return null;
}
/**
* @return <code>null</code>.
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolveTransitively(java.util.Set, org.apache.maven.artifact.Artifact, java.util.List, org.apache.maven.artifact.repository.ArtifactRepository, org.apache.maven.artifact.metadata.ArtifactMetadataSource, java.util.List)
*/
public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact,
List remoteRepositories, ArtifactRepository localRepository,
ArtifactMetadataSource source, List listeners )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return null;
}
/**
* @return <code>null</code>.
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolveTransitively(java.util.Set, org.apache.maven.artifact.Artifact, org.apache.maven.artifact.repository.ArtifactRepository, java.util.List, org.apache.maven.artifact.metadata.ArtifactMetadataSource, org.apache.maven.artifact.resolver.filter.ArtifactFilter)
*/
public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact,
ArtifactRepository localRepository, List remoteRepositories,
ArtifactMetadataSource source, ArtifactFilter filter )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return null;
}
/**
* @return <code>null</code>.
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolveTransitively(java.util.Set, org.apache.maven.artifact.Artifact, java.util.Map, org.apache.maven.artifact.repository.ArtifactRepository, java.util.List, org.apache.maven.artifact.metadata.ArtifactMetadataSource)
*/
public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact,
Map managedVersions, ArtifactRepository localRepository,
List remoteRepositories, ArtifactMetadataSource source )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return null;
}
/**
* @return <code>null</code>.
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolveTransitively(java.util.Set, org.apache.maven.artifact.Artifact, java.util.Map, org.apache.maven.artifact.repository.ArtifactRepository, java.util.List, org.apache.maven.artifact.metadata.ArtifactMetadataSource, org.apache.maven.artifact.resolver.filter.ArtifactFilter)
*/
public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact,
Map managedVersions, ArtifactRepository localRepository,
List remoteRepositories, ArtifactMetadataSource source,
ArtifactFilter filter )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return null;
}
/**
* @return <code>null</code>.
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolveTransitively(java.util.Set, org.apache.maven.artifact.Artifact, java.util.Map, org.apache.maven.artifact.repository.ArtifactRepository, java.util.List, org.apache.maven.artifact.metadata.ArtifactMetadataSource, org.apache.maven.artifact.resolver.filter.ArtifactFilter, java.util.List)
*/
public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact,
Map managedVersions, ArtifactRepository localRepository,
List remoteRepositories, ArtifactMetadataSource source,
ArtifactFilter filter, List listeners )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return null;
}
/**
* By default, do nothing.
*
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolveAlways(org.apache.maven.artifact.Artifact, java.util.List, org.apache.maven.artifact.repository.ArtifactRepository)
*/
public void resolveAlways( Artifact artifact, List remoteRepositories, ArtifactRepository localRepository )
throws ArtifactResolutionException, ArtifactNotFoundException
{
// nop
}
}
| true | true | public void resolve( Artifact artifact, List remoteRepositories, ArtifactRepository localRepository )
throws ArtifactResolutionException, ArtifactNotFoundException
{
if ( !this.throwArtifactNotFoundException && !this.throwArtifactResolutionException )
{
try
{
if ( factory != null )
{
factory.setArtifactFile( artifact );
}
}
catch ( IOException e )
{
throw new ArtifactResolutionException( "IOException: " + e.getMessage(), artifact, e );
}
}
else
{
if ( throwArtifactResolutionException )
{
throw new ArtifactResolutionException( "Catch!", artifact );
}
throw new ArtifactNotFoundException( "Catch!", artifact );
}
}
| public void resolve( Artifact artifact, List remoteRepositories, ArtifactRepository localRepository )
throws ArtifactResolutionException, ArtifactNotFoundException
{
if ( !this.throwArtifactNotFoundException && !this.throwArtifactResolutionException )
{
try
{
if ( factory != null )
{
factory.setArtifactFile( artifact, factory.getWorkingDir() );
}
}
catch ( IOException e )
{
throw new ArtifactResolutionException( "IOException: " + e.getMessage(), artifact, e );
}
}
else
{
if ( throwArtifactResolutionException )
{
throw new ArtifactResolutionException( "Catch!", artifact );
}
throw new ArtifactNotFoundException( "Catch!", artifact );
}
}
|
diff --git a/server-integ/src/test/java/org/apache/directory/server/operations/modify/ModifyReplaceIT.java b/server-integ/src/test/java/org/apache/directory/server/operations/modify/ModifyReplaceIT.java
index 8c3f9763d0..d43c158ede 100644
--- a/server-integ/src/test/java/org/apache/directory/server/operations/modify/ModifyReplaceIT.java
+++ b/server-integ/src/test/java/org/apache/directory/server/operations/modify/ModifyReplaceIT.java
@@ -1,373 +1,373 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.server.operations.modify;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.apache.directory.server.core.DefaultDirectoryService;
import org.apache.directory.server.core.DirectoryService;
import org.apache.directory.server.core.entry.ServerEntry;
import org.apache.directory.server.core.integ.IntegrationUtils;
import org.apache.directory.server.core.integ.Level;
import org.apache.directory.server.core.integ.annotations.ApplyLdifs;
import org.apache.directory.server.core.integ.annotations.CleanupLevel;
import org.apache.directory.server.core.integ.annotations.Factory;
import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmIndex;
import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmPartition;
import org.apache.directory.server.integ.LdapServerFactory;
import org.apache.directory.server.integ.SiRunner;
import static org.apache.directory.server.integ.ServerIntegrationUtils.getWiredContext;
import org.apache.directory.server.ldap.LdapService;
import org.apache.directory.server.ldap.handlers.bind.MechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.SimpleMechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.cramMD5.CramMd5MechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.digestMD5.DigestMd5MechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.gssapi.GssapiMechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.ntlm.NtlmMechanismHandler;
import org.apache.directory.server.ldap.handlers.extended.StartTlsHandler;
import org.apache.directory.server.ldap.handlers.extended.StoredProcedureExtendedOperationHandler;
import org.apache.directory.server.protocol.shared.transport.TcpTransport;
import org.apache.directory.server.xdbm.Index;
import org.apache.directory.shared.ldap.constants.SchemaConstants;
import org.apache.directory.shared.ldap.constants.SupportedSaslMechanisms;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.apache.mina.util.AvailablePortFinder;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertEquals;
/**
* Test case for all modify replace operations.
*
* Demonstrates DIRSERVER-646 ("Replacing an unknown attribute with
* no values (deletion) causes an error").
*/
@RunWith ( SiRunner.class )
@CleanupLevel ( Level.SUITE )
@Factory ( ModifyReplaceIT.Factory.class )
@ApplyLdifs( {
// Entry # 1
"dn: cn=Kate Bush,ou=system\n" +
"objectClass: top\n" +
"objectClass: person\n" +
"sn: Bush\n" +
"cn: Kate Bush\n\n" +
// Entry # 2
"dn: cn=Kim Wilde,ou=system\n" +
"objectClass: top\n" +
"objectClass: person\n" +
"objectClass: organizationalPerson \n" +
"objectClass: inetOrgPerson \n" +
"sn: Wilde\n" +
"cn: Kim Wilde\n\n"
}
)
public class ModifyReplaceIT
{
private static final String BASE = "ou=system";
public static LdapService ldapService;
public static class Factory implements LdapServerFactory
{
public LdapService newInstance() throws Exception
{
DirectoryService service = new DefaultDirectoryService();
IntegrationUtils.doDelete( service.getWorkingDirectory() );
service.getChangeLog().setEnabled( true );
service.setShutdownHookEnabled( false );
JdbmPartition system = new JdbmPartition();
system.setId( "system" );
// @TODO need to make this configurable for the system partition
system.setCacheSize( 500 );
system.setSuffix( "ou=system" );
// Add indexed attributes for system partition
Set<Index<?,ServerEntry>> indexedAttrs = new HashSet<Index<?,ServerEntry>>();
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OBJECT_CLASS_AT ) );
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OU_AT ) );
system.setIndexedAttributes( indexedAttrs );
service.setSystemPartition( system );
// change the working directory to something that is unique
// on the system and somewhere either under target directory
// or somewhere in a temp area of the machine.
LdapService ldapService = new LdapService();
ldapService.setDirectoryService( service );
- ldapService.setSocketAcceptor( new NioSocketAcceptor() );
int port = AvailablePortFinder.getNextAvailable( 1024 );
ldapService.setTcpTransport( new TcpTransport( port ) );
+ ldapService.setSocketAcceptor( new NioSocketAcceptor() );
ldapService.getTcpTransport().setNbThreads( 3 );
ldapService.addExtendedOperationHandler( new StartTlsHandler() );
ldapService.addExtendedOperationHandler( new StoredProcedureExtendedOperationHandler() );
// Setup SASL Mechanisms
Map<String, MechanismHandler> mechanismHandlerMap = new HashMap<String,MechanismHandler>();
mechanismHandlerMap.put( SupportedSaslMechanisms.PLAIN, new SimpleMechanismHandler() );
CramMd5MechanismHandler cramMd5MechanismHandler = new CramMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.CRAM_MD5, cramMd5MechanismHandler );
DigestMd5MechanismHandler digestMd5MechanismHandler = new DigestMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.DIGEST_MD5, digestMd5MechanismHandler );
GssapiMechanismHandler gssapiMechanismHandler = new GssapiMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.GSSAPI, gssapiMechanismHandler );
NtlmMechanismHandler ntlmMechanismHandler = new NtlmMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.NTLM, ntlmMechanismHandler );
mechanismHandlerMap.put( SupportedSaslMechanisms.GSS_SPNEGO, ntlmMechanismHandler );
ldapService.setSaslMechanismHandlers( mechanismHandlerMap );
return ldapService;
}
}
/**
* Create a person entry and try to remove a not present attribute
*/
@Test
public void testReplaceToRemoveNotPresentAttribute() throws Exception
{
DirContext sysRoot = ( DirContext ) getWiredContext( ldapService ).lookup( BASE );
String rdn = "cn=Kate Bush";
Attribute attr = new BasicAttribute( "description" );
ModificationItem item = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, attr );
sysRoot.modifyAttributes( rdn, new ModificationItem[] { item } );
SearchControls sctls = new SearchControls();
sctls.setSearchScope( SearchControls.SUBTREE_SCOPE );
String filter = "(sn=Bush)";
String base = "";
NamingEnumeration<SearchResult> enm = sysRoot.search( base, filter, sctls );
while ( enm.hasMore() )
{
SearchResult sr = ( SearchResult ) enm.next();
Attribute cn = sr.getAttributes().get( "cn" );
assertNotNull( cn );
assertTrue( cn.contains( "Kate Bush") );
Attribute desc = sr.getAttributes().get( "description" );
assertNull( desc );
}
sysRoot.destroySubcontext( rdn );
}
/**
* Create a person entry and try to add a not present attribute via a REPLACE
*/
@Test
public void testReplaceToAddNotPresentAttribute() throws Exception
{
DirContext sysRoot = ( DirContext ) getWiredContext( ldapService ).lookup( BASE );
String rdn = "cn=Kate Bush";
Attribute attr = new BasicAttribute( "description", "added description" );
ModificationItem item = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, attr );
sysRoot.modifyAttributes( rdn, new ModificationItem[] { item } );
SearchControls sctls = new SearchControls();
sctls.setSearchScope( SearchControls.SUBTREE_SCOPE );
String filter = "(sn=Bush)";
String base = "";
NamingEnumeration<SearchResult> enm = sysRoot.search( base, filter, sctls );
while ( enm.hasMore() )
{
SearchResult sr = ( SearchResult ) enm.next();
Attribute cn = sr.getAttributes().get( "cn" );
assertNotNull( cn );
assertTrue( cn.contains( "Kate Bush") );
Attribute desc = sr.getAttributes().get( "description" );
assertNotNull( desc );
assertTrue( desc.contains( "added description") );
assertEquals( 1, desc.size() );
}
sysRoot.destroySubcontext( rdn );
}
/**
* Create a person entry and try to remove a non existing attribute
*/
@Test
public void testReplaceNonExistingAttribute() throws Exception
{
DirContext sysRoot = ( DirContext ) getWiredContext( ldapService ).lookup( BASE );
String rdn = "cn=Kate Bush";
Attribute attr = new BasicAttribute( "numberOfOctaves" );
ModificationItem item = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, attr );
sysRoot.modifyAttributes( rdn, new ModificationItem[] { item } );
SearchControls sctls = new SearchControls();
sctls.setSearchScope( SearchControls.SUBTREE_SCOPE );
String filter = "(sn=Bush)";
String base = "";
NamingEnumeration<SearchResult> enm = sysRoot.search( base, filter, sctls );
while ( enm.hasMore() )
{
SearchResult sr = enm.next();
Attribute cn = sr.getAttributes().get( "cn" );
assertNotNull( cn );
assertTrue( cn.contains( "Kate Bush" ) );
}
sysRoot.destroySubcontext( rdn );
}
/**
* Create a person entry and try to remove a non existing attribute
*/
@Test
public void testReplaceNonExistingAttributeManyMods() throws Exception
{
DirContext sysRoot = ( DirContext ) getWiredContext( ldapService ).lookup( BASE );
String rdn = "cn=Kate Bush";
Attribute attr = new BasicAttribute( "numberOfOctaves" );
ModificationItem item = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, attr );
Attribute attr2 = new BasicAttribute( "description", "blah blah blah" );
ModificationItem item2 = new ModificationItem( DirContext.ADD_ATTRIBUTE, attr2 );
sysRoot.modifyAttributes(rdn, new ModificationItem[] { item, item2 });
SearchControls sctls = new SearchControls();
sctls.setSearchScope( SearchControls.SUBTREE_SCOPE );
String filter = "(sn=Bush)";
String base = "";
NamingEnumeration<SearchResult> enm = sysRoot.search( base, filter, sctls );
while ( enm.hasMore() )
{
SearchResult sr = enm.next();
Attribute cn = sr.getAttributes().get( "cn" );
assertNotNull( cn );
assertTrue( cn.contains( "Kate Bush" ) );
}
sysRoot.destroySubcontext( rdn );
}
/**
* Create a person entry and try to replace a non existing indexed attribute
*/
@Test
public void testReplaceNonExistingIndexedAttribute() throws Exception
{
DirContext sysRoot = ( DirContext ) getWiredContext( ldapService ).lookup( BASE );
String rdn = "cn=Kim Wilde";
//ldapService.getDirectoryService().getPartitions();
Attribute attr = new BasicAttribute( "ou", "test" );
ModificationItem item = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, attr );
sysRoot.modifyAttributes(rdn, new ModificationItem[] { item });
SearchControls sctls = new SearchControls();
sctls.setSearchScope( SearchControls.SUBTREE_SCOPE );
String filter = "(sn=Wilde)";
String base = "";
NamingEnumeration<SearchResult> enm = sysRoot.search( base, filter, sctls );
while ( enm.hasMore() )
{
SearchResult sr = enm.next();
Attribute ou = sr.getAttributes().get( "ou" );
assertNotNull( ou );
assertTrue( ou.contains( "test" ) );
}
sysRoot.destroySubcontext( rdn );
}
/**
* Create a person entry, replace telephoneNumber, verify the
* case of the attribute description attribute.
*/
@Test
public void testReplaceCaseOfAttributeDescription() throws Exception
{
DirContext ctx = ( DirContext ) getWiredContext( ldapService ).lookup( BASE );
String rdn = "cn=Kate Bush";
// Replace telephoneNumber
String newValue = "2345678901";
Attributes attrs = new BasicAttributes( "telephoneNumber", newValue, false );
ctx.modifyAttributes( rdn, DirContext.REPLACE_ATTRIBUTE, attrs );
// Verify, that
// - case of attribute description is correct
// - attribute value is added
attrs = ctx.getAttributes( rdn );
Attribute attr = attrs.get( "telephoneNumber" );
assertNotNull( attr );
assertEquals( "telephoneNumber", attr.getID() );
assertTrue( attr.contains( newValue ) );
assertEquals( 1, attr.size() );
}
}
| false | true | public LdapService newInstance() throws Exception
{
DirectoryService service = new DefaultDirectoryService();
IntegrationUtils.doDelete( service.getWorkingDirectory() );
service.getChangeLog().setEnabled( true );
service.setShutdownHookEnabled( false );
JdbmPartition system = new JdbmPartition();
system.setId( "system" );
// @TODO need to make this configurable for the system partition
system.setCacheSize( 500 );
system.setSuffix( "ou=system" );
// Add indexed attributes for system partition
Set<Index<?,ServerEntry>> indexedAttrs = new HashSet<Index<?,ServerEntry>>();
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OBJECT_CLASS_AT ) );
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OU_AT ) );
system.setIndexedAttributes( indexedAttrs );
service.setSystemPartition( system );
// change the working directory to something that is unique
// on the system and somewhere either under target directory
// or somewhere in a temp area of the machine.
LdapService ldapService = new LdapService();
ldapService.setDirectoryService( service );
ldapService.setSocketAcceptor( new NioSocketAcceptor() );
int port = AvailablePortFinder.getNextAvailable( 1024 );
ldapService.setTcpTransport( new TcpTransport( port ) );
ldapService.getTcpTransport().setNbThreads( 3 );
ldapService.addExtendedOperationHandler( new StartTlsHandler() );
ldapService.addExtendedOperationHandler( new StoredProcedureExtendedOperationHandler() );
// Setup SASL Mechanisms
Map<String, MechanismHandler> mechanismHandlerMap = new HashMap<String,MechanismHandler>();
mechanismHandlerMap.put( SupportedSaslMechanisms.PLAIN, new SimpleMechanismHandler() );
CramMd5MechanismHandler cramMd5MechanismHandler = new CramMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.CRAM_MD5, cramMd5MechanismHandler );
DigestMd5MechanismHandler digestMd5MechanismHandler = new DigestMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.DIGEST_MD5, digestMd5MechanismHandler );
GssapiMechanismHandler gssapiMechanismHandler = new GssapiMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.GSSAPI, gssapiMechanismHandler );
NtlmMechanismHandler ntlmMechanismHandler = new NtlmMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.NTLM, ntlmMechanismHandler );
mechanismHandlerMap.put( SupportedSaslMechanisms.GSS_SPNEGO, ntlmMechanismHandler );
ldapService.setSaslMechanismHandlers( mechanismHandlerMap );
return ldapService;
}
| public LdapService newInstance() throws Exception
{
DirectoryService service = new DefaultDirectoryService();
IntegrationUtils.doDelete( service.getWorkingDirectory() );
service.getChangeLog().setEnabled( true );
service.setShutdownHookEnabled( false );
JdbmPartition system = new JdbmPartition();
system.setId( "system" );
// @TODO need to make this configurable for the system partition
system.setCacheSize( 500 );
system.setSuffix( "ou=system" );
// Add indexed attributes for system partition
Set<Index<?,ServerEntry>> indexedAttrs = new HashSet<Index<?,ServerEntry>>();
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OBJECT_CLASS_AT ) );
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OU_AT ) );
system.setIndexedAttributes( indexedAttrs );
service.setSystemPartition( system );
// change the working directory to something that is unique
// on the system and somewhere either under target directory
// or somewhere in a temp area of the machine.
LdapService ldapService = new LdapService();
ldapService.setDirectoryService( service );
int port = AvailablePortFinder.getNextAvailable( 1024 );
ldapService.setTcpTransport( new TcpTransport( port ) );
ldapService.setSocketAcceptor( new NioSocketAcceptor() );
ldapService.getTcpTransport().setNbThreads( 3 );
ldapService.addExtendedOperationHandler( new StartTlsHandler() );
ldapService.addExtendedOperationHandler( new StoredProcedureExtendedOperationHandler() );
// Setup SASL Mechanisms
Map<String, MechanismHandler> mechanismHandlerMap = new HashMap<String,MechanismHandler>();
mechanismHandlerMap.put( SupportedSaslMechanisms.PLAIN, new SimpleMechanismHandler() );
CramMd5MechanismHandler cramMd5MechanismHandler = new CramMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.CRAM_MD5, cramMd5MechanismHandler );
DigestMd5MechanismHandler digestMd5MechanismHandler = new DigestMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.DIGEST_MD5, digestMd5MechanismHandler );
GssapiMechanismHandler gssapiMechanismHandler = new GssapiMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.GSSAPI, gssapiMechanismHandler );
NtlmMechanismHandler ntlmMechanismHandler = new NtlmMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.NTLM, ntlmMechanismHandler );
mechanismHandlerMap.put( SupportedSaslMechanisms.GSS_SPNEGO, ntlmMechanismHandler );
ldapService.setSaslMechanismHandlers( mechanismHandlerMap );
return ldapService;
}
|
diff --git a/python-checks/src/test/java/org/sonar/python/checks/CheckListTest.java b/python-checks/src/test/java/org/sonar/python/checks/CheckListTest.java
index 85b5bfe9..82d744ac 100644
--- a/python-checks/src/test/java/org/sonar/python/checks/CheckListTest.java
+++ b/python-checks/src/test/java/org/sonar/python/checks/CheckListTest.java
@@ -1,95 +1,95 @@
/*
* Sonar Python Plugin
* Copyright (C) 2011 SonarSource and Waleri Enns
* [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.python.checks;
import com.google.common.collect.Sets;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.sonar.api.rules.AnnotationRuleParser;
import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RuleParam;
import java.io.File;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;
import static org.fest.assertions.Assertions.assertThat;
public class CheckListTest {
/**
* Enforces that each check declared in list.
*/
@Test
public void count() {
int count = 0;
List<File> files = (List<File>) FileUtils.listFiles(new File("src/main/java/org/sonar/python/checks/"), new String[] {"java"}, false);
for (File file : files) {
if (file.getName().endsWith("Check.java")) {
count++;
}
}
assertThat(CheckList.getChecks().size()).isEqualTo(count);
}
/**
* Enforces that each check has test, name and description.
*/
@Test
public void test() {
List<Class> checks = CheckList.getChecks();
for (Class cls : checks) {
String testName = '/' + cls.getName().replace('.', '/') + "Test.class";
assertThat(getClass().getResource(testName))
.overridingErrorMessage("No test for " + cls.getSimpleName())
.isNotNull();
}
ResourceBundle resourceBundle = ResourceBundle.getBundle("org.sonar.l10n.python", Locale.ENGLISH);
Set<String> keys = Sets.newHashSet();
List<Rule> rules = new AnnotationRuleParser().parse("repositoryKey", checks);
for (Rule rule : rules) {
assertThat(keys).as("Duplicate key " + rule.getKey()).excludes(rule.getKey());
keys.add(rule.getKey());
resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".name");
assertThat(getClass().getResource("/org/sonar/l10n/python/rules/python/" + rule.getKey() + ".html"))
.overridingErrorMessage("No description for " + rule.getKey())
.isNotNull();
assertThat(rule.getDescription())
.overridingErrorMessage("Description of " + rule.getKey() + " should be in separate file")
- .isEmpty();
+ .isNull();
for (RuleParam param : rule.getParams()) {
resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".param." + param.getKey());
assertThat(param.getDescription())
.overridingErrorMessage("Description for param " + param.getKey() + " of " + rule.getKey() + " should be in separate file")
.isEmpty();
}
}
}
}
| true | true | public void test() {
List<Class> checks = CheckList.getChecks();
for (Class cls : checks) {
String testName = '/' + cls.getName().replace('.', '/') + "Test.class";
assertThat(getClass().getResource(testName))
.overridingErrorMessage("No test for " + cls.getSimpleName())
.isNotNull();
}
ResourceBundle resourceBundle = ResourceBundle.getBundle("org.sonar.l10n.python", Locale.ENGLISH);
Set<String> keys = Sets.newHashSet();
List<Rule> rules = new AnnotationRuleParser().parse("repositoryKey", checks);
for (Rule rule : rules) {
assertThat(keys).as("Duplicate key " + rule.getKey()).excludes(rule.getKey());
keys.add(rule.getKey());
resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".name");
assertThat(getClass().getResource("/org/sonar/l10n/python/rules/python/" + rule.getKey() + ".html"))
.overridingErrorMessage("No description for " + rule.getKey())
.isNotNull();
assertThat(rule.getDescription())
.overridingErrorMessage("Description of " + rule.getKey() + " should be in separate file")
.isEmpty();
for (RuleParam param : rule.getParams()) {
resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".param." + param.getKey());
assertThat(param.getDescription())
.overridingErrorMessage("Description for param " + param.getKey() + " of " + rule.getKey() + " should be in separate file")
.isEmpty();
}
}
}
| public void test() {
List<Class> checks = CheckList.getChecks();
for (Class cls : checks) {
String testName = '/' + cls.getName().replace('.', '/') + "Test.class";
assertThat(getClass().getResource(testName))
.overridingErrorMessage("No test for " + cls.getSimpleName())
.isNotNull();
}
ResourceBundle resourceBundle = ResourceBundle.getBundle("org.sonar.l10n.python", Locale.ENGLISH);
Set<String> keys = Sets.newHashSet();
List<Rule> rules = new AnnotationRuleParser().parse("repositoryKey", checks);
for (Rule rule : rules) {
assertThat(keys).as("Duplicate key " + rule.getKey()).excludes(rule.getKey());
keys.add(rule.getKey());
resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".name");
assertThat(getClass().getResource("/org/sonar/l10n/python/rules/python/" + rule.getKey() + ".html"))
.overridingErrorMessage("No description for " + rule.getKey())
.isNotNull();
assertThat(rule.getDescription())
.overridingErrorMessage("Description of " + rule.getKey() + " should be in separate file")
.isNull();
for (RuleParam param : rule.getParams()) {
resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".param." + param.getKey());
assertThat(param.getDescription())
.overridingErrorMessage("Description for param " + param.getKey() + " of " + rule.getKey() + " should be in separate file")
.isEmpty();
}
}
}
|
diff --git a/asta4d-sample/src/main/java/com/astamuse/asta4d/sample/snippet/SimpleSnippet.java b/asta4d-sample/src/main/java/com/astamuse/asta4d/sample/snippet/SimpleSnippet.java
index ae760013..f07c6188 100644
--- a/asta4d-sample/src/main/java/com/astamuse/asta4d/sample/snippet/SimpleSnippet.java
+++ b/asta4d-sample/src/main/java/com/astamuse/asta4d/sample/snippet/SimpleSnippet.java
@@ -1,68 +1,68 @@
/*
* Copyright 2012 astamuse company,Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.astamuse.asta4d.sample.snippet;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Element;
import com.astamuse.asta4d.render.GoThroughRenderer;
import com.astamuse.asta4d.render.Renderer;
import com.astamuse.asta4d.util.ElementUtil;
public class SimpleSnippet {
// @ShowCode:showSnippetStart
// @ShowCode:showVariableinjectionStart
public Renderer render(String name) {
if (StringUtils.isEmpty(name)) {
name = "Asta4D";
}
Element element = ElementUtil.parseAsSingle("<span>Hello " + name + "!</span>");
return Renderer.create("*", element);
}
// @ShowCode:showVariableinjectionEnd
public Renderer setProfile() {
Renderer render = new GoThroughRenderer();
render.add("p#name span", "asta4d");
render.add("p#age span", 20);
return render;
}
// @ShowCode:showSnippetEnd
// @ShowCode:showVariableinjectionStart
public Renderer setProfileByVariableInjection(String name, int age) {
Renderer render = new GoThroughRenderer();
render.add("p#name span", name);
render.add("p#age span", age);
return render;
}
// @ShowCode:showVariableinjectionEnd
// @ShowCode:showAttributevaluesStart
public Renderer manipulateAttrValues() {
Renderer render = new GoThroughRenderer();
render.add("input#yes", "checked", "checked");
- render.add("button#delete", "disabled", null);
+ render.add("button#delete", "disabled", (Object) null);
render.add("li#plus", "+class", "red");
render.add("li#minus", "-class", "bold");
return render;
}
// @ShowCode:showAttributevaluesEnd
}
| true | true | public Renderer manipulateAttrValues() {
Renderer render = new GoThroughRenderer();
render.add("input#yes", "checked", "checked");
render.add("button#delete", "disabled", null);
render.add("li#plus", "+class", "red");
render.add("li#minus", "-class", "bold");
return render;
}
| public Renderer manipulateAttrValues() {
Renderer render = new GoThroughRenderer();
render.add("input#yes", "checked", "checked");
render.add("button#delete", "disabled", (Object) null);
render.add("li#plus", "+class", "red");
render.add("li#minus", "-class", "bold");
return render;
}
|
diff --git a/src/org/geometerplus/zlibrary/core/network/ZLNetworkManager.java b/src/org/geometerplus/zlibrary/core/network/ZLNetworkManager.java
index d7ee5b0..8e60789 100644
--- a/src/org/geometerplus/zlibrary/core/network/ZLNetworkManager.java
+++ b/src/org/geometerplus/zlibrary/core/network/ZLNetworkManager.java
@@ -1,225 +1,225 @@
/*
* Copyright (C) 2010 Geometer Plus <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.zlibrary.core.network;
import java.util.*;
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
import java.security.GeneralSecurityException;
import java.security.cert.*;
import org.geometerplus.zlibrary.core.util.ZLNetworkUtil;
import org.geometerplus.zlibrary.core.filesystem.ZLResourceFile;
public class ZLNetworkManager {
private static ZLNetworkManager ourManager;
public static ZLNetworkManager Instance() {
if (ourManager == null) {
ourManager = new ZLNetworkManager();
}
return ourManager;
}
private String doBeforeRequest(ZLNetworkRequest request) {
final String err = request.doBefore();
if (err != null) {
return err;
}
/*if (request.isInstanceOf(ZLNetworkPostRequest::TYPE_ID)) {
return doBeforePostRequest((ZLNetworkPostRequest &) request);
}*/
return null;
}
private String setCommonHTTPOptions(ZLNetworkRequest request, HttpURLConnection httpConnection) {
httpConnection.setInstanceFollowRedirects(request.FollowRedirects);
httpConnection.setConnectTimeout(15000); // FIXME: hardcoded timeout value!!!
httpConnection.setReadTimeout(30000); // FIXME: hardcoded timeout value!!!
//httpConnection.setRequestProperty("Connection", "Close");
httpConnection.setRequestProperty("User-Agent", ZLNetworkUtil.getUserAgent());
httpConnection.setAllowUserInteraction(false);
if (httpConnection instanceof HttpsURLConnection) {
HttpsURLConnection httpsConnection = (HttpsURLConnection) httpConnection;
if (request.SSLCertificate != null) {
InputStream stream;
try {
ZLResourceFile file = ZLResourceFile.createResourceFile(request.SSLCertificate);
stream = file.getInputStream();
} catch (IOException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_BAD_FILE, request.SSLCertificate);
}
try {
TrustManager[] managers = new TrustManager[] { new ZLX509TrustManager(stream) };
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, managers, null);
httpsConnection.setSSLSocketFactory(context.getSocketFactory());
} catch (CertificateExpiredException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_EXPIRED, request.SSLCertificate);
} catch (CertificateNotYetValidException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_NOT_YET_VALID, request.SSLCertificate);
} catch (CertificateException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_BAD_FILE, request.SSLCertificate);
} catch (GeneralSecurityException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_SUBSYSTEM);
} finally {
try {
stream.close();
} catch (IOException ex) {
}
}
}
}
// TODO: handle Authentication
return null;
}
public String perform(ZLNetworkRequest request) {
- boolean sucess = false;
+ boolean success = false;
try {
final String error = doBeforeRequest(request);
if (error != null) {
return error;
}
HttpURLConnection httpConnection = null;
int response = -1;
for (int retryCounter = 0; retryCounter < 3 && response == -1; ++retryCounter) {
final URL url = new URL(request.URL);
final URLConnection connection = url.openConnection();
if (!(connection instanceof HttpURLConnection)) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_UNSUPPORTED_PROTOCOL);
}
httpConnection = (HttpURLConnection) connection;
String err = setCommonHTTPOptions(request, httpConnection);
if (err != null) {
return err;
}
httpConnection.connect();
response = httpConnection.getResponseCode();
}
if (response == HttpURLConnection.HTTP_OK) {
InputStream stream = httpConnection.getInputStream();
try {
final String err = request.doHandleStream(httpConnection, stream);
if (err != null) {
return err;
}
} finally {
stream.close();
}
- sucess = true;
+ success = true;
} else {
if (response == HttpURLConnection.HTTP_UNAUTHORIZED) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_AUTHENTICATION_FAILED);
} else {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
}
}
} catch (SSLHandshakeException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_CONNECT, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLKeyException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_BAD_KEY, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLPeerUnverifiedException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PEER_UNVERIFIED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLProtocolException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PROTOCOL_ERROR);
} catch (SSLException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_SUBSYSTEM);
} catch (ConnectException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_CONNECTION_REFUSED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (NoRouteToHostException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_HOST_CANNOT_BE_REACHED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (UnknownHostException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_RESOLVE_HOST, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (MalformedURLException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_INVALID_URL);
} catch (SocketTimeoutException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_TIMEOUT);
} catch (IOException ex) {
ex.printStackTrace();
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
} finally {
- final String err = request.doAfter(sucess);
- if (sucess && err != null) {
+ final String err = request.doAfter(success);
+ if (success && err != null) {
return err;
}
}
return null;
}
public String perform(List<ZLNetworkRequest> requests) {
if (requests.size() == 0) {
return "";
}
if (requests.size() == 1) {
return perform(requests.get(0));
}
HashSet<String> errors = new HashSet<String>();
// TODO: implement concurrent execution !!!
for (ZLNetworkRequest r: requests) {
final String e = perform(r);
if (e != null && !errors.contains(e)) {
errors.add(e);
}
}
if (errors.size() == 0) {
return null;
}
StringBuilder message = new StringBuilder();
for (String e: errors) {
if (message.length() != 0) {
message.append(", ");
}
message.append(e);
}
return message.toString();
}
public final String downloadToFile(String url, final File outFile) {
return downloadToFile(url, outFile, 8192);
}
public final String downloadToFile(String url, final File outFile, final int bufferSize) {
return perform(new ZLNetworkRequest(url) {
public String handleStream(URLConnection connection, InputStream inputStream) throws IOException {
OutputStream outStream = new FileOutputStream(outFile);
try {
final byte[] buffer = new byte[bufferSize];
while (true) {
final int size = inputStream.read(buffer);
if (size <= 0) {
break;
}
outStream.write(buffer, 0, size);
}
} finally {
outStream.close();
}
return null;
}
});
}
}
| false | true | public String perform(ZLNetworkRequest request) {
boolean sucess = false;
try {
final String error = doBeforeRequest(request);
if (error != null) {
return error;
}
HttpURLConnection httpConnection = null;
int response = -1;
for (int retryCounter = 0; retryCounter < 3 && response == -1; ++retryCounter) {
final URL url = new URL(request.URL);
final URLConnection connection = url.openConnection();
if (!(connection instanceof HttpURLConnection)) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_UNSUPPORTED_PROTOCOL);
}
httpConnection = (HttpURLConnection) connection;
String err = setCommonHTTPOptions(request, httpConnection);
if (err != null) {
return err;
}
httpConnection.connect();
response = httpConnection.getResponseCode();
}
if (response == HttpURLConnection.HTTP_OK) {
InputStream stream = httpConnection.getInputStream();
try {
final String err = request.doHandleStream(httpConnection, stream);
if (err != null) {
return err;
}
} finally {
stream.close();
}
sucess = true;
} else {
if (response == HttpURLConnection.HTTP_UNAUTHORIZED) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_AUTHENTICATION_FAILED);
} else {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
}
}
} catch (SSLHandshakeException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_CONNECT, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLKeyException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_BAD_KEY, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLPeerUnverifiedException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PEER_UNVERIFIED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLProtocolException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PROTOCOL_ERROR);
} catch (SSLException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_SUBSYSTEM);
} catch (ConnectException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_CONNECTION_REFUSED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (NoRouteToHostException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_HOST_CANNOT_BE_REACHED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (UnknownHostException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_RESOLVE_HOST, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (MalformedURLException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_INVALID_URL);
} catch (SocketTimeoutException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_TIMEOUT);
} catch (IOException ex) {
ex.printStackTrace();
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
} finally {
final String err = request.doAfter(sucess);
if (sucess && err != null) {
return err;
}
}
return null;
}
| public String perform(ZLNetworkRequest request) {
boolean success = false;
try {
final String error = doBeforeRequest(request);
if (error != null) {
return error;
}
HttpURLConnection httpConnection = null;
int response = -1;
for (int retryCounter = 0; retryCounter < 3 && response == -1; ++retryCounter) {
final URL url = new URL(request.URL);
final URLConnection connection = url.openConnection();
if (!(connection instanceof HttpURLConnection)) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_UNSUPPORTED_PROTOCOL);
}
httpConnection = (HttpURLConnection) connection;
String err = setCommonHTTPOptions(request, httpConnection);
if (err != null) {
return err;
}
httpConnection.connect();
response = httpConnection.getResponseCode();
}
if (response == HttpURLConnection.HTTP_OK) {
InputStream stream = httpConnection.getInputStream();
try {
final String err = request.doHandleStream(httpConnection, stream);
if (err != null) {
return err;
}
} finally {
stream.close();
}
success = true;
} else {
if (response == HttpURLConnection.HTTP_UNAUTHORIZED) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_AUTHENTICATION_FAILED);
} else {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
}
}
} catch (SSLHandshakeException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_CONNECT, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLKeyException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_BAD_KEY, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLPeerUnverifiedException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PEER_UNVERIFIED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLProtocolException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PROTOCOL_ERROR);
} catch (SSLException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_SUBSYSTEM);
} catch (ConnectException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_CONNECTION_REFUSED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (NoRouteToHostException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_HOST_CANNOT_BE_REACHED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (UnknownHostException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_RESOLVE_HOST, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (MalformedURLException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_INVALID_URL);
} catch (SocketTimeoutException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_TIMEOUT);
} catch (IOException ex) {
ex.printStackTrace();
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
} finally {
final String err = request.doAfter(success);
if (success && err != null) {
return err;
}
}
return null;
}
|
diff --git a/src/com/mrockey28/bukkit/ItemRepair/AutoRepairSupport.java b/src/com/mrockey28/bukkit/ItemRepair/AutoRepairSupport.java
index a42084e..0ebc922 100644
--- a/src/com/mrockey28/bukkit/ItemRepair/AutoRepairSupport.java
+++ b/src/com/mrockey28/bukkit/ItemRepair/AutoRepairSupport.java
@@ -1,505 +1,503 @@
package com.mrockey28.bukkit.ItemRepair;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import net.milkbowl.vault.Vault;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import com.mrockey28.bukkit.ItemRepair.AutoRepairPlugin.operationType;
/**
*
* @author lostaris, mrockey28
*/
public class AutoRepairSupport {
private final AutoRepairPlugin plugin;
protected static Player player;
public AutoRepairSupport(AutoRepairPlugin instance, Player player) {
plugin = instance;
AutoRepairSupport.player = player;
}
private boolean warning = false;
private boolean lastWarning = false;
private float CalcPercentUsed(ItemStack tool, int durability)
{
float percentUsed = -1;
percentUsed = (float)tool.getDurability() / (float)durability;
return percentUsed;
}
public boolean accountForRoundingType (int slot, ArrayList<ItemStack> req, String itemName)
{
return true;
}
public void toolReq(ItemStack tool, int slot) {
doRepairOperation(tool, slot, operationType.QUERY);
}
public void deduct(ArrayList<ItemStack> req) {
PlayerInventory inven = player.getInventory();
for (int i =0; i < req.size(); i++) {
ItemStack currItem = new ItemStack(req.get(i).getTypeId(), req.get(i).getAmount());
int neededAmount = req.get(i).getAmount();
int smallestSlot = findSmallest(currItem);
if (smallestSlot != -1) {
while (neededAmount > 0) {
smallestSlot = findSmallest(currItem);
ItemStack smallestItem = inven.getItem(smallestSlot);
if (neededAmount < smallestItem.getAmount()) {
// got enough in smallest stack deal and done
ItemStack newSize = new ItemStack(currItem.getType(), smallestItem.getAmount() - neededAmount);
inven.setItem(smallestSlot, newSize);
neededAmount = 0;
} else {
// need to remove from more than one stack, deal and continue
neededAmount -= smallestItem.getAmount();
inven.clear(smallestSlot);
}
}
}
}
}
public void doRepairOperation(ItemStack tool, int slot, AutoRepairPlugin.operationType op)
{
double balance = AutoRepairPlugin.econ.getBalance(player.getName());
if (!AutoRepairPlugin.isOpAllowed(getPlayer(), op)) {
return;
}
if (op == operationType.WARN && !AutoRepairPlugin.isRepairCosts() && !AutoRepairPlugin.isAutoRepair()) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
}
if (op == operationType.WARN && !warning) warning = true;
else if (op == operationType.WARN) return;
PlayerInventory inven = getPlayer().getInventory();
HashMap<String, ArrayList<ItemStack> > recipies = AutoRepairPlugin.getRepairRecipies();
String itemName = Material.getMaterial(tool.getTypeId()).toString();
HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts();
ArrayList<ItemStack> req = new ArrayList<ItemStack>(recipies.get(itemName).size());
ArrayList<ItemStack> neededItems = new ArrayList<ItemStack>(0);
//do a deep copy of the required items list so we can modify it temporarily for rounding purposes
for (ItemStack i: recipies.get(itemName)) {
req.add((ItemStack)i.clone());
}
String toolString = tool.getType().toString();
int durability = durabilities.get(itemName);
double cost = 0;
if (AutoRepairPlugin.getiConCosts().containsKey(toolString)) {
cost = (double)AutoRepairPlugin.getiConCosts().get(itemName);
}
else
{
player.sendMessage("�cThis item is not in the AutoRepair database.");
return;
}
//do rounding based on dmg already done to item, if called for by config
if (op != operationType.AUTO_REPAIR && AutoRepairPlugin.rounding != "flat")
{
float percentUsed = CalcPercentUsed(inven.getItem(slot), durability);
for (int index = 0; index < req.size(); index++) {
float amnt = req.get(index).getAmount();
int amntInt;
amnt = amnt * percentUsed;
cost = cost * percentUsed;
amnt = Math.round(amnt);
amntInt = (int)amnt;
if (AutoRepairPlugin.rounding == "min")
{
if (amntInt == 0)
{
amntInt = 1;
}
}
req.get(index).setAmount(amntInt);
}
}
try {
//No repair costs
if (!AutoRepairPlugin.isRepairCosts()) {
switch (op)
{
case WARN:
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
getPlayer().sendMessage("�3Repaired " + itemName);
inven.setItem(slot, repItem(tool));
break;
case QUERY:
getPlayer().sendMessage("�3No materials needed to repair.");
break;
}
}
//Using economy to pay only
else if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("true") == 0)
{
switch (op)
{ case QUERY:
player.sendMessage("�6It costs " + AutoRepairPlugin.econ.format((double)cost)
+ " to repair " + tool.getType());
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (cost <= balance) {
//balance = iConomy.db.get_balance(player.getName());
AutoRepairPlugin.econ.withdrawPlayer(player.getName(), cost);
player.sendMessage("�3Using " + AutoRepairPlugin.econ.format((double)cost) + " to repair " + itemName);
//inven.setItem(slot, repItem(tool));
inven.setItem(slot, repItem(tool));
} else {
iConWarn(itemName, cost);
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
if (cost > balance) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
iConWarn(toolString, cost);
}
break;
}
}
//Using both economy and item costs to pay
else if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("both") == 0)
{
switch (op)
{
case QUERY:
- isEnoughItems(req, neededItems);
player.sendMessage("�6To repair " + tool.getType() + " you need: "
+ AutoRepairPlugin.econ.format((double)cost) + " and");
- player.sendMessage("�6" + printFormatReqs(neededItems));
+ player.sendMessage("�6" + printFormatReqs(req));
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (cost <= balance && isEnoughItems(req, neededItems)) {
//balance = iConomy.db.get_balance(player.getName());
AutoRepairPlugin.econ.withdrawPlayer(player.getName(), cost);
deduct(req);
player.sendMessage("�3Using " + AutoRepairPlugin.econ.format((double)cost) + " and");
player.sendMessage("�3" + printFormatReqs(req) + " to repair " + itemName);
inven.setItem(slot, repItem(tool));
} else {
if (op == operationType.MANUAL_REPAIR || !getLastWarning()) {
if (AutoRepairPlugin.isAllowed(player, "warn")) {
if (cost > balance && !isEnoughItems(req, neededItems)) bothWarn(itemName, cost, neededItems);
else if (cost > balance) iConWarn(itemName, cost);
else justItemsWarn(itemName, neededItems);
}
if (op == operationType.AUTO_REPAIR) setLastWarning(true);
}
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
else if (cost > balance || !isEnoughItems(req, neededItems)) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
if (cost > balance && !isEnoughItems(req, neededItems)) bothWarn(itemName, cost, neededItems);
else if (cost > balance) iConWarn(itemName, cost);
else justItemsWarn(itemName, neededItems);
}
break;
}
}
//Just using item costs to pay
else
{
switch (op)
{
case QUERY:
- isEnoughItems(req, neededItems);
player.sendMessage("�6To repair " + tool.getType() + " you need:");
- player.sendMessage("�6" + printFormatReqs(neededItems));
+ player.sendMessage("�6" + printFormatReqs(req));
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (isEnoughItems(req, neededItems)) {
deduct(req);
player.sendMessage("�3Using " + printFormatReqs(req) + " to repair " + itemName);
inven.setItem(slot, repItem(tool));
} else {
if (op == operationType.MANUAL_REPAIR || !getLastWarning()) {
if (AutoRepairPlugin.isAllowed(player, "warn")) {
justItemsWarn(itemName, req);
}
if (op == operationType.AUTO_REPAIR) setLastWarning(true);
}
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
else if (!isEnoughItems(req, neededItems)) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
justItemsWarn(toolString, neededItems);
}
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public void repairWarn(ItemStack tool, int slot) {
doRepairOperation(tool, slot, operationType.WARN);
}
public boolean repArmourInfo(String query) {
if (AutoRepairPlugin.isRepairCosts()) {
try {
char getRecipe = query.charAt(0);
if (getRecipe == '?') {
//ArrayList<ItemStack> req = this.repArmourAmount(player);
//player.sendMessage("�6To repair all your armour you need:");
//player.sendMessage("�6" + this.printFormatReqs(req));
int total =0;
ArrayList<ItemStack> req = repArmourAmount();
PlayerInventory inven = player.getInventory();
if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("true") == 0){
for (ItemStack i : inven.getArmorContents()) {
if (AutoRepairPlugin.getiConCosts().containsKey(i.getType().toString())) {
total += AutoRepairPlugin.getiConCosts().get(i.getType().toString());
}
}
player.sendMessage("�6To repair all your armour you need: "
+ AutoRepairPlugin.econ.format((double)total));
// icon and item cost
} else if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("both") == 0) {
for (ItemStack i : inven.getArmorContents()) {
if (AutoRepairPlugin.getiConCosts().containsKey(i.getType().toString())) {
total += AutoRepairPlugin.getiConCosts().get(i.getType().toString());
}
}
player.sendMessage("�6To repair all your armour you need: "
+ AutoRepairPlugin.econ.format((double)total));
player.sendMessage("�6" + this.printFormatReqs(req));
// just item cost
} else {
player.sendMessage("�6To repair all your armour you need:");
player.sendMessage("�6" + this.printFormatReqs(req));
}
}
} catch (Exception e) {
return false;
}
} else {
player.sendMessage("�3No materials needed to repair");
}
return true;
}
public ArrayList<ItemStack> repArmourAmount() {
HashMap<String, ArrayList<ItemStack> > recipies = AutoRepairPlugin.getRepairRecipies();
PlayerInventory inven = player.getInventory();
ItemStack[] armour = inven.getArmorContents();
HashMap<String, Integer> totalCost = new HashMap<String, Integer>();
for (int i=0; i<armour.length; i++) {
String item = armour[i].getType().toString();
if (recipies.containsKey(item)) {
ArrayList<ItemStack> reqItems = recipies.get(item);
for (int j =0; j<reqItems.size(); j++) {
if(totalCost.containsKey(reqItems.get(j).getType().toString())) {
int amount = totalCost.get(reqItems.get(j).getType().toString());
totalCost.remove(reqItems.get(j).getType().toString());
int newAmount = amount + reqItems.get(j).getAmount();
totalCost.put(reqItems.get(j).getType().toString(), newAmount);
} else {
totalCost.put(reqItems.get(j).getType().toString(), reqItems.get(j).getAmount());
}
}
}
}
ArrayList<ItemStack> req = new ArrayList<ItemStack>();
for (Object key: totalCost.keySet()) {
req.add(new ItemStack(Material.getMaterial(key.toString()), totalCost.get(key)));
}
return req;
}
public ItemStack repItem(ItemStack item) {
item.setDurability((short) 0);
return item;
}
//prints the durability left of the current tool to the player
public void durabilityLeft(ItemStack tool) {
if (AutoRepairPlugin.isAllowed(player, "info")) { //!AutoRepairPlugin.isPermissions || AutoRepairPlugin.Permissions.has(player, "AutoRepair.info")) {
int usesLeft = this.returnUsesLeft(tool);
if (usesLeft != -1) {
player.sendMessage("�3" + usesLeft + " blocks left untill this tool breaks." );
} else {
player.sendMessage("�6This is not a tool.");
}
} else {
player.sendMessage("�cYou dont have permission to do the ? or dmg commands.");
}
}
public int returnUsesLeft(ItemStack tool) {
int usesLeft = -1;
HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts();
String itemName = Material.getMaterial(tool.getTypeId()).toString();
int durability = durabilities.get(itemName);
usesLeft = durability - tool.getDurability();
return usesLeft;
}
@SuppressWarnings("unchecked")
public int findSmallest(ItemStack item) {
PlayerInventory inven = player.getInventory();
HashMap<Integer, ? extends ItemStack> items = inven.all(item.getTypeId());
int slot = -1;
int smallest = 64;
//iterator for the hashmap
Set<?> set = items.entrySet();
Iterator<?> i = set.iterator();
//ItemStack highest = new ItemStack(repairItem.getType(), 0);
while(i.hasNext()){
Map.Entry me = (Map.Entry)i.next();
ItemStack item1 = (ItemStack) me.getValue();
//if the player has doesn't not have enough of the item used to repair
if (item1.getAmount() <= smallest) {
smallest = item1.getAmount();
slot = (Integer)me.getKey();
}
}
return slot;
}
@SuppressWarnings("unchecked")
public int getTotalItems(ItemStack item) {
int total = 0;
PlayerInventory inven = player.getInventory();
HashMap<Integer, ? extends ItemStack> items = inven.all(item.getTypeId());
//iterator for the hashmap
Set<?> set = items.entrySet();
Iterator<?> i = set.iterator();
//ItemStack highest = new ItemStack(repairItem.getType(), 0);
while(i.hasNext()){
Map.Entry me = (Map.Entry)i.next();
ItemStack item1 = (ItemStack) me.getValue();
//if the player has doesn't not have enough of the item used to repair
total += item1.getAmount();
}
return total;
}
// checks to see if the player has enough of a list of items
public boolean isEnough(String itemName) {
ArrayList<ItemStack> reqItems = AutoRepairPlugin.getRepairRecipies().get(itemName);
boolean enoughItemFlag = true;
for (int i =0; i < reqItems.size(); i++) {
ItemStack currItem = new ItemStack(reqItems.get(i).getTypeId(), reqItems.get(i).getAmount());
int neededAmount = reqItems.get(i).getAmount();
int currTotal = getTotalItems(currItem);
if (neededAmount > currTotal) {
enoughItemFlag = false;
}
}
return enoughItemFlag;
}
public boolean isEnoughItems (ArrayList<ItemStack> req, ArrayList<ItemStack> neededItems) {
boolean enough = true;
for (int i =0; i<req.size(); i++) {
ItemStack currItem = new ItemStack(req.get(i).getTypeId(), req.get(i).getAmount());
int neededAmount = req.get(i).getAmount();
int currTotal = getTotalItems(currItem);
if (neededAmount > currTotal) {
neededItems.add(req.get(i).clone());
enough = false;
}
}
return enough;
}
public void iConWarn(String itemName, double total) {
getPlayer().sendMessage("�cYou are cannot afford to repair " + itemName);
getPlayer().sendMessage("�cNeed: " + AutoRepairPlugin.econ.format((double)total));
}
public void bothWarn(String itemName, double total, ArrayList<ItemStack> req) {
getPlayer().sendMessage("�cYou are missing one or more items to repair " + itemName);
getPlayer().sendMessage("�cNeed: " + printFormatReqs(req) + " and " +
AutoRepairPlugin.econ.format((double)total));
}
public void justItemsWarn(String itemName, ArrayList<ItemStack> req) {
player.sendMessage("�cYou are missing one or more items to repair " + itemName);
player.sendMessage("�cNeed: " + printFormatReqs(req));
}
public String printFormatReqs(ArrayList<ItemStack> items) {
StringBuffer string = new StringBuffer();
string.append(" ");
for (int i = 0; i < items.size(); i++) {
string.append(items.get(i).getAmount() + " " + items.get(i).getType() + " ");
}
return string.toString();
}
public boolean getWarning() {
return warning;
}
public boolean getLastWarning() {
return lastWarning;
}
public void setWarning(boolean newValue) {
this.warning = newValue;
}
public void setLastWarning(boolean newValue) {
this.lastWarning = newValue;
}
public AutoRepairPlugin getPlugin() {
return plugin;
}
public static Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
AutoRepairSupport.player = player;
}
}
| false | true | public void doRepairOperation(ItemStack tool, int slot, AutoRepairPlugin.operationType op)
{
double balance = AutoRepairPlugin.econ.getBalance(player.getName());
if (!AutoRepairPlugin.isOpAllowed(getPlayer(), op)) {
return;
}
if (op == operationType.WARN && !AutoRepairPlugin.isRepairCosts() && !AutoRepairPlugin.isAutoRepair()) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
}
if (op == operationType.WARN && !warning) warning = true;
else if (op == operationType.WARN) return;
PlayerInventory inven = getPlayer().getInventory();
HashMap<String, ArrayList<ItemStack> > recipies = AutoRepairPlugin.getRepairRecipies();
String itemName = Material.getMaterial(tool.getTypeId()).toString();
HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts();
ArrayList<ItemStack> req = new ArrayList<ItemStack>(recipies.get(itemName).size());
ArrayList<ItemStack> neededItems = new ArrayList<ItemStack>(0);
//do a deep copy of the required items list so we can modify it temporarily for rounding purposes
for (ItemStack i: recipies.get(itemName)) {
req.add((ItemStack)i.clone());
}
String toolString = tool.getType().toString();
int durability = durabilities.get(itemName);
double cost = 0;
if (AutoRepairPlugin.getiConCosts().containsKey(toolString)) {
cost = (double)AutoRepairPlugin.getiConCosts().get(itemName);
}
else
{
player.sendMessage("�cThis item is not in the AutoRepair database.");
return;
}
//do rounding based on dmg already done to item, if called for by config
if (op != operationType.AUTO_REPAIR && AutoRepairPlugin.rounding != "flat")
{
float percentUsed = CalcPercentUsed(inven.getItem(slot), durability);
for (int index = 0; index < req.size(); index++) {
float amnt = req.get(index).getAmount();
int amntInt;
amnt = amnt * percentUsed;
cost = cost * percentUsed;
amnt = Math.round(amnt);
amntInt = (int)amnt;
if (AutoRepairPlugin.rounding == "min")
{
if (amntInt == 0)
{
amntInt = 1;
}
}
req.get(index).setAmount(amntInt);
}
}
try {
//No repair costs
if (!AutoRepairPlugin.isRepairCosts()) {
switch (op)
{
case WARN:
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
getPlayer().sendMessage("�3Repaired " + itemName);
inven.setItem(slot, repItem(tool));
break;
case QUERY:
getPlayer().sendMessage("�3No materials needed to repair.");
break;
}
}
//Using economy to pay only
else if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("true") == 0)
{
switch (op)
{ case QUERY:
player.sendMessage("�6It costs " + AutoRepairPlugin.econ.format((double)cost)
+ " to repair " + tool.getType());
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (cost <= balance) {
//balance = iConomy.db.get_balance(player.getName());
AutoRepairPlugin.econ.withdrawPlayer(player.getName(), cost);
player.sendMessage("�3Using " + AutoRepairPlugin.econ.format((double)cost) + " to repair " + itemName);
//inven.setItem(slot, repItem(tool));
inven.setItem(slot, repItem(tool));
} else {
iConWarn(itemName, cost);
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
if (cost > balance) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
iConWarn(toolString, cost);
}
break;
}
}
//Using both economy and item costs to pay
else if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("both") == 0)
{
switch (op)
{
case QUERY:
isEnoughItems(req, neededItems);
player.sendMessage("�6To repair " + tool.getType() + " you need: "
+ AutoRepairPlugin.econ.format((double)cost) + " and");
player.sendMessage("�6" + printFormatReqs(neededItems));
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (cost <= balance && isEnoughItems(req, neededItems)) {
//balance = iConomy.db.get_balance(player.getName());
AutoRepairPlugin.econ.withdrawPlayer(player.getName(), cost);
deduct(req);
player.sendMessage("�3Using " + AutoRepairPlugin.econ.format((double)cost) + " and");
player.sendMessage("�3" + printFormatReqs(req) + " to repair " + itemName);
inven.setItem(slot, repItem(tool));
} else {
if (op == operationType.MANUAL_REPAIR || !getLastWarning()) {
if (AutoRepairPlugin.isAllowed(player, "warn")) {
if (cost > balance && !isEnoughItems(req, neededItems)) bothWarn(itemName, cost, neededItems);
else if (cost > balance) iConWarn(itemName, cost);
else justItemsWarn(itemName, neededItems);
}
if (op == operationType.AUTO_REPAIR) setLastWarning(true);
}
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
else if (cost > balance || !isEnoughItems(req, neededItems)) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
if (cost > balance && !isEnoughItems(req, neededItems)) bothWarn(itemName, cost, neededItems);
else if (cost > balance) iConWarn(itemName, cost);
else justItemsWarn(itemName, neededItems);
}
break;
}
}
//Just using item costs to pay
else
{
switch (op)
{
case QUERY:
isEnoughItems(req, neededItems);
player.sendMessage("�6To repair " + tool.getType() + " you need:");
player.sendMessage("�6" + printFormatReqs(neededItems));
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (isEnoughItems(req, neededItems)) {
deduct(req);
player.sendMessage("�3Using " + printFormatReqs(req) + " to repair " + itemName);
inven.setItem(slot, repItem(tool));
} else {
if (op == operationType.MANUAL_REPAIR || !getLastWarning()) {
if (AutoRepairPlugin.isAllowed(player, "warn")) {
justItemsWarn(itemName, req);
}
if (op == operationType.AUTO_REPAIR) setLastWarning(true);
}
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
else if (!isEnoughItems(req, neededItems)) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
justItemsWarn(toolString, neededItems);
}
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
| public void doRepairOperation(ItemStack tool, int slot, AutoRepairPlugin.operationType op)
{
double balance = AutoRepairPlugin.econ.getBalance(player.getName());
if (!AutoRepairPlugin.isOpAllowed(getPlayer(), op)) {
return;
}
if (op == operationType.WARN && !AutoRepairPlugin.isRepairCosts() && !AutoRepairPlugin.isAutoRepair()) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
}
if (op == operationType.WARN && !warning) warning = true;
else if (op == operationType.WARN) return;
PlayerInventory inven = getPlayer().getInventory();
HashMap<String, ArrayList<ItemStack> > recipies = AutoRepairPlugin.getRepairRecipies();
String itemName = Material.getMaterial(tool.getTypeId()).toString();
HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts();
ArrayList<ItemStack> req = new ArrayList<ItemStack>(recipies.get(itemName).size());
ArrayList<ItemStack> neededItems = new ArrayList<ItemStack>(0);
//do a deep copy of the required items list so we can modify it temporarily for rounding purposes
for (ItemStack i: recipies.get(itemName)) {
req.add((ItemStack)i.clone());
}
String toolString = tool.getType().toString();
int durability = durabilities.get(itemName);
double cost = 0;
if (AutoRepairPlugin.getiConCosts().containsKey(toolString)) {
cost = (double)AutoRepairPlugin.getiConCosts().get(itemName);
}
else
{
player.sendMessage("�cThis item is not in the AutoRepair database.");
return;
}
//do rounding based on dmg already done to item, if called for by config
if (op != operationType.AUTO_REPAIR && AutoRepairPlugin.rounding != "flat")
{
float percentUsed = CalcPercentUsed(inven.getItem(slot), durability);
for (int index = 0; index < req.size(); index++) {
float amnt = req.get(index).getAmount();
int amntInt;
amnt = amnt * percentUsed;
cost = cost * percentUsed;
amnt = Math.round(amnt);
amntInt = (int)amnt;
if (AutoRepairPlugin.rounding == "min")
{
if (amntInt == 0)
{
amntInt = 1;
}
}
req.get(index).setAmount(amntInt);
}
}
try {
//No repair costs
if (!AutoRepairPlugin.isRepairCosts()) {
switch (op)
{
case WARN:
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
getPlayer().sendMessage("�3Repaired " + itemName);
inven.setItem(slot, repItem(tool));
break;
case QUERY:
getPlayer().sendMessage("�3No materials needed to repair.");
break;
}
}
//Using economy to pay only
else if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("true") == 0)
{
switch (op)
{ case QUERY:
player.sendMessage("�6It costs " + AutoRepairPlugin.econ.format((double)cost)
+ " to repair " + tool.getType());
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (cost <= balance) {
//balance = iConomy.db.get_balance(player.getName());
AutoRepairPlugin.econ.withdrawPlayer(player.getName(), cost);
player.sendMessage("�3Using " + AutoRepairPlugin.econ.format((double)cost) + " to repair " + itemName);
//inven.setItem(slot, repItem(tool));
inven.setItem(slot, repItem(tool));
} else {
iConWarn(itemName, cost);
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
if (cost > balance) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
iConWarn(toolString, cost);
}
break;
}
}
//Using both economy and item costs to pay
else if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("both") == 0)
{
switch (op)
{
case QUERY:
player.sendMessage("�6To repair " + tool.getType() + " you need: "
+ AutoRepairPlugin.econ.format((double)cost) + " and");
player.sendMessage("�6" + printFormatReqs(req));
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (cost <= balance && isEnoughItems(req, neededItems)) {
//balance = iConomy.db.get_balance(player.getName());
AutoRepairPlugin.econ.withdrawPlayer(player.getName(), cost);
deduct(req);
player.sendMessage("�3Using " + AutoRepairPlugin.econ.format((double)cost) + " and");
player.sendMessage("�3" + printFormatReqs(req) + " to repair " + itemName);
inven.setItem(slot, repItem(tool));
} else {
if (op == operationType.MANUAL_REPAIR || !getLastWarning()) {
if (AutoRepairPlugin.isAllowed(player, "warn")) {
if (cost > balance && !isEnoughItems(req, neededItems)) bothWarn(itemName, cost, neededItems);
else if (cost > balance) iConWarn(itemName, cost);
else justItemsWarn(itemName, neededItems);
}
if (op == operationType.AUTO_REPAIR) setLastWarning(true);
}
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
else if (cost > balance || !isEnoughItems(req, neededItems)) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
if (cost > balance && !isEnoughItems(req, neededItems)) bothWarn(itemName, cost, neededItems);
else if (cost > balance) iConWarn(itemName, cost);
else justItemsWarn(itemName, neededItems);
}
break;
}
}
//Just using item costs to pay
else
{
switch (op)
{
case QUERY:
player.sendMessage("�6To repair " + tool.getType() + " you need:");
player.sendMessage("�6" + printFormatReqs(req));
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (isEnoughItems(req, neededItems)) {
deduct(req);
player.sendMessage("�3Using " + printFormatReqs(req) + " to repair " + itemName);
inven.setItem(slot, repItem(tool));
} else {
if (op == operationType.MANUAL_REPAIR || !getLastWarning()) {
if (AutoRepairPlugin.isAllowed(player, "warn")) {
justItemsWarn(itemName, req);
}
if (op == operationType.AUTO_REPAIR) setLastWarning(true);
}
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
else if (!isEnoughItems(req, neededItems)) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
justItemsWarn(toolString, neededItems);
}
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
|
diff --git a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/editors/InvisibleContextElementsPart.java b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/editors/InvisibleContextElementsPart.java
index 1f1ee4bce..82be6b204 100644
--- a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/editors/InvisibleContextElementsPart.java
+++ b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/editors/InvisibleContextElementsPart.java
@@ -1,410 +1,410 @@
/*******************************************************************************
* Copyright (c) 2004, 2008 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.context.ui.editors;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.context.core.AbstractContextStructureBridge;
import org.eclipse.mylyn.context.core.ContextCore;
import org.eclipse.mylyn.context.core.IInteractionContext;
import org.eclipse.mylyn.context.core.IInteractionElement;
import org.eclipse.mylyn.internal.commons.ui.SwtUtil;
import org.eclipse.mylyn.internal.context.core.ContextCorePlugin;
import org.eclipse.mylyn.internal.context.ui.ContextUiPlugin;
import org.eclipse.mylyn.internal.provisional.commons.ui.WorkbenchUtil;
import org.eclipse.mylyn.tasks.ui.TasksUiImages;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.navigator.CommonViewer;
/**
* @author Shawn Minto
*/
public class InvisibleContextElementsPart {
private final class InteractionElementTableSorter extends ViewerSorter {
private int criteria = 0;
private boolean isDecending = true;
private final ITableLabelProvider labelProvider;
public InteractionElementTableSorter(ITableLabelProvider labelProvider) {
this.labelProvider = labelProvider;
}
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
int result = 0;
String value1 = labelProvider.getColumnText(e1, criteria);
String value2 = labelProvider.getColumnText(e2, criteria);
if (value1 == null && value2 != null) {
result = -1;
} else if (value1 != null && value2 == null) {
result = 1;
} else if (value1 != null && value2 != null) {
result = value1.compareTo(value2);
}
return isDecending() ? (result * -1) : result;
}
public boolean isDecending() {
return isDecending;
}
public void setCriteria(int index) {
if (criteria == index) {
isDecending = !isDecending;
} else {
isDecending = false;
}
criteria = index;
}
}
private final class InteractionElementTableLabelProvider extends LabelProvider implements ITableLabelProvider {
@Override
public String getText(Object element) {
if (element instanceof IInteractionElement) {
return ((IInteractionElement) element).getHandleIdentifier();
}
return super.getText(element);
}
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
if (element instanceof IInteractionElement) {
if (columnIndex == 0) {
return ((IInteractionElement) element).getHandleIdentifier();
} else if (columnIndex == 1) {
return ((IInteractionElement) element).getContentType();
}
}
return ""; //$NON-NLS-1$
}
}
private final class RemoveInvisibleAction extends Action {
public RemoveInvisibleAction() {
setText(Messages.ContextEditorFormPage_Remove_Invisible_);
setToolTipText(Messages.ContextEditorFormPage_Remove_Invisible_);
setImageDescriptor(TasksUiImages.CONTEXT_CLEAR);
}
@Override
public void run() {
if (commonViewer == null) {
MessageDialog.openWarning(WorkbenchUtil.getShell(), Messages.ContextEditorFormPage_Remove_Invisible,
Messages.ContextEditorFormPage_Activate_task_to_remove_invisible);
return;
}
boolean confirmed = MessageDialog.openConfirm(Display.getCurrent().getActiveShell(),
Messages.ContextEditorFormPage_Remove_Invisible,
Messages.ContextEditorFormPage_Remove_every_element_not_visible);
if (confirmed) {
if (ContextCore.getContextManager().isContextActive()) {
try {
final Collection<Object> allVisible = getAllVisibleElementsInContextPage();
PlatformUI.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException {
monitor.beginTask(Messages.InvisibleContextElementsPart_Collecting_all_invisible,
IProgressMonitor.UNKNOWN);
if (allVisible != null) {
IInteractionContext context = ContextCore.getContextManager().getActiveContext();
final List<IInteractionElement> allToRemove = getAllInvisibleElements(context,
allVisible);
Display.getDefault().asyncExec(new Runnable() {
public void run() {
ContextCore.getContextManager().deleteElements(allToRemove);
}
});
} else {
MessageDialog.openInformation(Display.getCurrent().getActiveShell(),
Messages.ContextEditorFormPage_Remove_Invisible,
Messages.ContextEditorFormPage_No_context_active);
}
}
});
} catch (InvocationTargetException e) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, e.getMessage(), e));
} catch (InterruptedException e) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, e.getMessage(), e));
}
} else {
MessageDialog.openInformation(Display.getCurrent().getActiveShell(),
Messages.ContextEditorFormPage_Remove_Invisible,
Messages.ContextEditorFormPage_No_context_active);
}
}
}
}
private TableViewer invisibleTable;
private Section invisibleSection;
private final CommonViewer commonViewer;
public InvisibleContextElementsPart(CommonViewer commonViewer) {
this.commonViewer = commonViewer;
}
public Control createControl(FormToolkit toolkit, Composite composite) {
invisibleSection = toolkit.createSection(composite, ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE);
invisibleSection.setText(NLS.bind(Messages.InvisibleContextElementsPart_Invisible_elements, "0")); //$NON-NLS-1$
invisibleSection.setEnabled(false);
Composite toolbarComposite = toolkit.createComposite(invisibleSection);
toolbarComposite.setBackground(null);
invisibleSection.setTextClient(toolbarComposite);
RowLayout rowLayout = new RowLayout();
rowLayout.marginTop = 0;
rowLayout.marginBottom = 0;
toolbarComposite.setLayout(rowLayout);
ToolBarManager toolbarManager = new ToolBarManager(SWT.FLAT);
toolbarManager.add(new RemoveInvisibleAction());
toolbarManager.createControl(toolbarComposite);
toolbarManager.markDirty();
toolbarManager.update(true);
Composite invisibleSectionClient = toolkit.createComposite(invisibleSection);
invisibleSectionClient.setLayout(new GridLayout());
invisibleSection.setClient(invisibleSectionClient);
Composite tableComposite = toolkit.createComposite(invisibleSectionClient);
- GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 200).grab(true, false).applyTo(tableComposite);
+ GridDataFactory.fillDefaults().hint(500, 200).grab(true, false).applyTo(tableComposite);
TableColumnLayout layout = new TableColumnLayout();
tableComposite.setLayout(layout);
invisibleTable = new TableViewer(tableComposite, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL
| SWT.FULL_SELECTION | SWT.HIDE_SELECTION);
invisibleTable.setColumnProperties(new String[] { Messages.InvisibleContextElementsPart_Structure_handle,
Messages.InvisibleContextElementsPart_Structure_kind });
invisibleTable.getTable().setHeaderVisible(true);
Table table = invisibleTable.getTable();
toolkit.adapt(table);
table.setMenu(null);
InteractionElementTableLabelProvider labelProvider = new InteractionElementTableLabelProvider();
invisibleTable.setLabelProvider(labelProvider);
invisibleTable.setContentProvider(new IStructuredContentProvider() {
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// ignore
}
public void dispose() {
// ignore
}
public Object[] getElements(Object inputElement) {
if (inputElement instanceof Collection<?>) {
return ((Collection<?>) inputElement).toArray();
}
return new Object[0];
}
});
InteractionElementTableSorter invisibleTableSorter = new InteractionElementTableSorter(labelProvider);
invisibleTableSorter.setCriteria(0);
invisibleTable.setSorter(invisibleTableSorter);
- createColumn(layout, 0, Messages.InvisibleContextElementsPart_Structure_handle, 300, table,
+ createColumn(layout, 0, Messages.InvisibleContextElementsPart_Structure_handle, 400, table,
invisibleTableSorter);
createColumn(layout, 1, Messages.InvisibleContextElementsPart_Structure_kind, 100, table, invisibleTableSorter);
table.setSortColumn(table.getColumn(0));
table.setSortDirection(SWT.DOWN);
if (ContextCore.getContextManager().isContextActive()) {
Collection<Object> allVisible = getAllVisibleElementsInContextPage();
if (allVisible != null) {
IInteractionContext context = ContextCore.getContextManager().getActiveContext();
updateInvisibleSectionInBackground(context, allVisible);
}
}
return invisibleSection;
}
private void createColumn(TableColumnLayout layout, final int index, String label, int weight, final Table table,
final InteractionElementTableSorter invisibleTableSorter) {
final TableColumn column = new TableColumn(table, SWT.LEFT, index);
column.setText(label);
column.setToolTipText(label);
column.setResizable(true);
layout.setColumnData(column, new ColumnPixelData(weight, true));
column.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
invisibleTableSorter.setCriteria(index);
table.setSortColumn(column);
if (invisibleTableSorter.isDecending()) {
table.setSortDirection(SWT.UP);
} else {
table.setSortDirection(SWT.DOWN);
}
invisibleTable.refresh();
}
});
}
public void updateInvisibleElementsSection() {
if (ContextCore.getContextManager().isContextActive()) {
Collection<Object> allVisible = getAllVisibleElementsInContextPage();
if (allVisible != null) {
IInteractionContext context = ContextCore.getContextManager().getActiveContext();
updateInvisibleSectionInBackground(context, allVisible);
}
}
}
private void updateInvisibleSectionInBackground(final IInteractionContext context,
final Collection<Object> allVisible) {
Job j = new Job(Messages.InvisibleContextElementsPart_Updating_invisible_element_list) {
@Override
protected IStatus run(IProgressMonitor monitor) {
monitor.beginTask(Messages.InvisibleContextElementsPart_Computing_invisible_elements,
IProgressMonitor.UNKNOWN);
final List<IInteractionElement> allInvisibleElements = getAllInvisibleElements(context, allVisible);
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if (invisibleSection != null && !invisibleSection.isDisposed()) {
invisibleSection.setText(NLS.bind(Messages.InvisibleContextElementsPart_Invisible_elements,
allInvisibleElements.size()));
invisibleSection.layout();
if (allInvisibleElements.size() == 0) {
invisibleSection.setExpanded(false);
invisibleSection.setEnabled(false);
} else {
invisibleSection.setEnabled(true);
}
}
if (invisibleTable != null && !invisibleTable.getTable().isDisposed()) {
invisibleTable.setInput(allInvisibleElements);
}
}
});
return Status.OK_STATUS;
};
};
j.schedule();
}
private List<IInteractionElement> getAllInvisibleElements(IInteractionContext context, Collection<Object> allVisible) {
List<IInteractionElement> allToRemove = context.getAllElements();
List<IInteractionElement> allVisibleElements = new ArrayList<IInteractionElement>();
for (Object visibleObject : allVisible) {
for (AbstractContextStructureBridge bridge : ContextCorePlugin.getDefault().getStructureBridges().values()) {
// AbstractContextStructureBridge bridge = ContextCorePlugin.getDefault().getStructureBridge(visibleObject);
if (bridge != null) {
String handle = bridge.getHandleIdentifier(visibleObject);
if (handle != null) {
IInteractionElement element = context.get(handle);
if (element != null) {
allVisibleElements.add(element);
}
}
}
}
AbstractContextStructureBridge bridge = ContextCorePlugin.getDefault().getStructureBridge(
ContextCore.CONTENT_TYPE_RESOURCE);
if (bridge != null) {
String handle = bridge.getHandleIdentifier(visibleObject);
if (handle != null) {
IInteractionElement element = context.get(handle);
if (element != null) {
allVisibleElements.add(element);
}
}
}
}
IInteractionElement emptyElement = context.get(""); //$NON-NLS-1$
if (emptyElement != null) {
allVisibleElements.add(emptyElement);
}
allToRemove.removeAll(allVisibleElements);
return allToRemove;
}
private Collection<Object> getAllVisibleElementsInContextPage() {
if (commonViewer == null || commonViewer.getTree() == null || commonViewer.getTree().isDisposed()) {
return null;
}
Set<Object> allVisible = new HashSet<Object>();
SwtUtil.collectItemData(commonViewer.getTree().getItems(), allVisible);
return allVisible;
}
}
| false | true | public Control createControl(FormToolkit toolkit, Composite composite) {
invisibleSection = toolkit.createSection(composite, ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE);
invisibleSection.setText(NLS.bind(Messages.InvisibleContextElementsPart_Invisible_elements, "0")); //$NON-NLS-1$
invisibleSection.setEnabled(false);
Composite toolbarComposite = toolkit.createComposite(invisibleSection);
toolbarComposite.setBackground(null);
invisibleSection.setTextClient(toolbarComposite);
RowLayout rowLayout = new RowLayout();
rowLayout.marginTop = 0;
rowLayout.marginBottom = 0;
toolbarComposite.setLayout(rowLayout);
ToolBarManager toolbarManager = new ToolBarManager(SWT.FLAT);
toolbarManager.add(new RemoveInvisibleAction());
toolbarManager.createControl(toolbarComposite);
toolbarManager.markDirty();
toolbarManager.update(true);
Composite invisibleSectionClient = toolkit.createComposite(invisibleSection);
invisibleSectionClient.setLayout(new GridLayout());
invisibleSection.setClient(invisibleSectionClient);
Composite tableComposite = toolkit.createComposite(invisibleSectionClient);
GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 200).grab(true, false).applyTo(tableComposite);
TableColumnLayout layout = new TableColumnLayout();
tableComposite.setLayout(layout);
invisibleTable = new TableViewer(tableComposite, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL
| SWT.FULL_SELECTION | SWT.HIDE_SELECTION);
invisibleTable.setColumnProperties(new String[] { Messages.InvisibleContextElementsPart_Structure_handle,
Messages.InvisibleContextElementsPart_Structure_kind });
invisibleTable.getTable().setHeaderVisible(true);
Table table = invisibleTable.getTable();
toolkit.adapt(table);
table.setMenu(null);
InteractionElementTableLabelProvider labelProvider = new InteractionElementTableLabelProvider();
invisibleTable.setLabelProvider(labelProvider);
invisibleTable.setContentProvider(new IStructuredContentProvider() {
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// ignore
}
public void dispose() {
// ignore
}
public Object[] getElements(Object inputElement) {
if (inputElement instanceof Collection<?>) {
return ((Collection<?>) inputElement).toArray();
}
return new Object[0];
}
});
InteractionElementTableSorter invisibleTableSorter = new InteractionElementTableSorter(labelProvider);
invisibleTableSorter.setCriteria(0);
invisibleTable.setSorter(invisibleTableSorter);
createColumn(layout, 0, Messages.InvisibleContextElementsPart_Structure_handle, 300, table,
invisibleTableSorter);
createColumn(layout, 1, Messages.InvisibleContextElementsPart_Structure_kind, 100, table, invisibleTableSorter);
table.setSortColumn(table.getColumn(0));
table.setSortDirection(SWT.DOWN);
if (ContextCore.getContextManager().isContextActive()) {
Collection<Object> allVisible = getAllVisibleElementsInContextPage();
if (allVisible != null) {
IInteractionContext context = ContextCore.getContextManager().getActiveContext();
updateInvisibleSectionInBackground(context, allVisible);
}
}
return invisibleSection;
}
| public Control createControl(FormToolkit toolkit, Composite composite) {
invisibleSection = toolkit.createSection(composite, ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE);
invisibleSection.setText(NLS.bind(Messages.InvisibleContextElementsPart_Invisible_elements, "0")); //$NON-NLS-1$
invisibleSection.setEnabled(false);
Composite toolbarComposite = toolkit.createComposite(invisibleSection);
toolbarComposite.setBackground(null);
invisibleSection.setTextClient(toolbarComposite);
RowLayout rowLayout = new RowLayout();
rowLayout.marginTop = 0;
rowLayout.marginBottom = 0;
toolbarComposite.setLayout(rowLayout);
ToolBarManager toolbarManager = new ToolBarManager(SWT.FLAT);
toolbarManager.add(new RemoveInvisibleAction());
toolbarManager.createControl(toolbarComposite);
toolbarManager.markDirty();
toolbarManager.update(true);
Composite invisibleSectionClient = toolkit.createComposite(invisibleSection);
invisibleSectionClient.setLayout(new GridLayout());
invisibleSection.setClient(invisibleSectionClient);
Composite tableComposite = toolkit.createComposite(invisibleSectionClient);
GridDataFactory.fillDefaults().hint(500, 200).grab(true, false).applyTo(tableComposite);
TableColumnLayout layout = new TableColumnLayout();
tableComposite.setLayout(layout);
invisibleTable = new TableViewer(tableComposite, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL
| SWT.FULL_SELECTION | SWT.HIDE_SELECTION);
invisibleTable.setColumnProperties(new String[] { Messages.InvisibleContextElementsPart_Structure_handle,
Messages.InvisibleContextElementsPart_Structure_kind });
invisibleTable.getTable().setHeaderVisible(true);
Table table = invisibleTable.getTable();
toolkit.adapt(table);
table.setMenu(null);
InteractionElementTableLabelProvider labelProvider = new InteractionElementTableLabelProvider();
invisibleTable.setLabelProvider(labelProvider);
invisibleTable.setContentProvider(new IStructuredContentProvider() {
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// ignore
}
public void dispose() {
// ignore
}
public Object[] getElements(Object inputElement) {
if (inputElement instanceof Collection<?>) {
return ((Collection<?>) inputElement).toArray();
}
return new Object[0];
}
});
InteractionElementTableSorter invisibleTableSorter = new InteractionElementTableSorter(labelProvider);
invisibleTableSorter.setCriteria(0);
invisibleTable.setSorter(invisibleTableSorter);
createColumn(layout, 0, Messages.InvisibleContextElementsPart_Structure_handle, 400, table,
invisibleTableSorter);
createColumn(layout, 1, Messages.InvisibleContextElementsPart_Structure_kind, 100, table, invisibleTableSorter);
table.setSortColumn(table.getColumn(0));
table.setSortDirection(SWT.DOWN);
if (ContextCore.getContextManager().isContextActive()) {
Collection<Object> allVisible = getAllVisibleElementsInContextPage();
if (allVisible != null) {
IInteractionContext context = ContextCore.getContextManager().getActiveContext();
updateInvisibleSectionInBackground(context, allVisible);
}
}
return invisibleSection;
}
|
diff --git a/src/mmb/foss/aueb/icong/DrawableAreaView.java b/src/mmb/foss/aueb/icong/DrawableAreaView.java
index 2e75b22..26fd822 100644
--- a/src/mmb/foss/aueb/icong/DrawableAreaView.java
+++ b/src/mmb/foss/aueb/icong/DrawableAreaView.java
@@ -1,306 +1,308 @@
package mmb.foss.aueb.icong;
import java.io.InputStream;
import java.util.ArrayList;
import mmb.foss.aueb.icong.boxes.Box;
import mmb.foss.aueb.icong.boxes.SavedState;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class DrawableAreaView extends View {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private ArrayList<Box> boxes = new ArrayList<Box>();
private Context mContext;
private Box selectedBox = null;
private int pressedX, pressedY;
private int originalX, originalY;
private int[] buttonCenter = new int[2];
private int WIDTH, HEIGHT;
private ArrayList<BoxButtonPair[]> lines = new ArrayList<BoxButtonPair[]>();
private Box box = null;
private int buttonPressed = -1;
private int buttonHovered = -1;
private boolean drawingline = false;
private boolean foundPair = false;
private int lineStartX, lineStartY, lineCurrentX, lineCurrentY;
private long tap;
private final int DOUBLE_TAP_INTERVAL = (int) (0.3 * 1000);
private BitmapDrawable trash;
private boolean showTrash;
private int trashX, trashY;
private Box possibleTrash;
public DrawableAreaView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
mContext = context;
paint.setColor(Color.BLACK);
WIDTH = MainActivity.width;
HEIGHT = MainActivity.height;
boxes = SavedState.getBoxes();
lines = SavedState.getLines();
}
protected void onDraw(Canvas c) {
if (WIDTH == 0 || trash == null) {
WIDTH = this.getWidth();
HEIGHT = this.getHeight();
InputStream is = mContext.getResources().openRawResource(
R.drawable.trash);
Bitmap originalBitmap = BitmapFactory.decodeStream(is);
int w = WIDTH / 10, h = (w * originalBitmap.getHeight())
/ originalBitmap.getWidth();
trash = new BitmapDrawable(mContext.getResources(),
Bitmap.createScaledBitmap(originalBitmap, w, h, true));
trashX = (WIDTH - trash.getBitmap().getWidth()) / 2;
trashY = HEIGHT - 40;
}
for (Box box : boxes) {
// TODO: Zooming to be removed
box.setZoom(1.8);
c.drawBitmap(box.getBitmap(), box.getX(), box.getY(), null);
for (int i = 0; i < box.getNumOfButtons(); i++) {
if (box.isPressed(i)) {
buttonCenter = box.getButtonCenter(i);
c.drawCircle(buttonCenter[0], buttonCenter[1],
box.getButtonRadius(i), paint);
}
}
}
for (BoxButtonPair[] line : lines) {
Box box0 = line[0].getBox(), box1 = line[1].getBox();
int button0 = line[0].getButton(), button1 = line[1].getButton();
int[] center0 = box0.getButtonCenter(button0), center1 = box1
.getButtonCenter(button1);
c.drawLine(center0[0], center0[1], center1[0], center1[1], paint);
}
if (drawingline) {
c.drawLine(lineStartX, lineStartY, lineCurrentX, lineCurrentY,
paint);
}
if (showTrash) {
c.drawBitmap(trash.getBitmap(), trashX, trashY, paint);
}
}
public void addBox(Box box) {
int x, y;
if (mContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
y = getLower() + 15;
x = (WIDTH / 2) - (box.getWidth() / 2);
} else {
y = (HEIGHT / 2) - (box.getHeight() / 2);
x = getRighter() + 15;
}
box.setY(y);
box.setX(x);
boxes.add(box);
SavedState.addBox(box);
invalidate();
}
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (showTrash && onTrash(event.getX(), event.getY())) {
// if trash icon is visible and clicked delete the possibleTrash
// box
deleteBox(possibleTrash);
possibleTrash = null;
}
box = getBoxTouched((int) event.getX(), (int) event.getY());
if (box != null) {
// if we have touched inside a box
selectedBox = box;
buttonPressed = box.isButton((int) event.getX(),
(int) event.getY());
// TODO double tap implementation
long tap = System.currentTimeMillis();
if (System.currentTimeMillis() - this.tap < DOUBLE_TAP_INTERVAL) {
// if we have double tapped inside a box
System.out.println("this is double tap");
} else {
System.out.println("this is NOT double tap");
}
this.tap = tap;
if (buttonPressed == -1) {
// if we haven't touched the box's button
pressedX = (int) event.getX();
pressedY = (int) event.getY();
originalX = box.getX();
originalY = box.getY();
showTrash = true;
possibleTrash = box;
} else {
// if we have touched the box's button
showTrash = false;
possibleTrash = null;
if (buttonPressed >= box.getNoOfInputs()) {
// if button pressed is an output button
if (!box.isPressed(buttonPressed)) {
// if the button pressed wasn't pressed before
box.setButtonPressed(buttonPressed);
} else {
// if the button pressed was pressed before deletes
// this connection/line
- removeLine(box,buttonPressed);
+ removeLine(box, buttonPressed);
}
int[] center = box.getButtonCenter(buttonPressed);
lineStartX = center[0];
lineStartY = center[1];
lineCurrentX = lineStartX;
lineCurrentY = lineStartY;
drawingline = true;
}
invalidate();
selectedBox = null;
}
} else {
// if we haven't touched inside a box
showTrash = false;
possibleTrash = null;
}
break;
case MotionEvent.ACTION_MOVE:
if (selectedBox != null) {
// if we have selected a box by tapping once in it
selectedBox.setX((int) event.getX() - (pressedX - originalX));
selectedBox.setY((int) event.getY() - (pressedY - originalY));
invalidate();
}
if (drawingline) {
// if we have pressed a previously not pressed box's output
// button
lineCurrentX = (int) event.getX();
lineCurrentY = (int) event.getY();
Box boxHovered = getBoxTouched((int) event.getX(),
(int) event.getY());
if (boxHovered != null) {
// if we have drawned a line on another box
buttonHovered = boxHovered.isButton((int) event.getX(),
(int) event.getY());
if (buttonHovered != -1) {
// if we have drawned a line on another's box's button
- if (buttonHovered < boxHovered.getNoOfInputs() && !boxHovered.isPressed(buttonHovered)) {
+ if (buttonHovered < boxHovered.getNoOfInputs()
+ && !boxHovered.isPressed(buttonHovered)
+ && !box.equals(boxHovered)) {
// if we have drawned a line on another's box's
// input button
int[] center = boxHovered
.getButtonCenter(buttonHovered);
lineStartX = center[0];
lineStartY = center[1];
boxHovered.setButtonPressed(buttonHovered);
drawingline = false;
BoxButtonPair[] line = {
new BoxButtonPair(box, buttonPressed),
new BoxButtonPair(boxHovered, buttonHovered) };
lines.add(line);
SavedState.addLine(line);
foundPair = true;
}
}
}
}
invalidate();
break;
case MotionEvent.ACTION_UP:
drawingline = false;
selectedBox = null;
// if when drawing a line stops and we haven'd reached another box's
// input button then erase the line and unpress the button
if (!foundPair && buttonPressed != -1 && box != null)
if (!((buttonPressed + 1) <= box.getNoOfInputs()))
box.unsetButtonPressed(buttonPressed);
foundPair = false;
pressedX = pressedY = originalX = originalY = 0;
// TODO implement here to pou peftei
invalidate();
return false;
}
return true;
}
// returns the lower pixel of the lower element
private int getLower() {
int y = 0;
for (Box box : boxes) {
if (y < box.getYY())
y = box.getYY();
}
return y;
}
// returns the righter pixel of the righter element
private int getRighter() {
int x = 0;
for (Box box : boxes) {
if (x < box.getXX())
x = box.getXX();
}
return x;
}
// returns the box that was touched
private Box getBoxTouched(int x, int y) {
for (Box b : boxes) {
if (b.isOnBox(x, y)) {
return b;
}
}
return null;
}
private boolean onTrash(float f, float g) {
boolean isOnTrash = false;
if (f >= trashX && f <= (trashX + trash.getBitmap().getWidth())
&& g >= trashY && g <= (trashY + trash.getBitmap().getHeight())) {
isOnTrash = true;
}
return isOnTrash;
}
private void deleteBox(Box box2del) {
boxes.remove(box2del);
removeLines(box2del);
SavedState.removeBox(box2del);
}
private void removeLine(Box box, int button) {
BoxButtonPair pair = new BoxButtonPair(box, button);
for (BoxButtonPair[] line : lines) {
if (line[0].equals(pair)) {
Box otherBox = line[1].getBox();
int otherButton = line[1].getButton();
lines.remove(line);
SavedState.removeLine(line);
otherBox.unsetButtonPressed(otherButton);
break;
} else if (line[1].equals(pair)) {
Box otherBox = line[0].getBox();
int otherButton = line[0].getButton();
lines.remove(line);
SavedState.removeLine(line);
otherBox.unsetButtonPressed(otherButton);
break;
}
}
}
private void removeLines(Box box) {
for (int i = 0; i < box.getNumOfButtons(); i++) {
removeLine(box, i);
}
}
}
| false | true | public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (showTrash && onTrash(event.getX(), event.getY())) {
// if trash icon is visible and clicked delete the possibleTrash
// box
deleteBox(possibleTrash);
possibleTrash = null;
}
box = getBoxTouched((int) event.getX(), (int) event.getY());
if (box != null) {
// if we have touched inside a box
selectedBox = box;
buttonPressed = box.isButton((int) event.getX(),
(int) event.getY());
// TODO double tap implementation
long tap = System.currentTimeMillis();
if (System.currentTimeMillis() - this.tap < DOUBLE_TAP_INTERVAL) {
// if we have double tapped inside a box
System.out.println("this is double tap");
} else {
System.out.println("this is NOT double tap");
}
this.tap = tap;
if (buttonPressed == -1) {
// if we haven't touched the box's button
pressedX = (int) event.getX();
pressedY = (int) event.getY();
originalX = box.getX();
originalY = box.getY();
showTrash = true;
possibleTrash = box;
} else {
// if we have touched the box's button
showTrash = false;
possibleTrash = null;
if (buttonPressed >= box.getNoOfInputs()) {
// if button pressed is an output button
if (!box.isPressed(buttonPressed)) {
// if the button pressed wasn't pressed before
box.setButtonPressed(buttonPressed);
} else {
// if the button pressed was pressed before deletes
// this connection/line
removeLine(box,buttonPressed);
}
int[] center = box.getButtonCenter(buttonPressed);
lineStartX = center[0];
lineStartY = center[1];
lineCurrentX = lineStartX;
lineCurrentY = lineStartY;
drawingline = true;
}
invalidate();
selectedBox = null;
}
} else {
// if we haven't touched inside a box
showTrash = false;
possibleTrash = null;
}
break;
case MotionEvent.ACTION_MOVE:
if (selectedBox != null) {
// if we have selected a box by tapping once in it
selectedBox.setX((int) event.getX() - (pressedX - originalX));
selectedBox.setY((int) event.getY() - (pressedY - originalY));
invalidate();
}
if (drawingline) {
// if we have pressed a previously not pressed box's output
// button
lineCurrentX = (int) event.getX();
lineCurrentY = (int) event.getY();
Box boxHovered = getBoxTouched((int) event.getX(),
(int) event.getY());
if (boxHovered != null) {
// if we have drawned a line on another box
buttonHovered = boxHovered.isButton((int) event.getX(),
(int) event.getY());
if (buttonHovered != -1) {
// if we have drawned a line on another's box's button
if (buttonHovered < boxHovered.getNoOfInputs() && !boxHovered.isPressed(buttonHovered)) {
// if we have drawned a line on another's box's
// input button
int[] center = boxHovered
.getButtonCenter(buttonHovered);
lineStartX = center[0];
lineStartY = center[1];
boxHovered.setButtonPressed(buttonHovered);
drawingline = false;
BoxButtonPair[] line = {
new BoxButtonPair(box, buttonPressed),
new BoxButtonPair(boxHovered, buttonHovered) };
lines.add(line);
SavedState.addLine(line);
foundPair = true;
}
}
}
}
invalidate();
break;
case MotionEvent.ACTION_UP:
drawingline = false;
selectedBox = null;
// if when drawing a line stops and we haven'd reached another box's
// input button then erase the line and unpress the button
if (!foundPair && buttonPressed != -1 && box != null)
if (!((buttonPressed + 1) <= box.getNoOfInputs()))
box.unsetButtonPressed(buttonPressed);
foundPair = false;
pressedX = pressedY = originalX = originalY = 0;
// TODO implement here to pou peftei
invalidate();
return false;
}
return true;
}
| public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (showTrash && onTrash(event.getX(), event.getY())) {
// if trash icon is visible and clicked delete the possibleTrash
// box
deleteBox(possibleTrash);
possibleTrash = null;
}
box = getBoxTouched((int) event.getX(), (int) event.getY());
if (box != null) {
// if we have touched inside a box
selectedBox = box;
buttonPressed = box.isButton((int) event.getX(),
(int) event.getY());
// TODO double tap implementation
long tap = System.currentTimeMillis();
if (System.currentTimeMillis() - this.tap < DOUBLE_TAP_INTERVAL) {
// if we have double tapped inside a box
System.out.println("this is double tap");
} else {
System.out.println("this is NOT double tap");
}
this.tap = tap;
if (buttonPressed == -1) {
// if we haven't touched the box's button
pressedX = (int) event.getX();
pressedY = (int) event.getY();
originalX = box.getX();
originalY = box.getY();
showTrash = true;
possibleTrash = box;
} else {
// if we have touched the box's button
showTrash = false;
possibleTrash = null;
if (buttonPressed >= box.getNoOfInputs()) {
// if button pressed is an output button
if (!box.isPressed(buttonPressed)) {
// if the button pressed wasn't pressed before
box.setButtonPressed(buttonPressed);
} else {
// if the button pressed was pressed before deletes
// this connection/line
removeLine(box, buttonPressed);
}
int[] center = box.getButtonCenter(buttonPressed);
lineStartX = center[0];
lineStartY = center[1];
lineCurrentX = lineStartX;
lineCurrentY = lineStartY;
drawingline = true;
}
invalidate();
selectedBox = null;
}
} else {
// if we haven't touched inside a box
showTrash = false;
possibleTrash = null;
}
break;
case MotionEvent.ACTION_MOVE:
if (selectedBox != null) {
// if we have selected a box by tapping once in it
selectedBox.setX((int) event.getX() - (pressedX - originalX));
selectedBox.setY((int) event.getY() - (pressedY - originalY));
invalidate();
}
if (drawingline) {
// if we have pressed a previously not pressed box's output
// button
lineCurrentX = (int) event.getX();
lineCurrentY = (int) event.getY();
Box boxHovered = getBoxTouched((int) event.getX(),
(int) event.getY());
if (boxHovered != null) {
// if we have drawned a line on another box
buttonHovered = boxHovered.isButton((int) event.getX(),
(int) event.getY());
if (buttonHovered != -1) {
// if we have drawned a line on another's box's button
if (buttonHovered < boxHovered.getNoOfInputs()
&& !boxHovered.isPressed(buttonHovered)
&& !box.equals(boxHovered)) {
// if we have drawned a line on another's box's
// input button
int[] center = boxHovered
.getButtonCenter(buttonHovered);
lineStartX = center[0];
lineStartY = center[1];
boxHovered.setButtonPressed(buttonHovered);
drawingline = false;
BoxButtonPair[] line = {
new BoxButtonPair(box, buttonPressed),
new BoxButtonPair(boxHovered, buttonHovered) };
lines.add(line);
SavedState.addLine(line);
foundPair = true;
}
}
}
}
invalidate();
break;
case MotionEvent.ACTION_UP:
drawingline = false;
selectedBox = null;
// if when drawing a line stops and we haven'd reached another box's
// input button then erase the line and unpress the button
if (!foundPair && buttonPressed != -1 && box != null)
if (!((buttonPressed + 1) <= box.getNoOfInputs()))
box.unsetButtonPressed(buttonPressed);
foundPair = false;
pressedX = pressedY = originalX = originalY = 0;
// TODO implement here to pou peftei
invalidate();
return false;
}
return true;
}
|
diff --git a/src/com/cyanogenmod/filemanager/ui/widgets/NavigationView.java b/src/com/cyanogenmod/filemanager/ui/widgets/NavigationView.java
index f17c645..61aa09e 100644
--- a/src/com/cyanogenmod/filemanager/ui/widgets/NavigationView.java
+++ b/src/com/cyanogenmod/filemanager/ui/widgets/NavigationView.java
@@ -1,1386 +1,1390 @@
/*
* Copyright (C) 2012 The CyanogenMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cyanogenmod.filemanager.ui.widgets;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.os.AsyncTask;
import android.os.storage.StorageVolume;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.cyanogenmod.filemanager.FileManagerApplication;
import com.cyanogenmod.filemanager.R;
import com.cyanogenmod.filemanager.adapters.FileSystemObjectAdapter;
import com.cyanogenmod.filemanager.adapters.FileSystemObjectAdapter.OnSelectionChangedListener;
import com.cyanogenmod.filemanager.console.ConsoleAllocException;
import com.cyanogenmod.filemanager.listeners.OnHistoryListener;
import com.cyanogenmod.filemanager.listeners.OnRequestRefreshListener;
import com.cyanogenmod.filemanager.listeners.OnSelectionListener;
import com.cyanogenmod.filemanager.model.Directory;
import com.cyanogenmod.filemanager.model.FileSystemObject;
import com.cyanogenmod.filemanager.model.ParentDirectory;
import com.cyanogenmod.filemanager.model.Symlink;
import com.cyanogenmod.filemanager.parcelables.NavigationViewInfoParcelable;
import com.cyanogenmod.filemanager.parcelables.SearchInfoParcelable;
import com.cyanogenmod.filemanager.preferences.AccessMode;
import com.cyanogenmod.filemanager.preferences.DisplayRestrictions;
import com.cyanogenmod.filemanager.preferences.FileManagerSettings;
import com.cyanogenmod.filemanager.preferences.NavigationLayoutMode;
import com.cyanogenmod.filemanager.preferences.ObjectIdentifier;
import com.cyanogenmod.filemanager.preferences.Preferences;
import com.cyanogenmod.filemanager.ui.ThemeManager;
import com.cyanogenmod.filemanager.ui.ThemeManager.Theme;
import com.cyanogenmod.filemanager.ui.policy.DeleteActionPolicy;
import com.cyanogenmod.filemanager.ui.policy.IntentsActionPolicy;
import com.cyanogenmod.filemanager.ui.widgets.FlingerListView.OnItemFlingerListener;
import com.cyanogenmod.filemanager.ui.widgets.FlingerListView.OnItemFlingerResponder;
import com.cyanogenmod.filemanager.util.CommandHelper;
import com.cyanogenmod.filemanager.util.DialogHelper;
import com.cyanogenmod.filemanager.util.ExceptionUtil;
import com.cyanogenmod.filemanager.util.ExceptionUtil.OnRelaunchCommandResult;
import com.cyanogenmod.filemanager.util.FileHelper;
import com.cyanogenmod.filemanager.util.StorageHelper;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The file manager implementation view (contains the graphical representation and the input
* management for a file manager; shows the folders/files, the mode view, react touch events,
* navigate, ...).
*/
public class NavigationView extends RelativeLayout implements
AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener,
BreadcrumbListener, OnSelectionChangedListener, OnSelectionListener, OnRequestRefreshListener {
private static final String TAG = "NavigationView"; //$NON-NLS-1$
/**
* An interface to communicate selection changes events.
*/
public interface OnNavigationSelectionChangedListener {
/**
* Method invoked when the selection changed.
*
* @param navView The navigation view that generate the event
* @param selectedItems The new selected items
*/
void onSelectionChanged(NavigationView navView, List<FileSystemObject> selectedItems);
}
/**
* An interface to communicate a request for show the menu associated
* with an item.
*/
public interface OnNavigationRequestMenuListener {
/**
* Method invoked when a request to show the menu associated
* with an item is started.
*
* @param navView The navigation view that generate the event
* @param item The item for which the request was started
*/
void onRequestMenu(NavigationView navView, FileSystemObject item);
}
/**
* An interface to communicate a request when the user choose a file.
*/
public interface OnFilePickedListener {
/**
* Method invoked when a request when the user choose a file.
*
* @param item The item choose
*/
void onFilePicked(FileSystemObject item);
}
/**
* An interface to communicate a change of the current directory
*/
public interface OnDirectoryChangedListener {
/**
* Method invoked when the current directory changes
*
* @param item The newly active directory
*/
void onDirectoryChanged(FileSystemObject item);
}
/**
* The navigation view mode
* @hide
*/
public enum NAVIGATION_MODE {
/**
* The navigation view acts as a browser, and allow open files itself.
*/
BROWSABLE,
/**
* The navigation view acts as a picker of files
*/
PICKABLE,
}
/**
* A listener for flinging events from {@link FlingerListView}
*/
private final OnItemFlingerListener mOnItemFlingerListener = new OnItemFlingerListener() {
@Override
public boolean onItemFlingerStart(
AdapterView<?> parent, View view, int position, long id) {
try {
// Response if the item can be removed
FileSystemObjectAdapter adapter = (FileSystemObjectAdapter)parent.getAdapter();
FileSystemObject fso = adapter.getItem(position);
if (fso != null) {
if (fso instanceof ParentDirectory) {
return false;
}
return true;
}
} catch (Exception e) {
ExceptionUtil.translateException(getContext(), e, true, false);
}
return false;
}
@Override
public void onItemFlingerEnd(OnItemFlingerResponder responder,
AdapterView<?> parent, View view, int position, long id) {
try {
// Response if the item can be removed
FileSystemObjectAdapter adapter = (FileSystemObjectAdapter)parent.getAdapter();
FileSystemObject fso = adapter.getItem(position);
if (fso != null) {
DeleteActionPolicy.removeFileSystemObject(
getContext(),
fso,
NavigationView.this,
NavigationView.this,
responder);
return;
}
// Cancels the flinger operation
responder.cancel();
} catch (Exception e) {
ExceptionUtil.translateException(getContext(), e, true, false);
responder.cancel();
}
}
};
private int mId;
private String mCurrentDir;
private NavigationLayoutMode mCurrentMode;
/**
* @hide
*/
List<FileSystemObject> mFiles;
private FileSystemObjectAdapter mAdapter;
private boolean mChangingDir;
private final Object mSync = new Object();
private OnHistoryListener mOnHistoryListener;
private OnNavigationSelectionChangedListener mOnNavigationSelectionChangedListener;
private OnNavigationRequestMenuListener mOnNavigationRequestMenuListener;
private OnFilePickedListener mOnFilePickedListener;
private OnDirectoryChangedListener mOnDirectoryChangedListener;
private boolean mChRooted;
private NAVIGATION_MODE mNavigationMode;
// Restrictions
private Map<DisplayRestrictions, Object> mRestrictions;
/**
* @hide
*/
Breadcrumb mBreadcrumb;
/**
* @hide
*/
NavigationCustomTitleView mTitle;
/**
* @hide
*/
AdapterView<?> mAdapterView;
//The layout for icons mode
private static final int RESOURCE_MODE_ICONS_LAYOUT = R.layout.navigation_view_icons;
private static final int RESOURCE_MODE_ICONS_ITEM = R.layout.navigation_view_icons_item;
//The layout for simple mode
private static final int RESOURCE_MODE_SIMPLE_LAYOUT = R.layout.navigation_view_simple;
private static final int RESOURCE_MODE_SIMPLE_ITEM = R.layout.navigation_view_simple_item;
//The layout for details mode
private static final int RESOURCE_MODE_DETAILS_LAYOUT = R.layout.navigation_view_details;
private static final int RESOURCE_MODE_DETAILS_ITEM = R.layout.navigation_view_details_item;
//The current layout identifier (is shared for all the mode layout)
private static final int RESOURCE_CURRENT_LAYOUT = R.id.navigation_view_layout;
/**
* Constructor of <code>NavigationView</code>.
*
* @param context The current context
* @param attrs The attributes of the XML tag that is inflating the view.
*/
public NavigationView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Navigable);
try {
init(a);
} finally {
a.recycle();
}
}
/**
* Constructor of <code>NavigationView</code>.
*
* @param context The current context
* @param attrs The attributes of the XML tag that is inflating the view.
* @param defStyle The default style to apply to this view. If 0, no style
* will be applied (beyond what is included in the theme). This may
* either be an attribute resource, whose value will be retrieved
* from the current theme, or an explicit style resource.
*/
public NavigationView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.Navigable, defStyle, 0);
try {
init(a);
} finally {
a.recycle();
}
}
/**
* Invoked when the instance need to be saved.
*
* @return NavigationViewInfoParcelable The serialized info
*/
public NavigationViewInfoParcelable onSaveState() {
//Return the persistent the data
NavigationViewInfoParcelable parcel = new NavigationViewInfoParcelable();
parcel.setId(this.mId);
parcel.setCurrentDir(this.mCurrentDir);
parcel.setChRooted(this.mChRooted);
parcel.setSelectedFiles(this.mAdapter.getSelectedItems());
parcel.setFiles(this.mFiles);
return parcel;
}
/**
* Invoked when the instance need to be restored.
*
* @param info The serialized info
* @return boolean If can restore
*/
public boolean onRestoreState(NavigationViewInfoParcelable info) {
synchronized (mSync) {
if (mChangingDir) {
return false;
}
}
//Restore the data
this.mId = info.getId();
this.mCurrentDir = info.getCurrentDir();
this.mChRooted = info.getChRooted();
this.mFiles = info.getFiles();
this.mAdapter.setSelectedItems(info.getSelectedFiles());
//Update the views
refresh();
return true;
}
/**
* Method that initializes the view. This method loads all the necessary
* information and create an appropriate layout for the view.
*
* @param tarray The type array
*/
private void init(TypedArray tarray) {
// Retrieve the mode
this.mNavigationMode = NAVIGATION_MODE.BROWSABLE;
int mode = tarray.getInteger(
R.styleable.Navigable_navigation,
NAVIGATION_MODE.BROWSABLE.ordinal());
if (mode >= 0 && mode < NAVIGATION_MODE.values().length) {
this.mNavigationMode = NAVIGATION_MODE.values()[mode];
}
// Initialize default restrictions (no restrictions)
this.mRestrictions = new HashMap<DisplayRestrictions, Object>();
//Initialize variables
this.mFiles = new ArrayList<FileSystemObject>();
// Is ChRooted environment?
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.PICKABLE) == 0) {
// Pick mode is always ChRooted
this.mChRooted = true;
} else {
this.mChRooted =
FileManagerApplication.getAccessMode().compareTo(AccessMode.SAFE) == 0;
}
//Retrieve the default configuration
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
SharedPreferences preferences = Preferences.getSharedPreferences();
int viewMode = preferences.getInt(
FileManagerSettings.SETTINGS_LAYOUT_MODE.getId(),
((ObjectIdentifier)FileManagerSettings.
SETTINGS_LAYOUT_MODE.getDefaultValue()).getId());
changeViewMode(NavigationLayoutMode.fromId(viewMode));
} else {
// Pick mode has always a details layout
changeViewMode(NavigationLayoutMode.DETAILS);
}
}
/**
* Method that returns the display restrictions to apply to this view.
*
* @return Map<DisplayRestrictions, Object> The restrictions to apply
*/
public Map<DisplayRestrictions, Object> getRestrictions() {
return this.mRestrictions;
}
/**
* Method that sets the display restrictions to apply to this view.
*
* @param mRestrictions The restrictions to apply
*/
public void setRestrictions(Map<DisplayRestrictions, Object> mRestrictions) {
this.mRestrictions = mRestrictions;
}
/**
* Method that returns the current file list of the navigation view.
*
* @return List<FileSystemObject> The current file list of the navigation view
*/
public List<FileSystemObject> getFiles() {
if (this.mFiles == null) {
return null;
}
return new ArrayList<FileSystemObject>(this.mFiles);
}
/**
* Method that returns the current file list of the navigation view.
*
* @return List<FileSystemObject> The current file list of the navigation view
*/
public List<FileSystemObject> getSelectedFiles() {
if (this.mAdapter != null && this.mAdapter.getSelectedItems() != null) {
return new ArrayList<FileSystemObject>(this.mAdapter.getSelectedItems());
}
return null;
}
/**
* Method that returns the custom title fragment associated with this navigation view.
*
* @return NavigationCustomTitleView The custom title view fragment
*/
public NavigationCustomTitleView getCustomTitle() {
return this.mTitle;
}
/**
* Method that associates the custom title fragment with this navigation view.
*
* @param title The custom title view fragment
*/
public void setCustomTitle(NavigationCustomTitleView title) {
this.mTitle = title;
}
/**
* Method that returns the breadcrumb associated with this navigation view.
*
* @return Breadcrumb The breadcrumb view fragment
*/
public Breadcrumb getBreadcrumb() {
return this.mBreadcrumb;
}
/**
* Method that associates the breadcrumb with this navigation view.
*
* @param breadcrumb The breadcrumb view fragment
*/
public void setBreadcrumb(Breadcrumb breadcrumb) {
this.mBreadcrumb = breadcrumb;
this.mBreadcrumb.addBreadcrumbListener(this);
}
/**
* Method that sets the listener for communicate history changes.
*
* @param onHistoryListener The listener for communicate history changes
*/
public void setOnHistoryListener(OnHistoryListener onHistoryListener) {
this.mOnHistoryListener = onHistoryListener;
}
/**
* Method that sets the listener which communicates selection changes.
*
* @param onNavigationSelectionChangedListener The listener reference
*/
public void setOnNavigationSelectionChangedListener(
OnNavigationSelectionChangedListener onNavigationSelectionChangedListener) {
this.mOnNavigationSelectionChangedListener = onNavigationSelectionChangedListener;
}
/**
* Method that sets the listener for menu item requests.
*
* @param onNavigationRequestMenuListener The listener reference
*/
public void setOnNavigationOnRequestMenuListener(
OnNavigationRequestMenuListener onNavigationRequestMenuListener) {
this.mOnNavigationRequestMenuListener = onNavigationRequestMenuListener;
}
/**
* @return the mOnFilePickedListener
*/
public OnFilePickedListener getOnFilePickedListener() {
return this.mOnFilePickedListener;
}
/**
* Method that sets the listener for picked items
*
* @param onFilePickedListener The listener reference
*/
public void setOnFilePickedListener(OnFilePickedListener onFilePickedListener) {
this.mOnFilePickedListener = onFilePickedListener;
}
/**
* Method that sets the listener for directory changes
*
* @param onDirectoryChangedListener The listener reference
*/
public void setOnDirectoryChangedListener(
OnDirectoryChangedListener onDirectoryChangedListener) {
this.mOnDirectoryChangedListener = onDirectoryChangedListener;
}
/**
* Method that sets if the view should use flinger gesture detection.
*
* @param useFlinger If the view should use flinger gesture detection
*/
public void setUseFlinger(boolean useFlinger) {
if (this.mCurrentMode.compareTo(NavigationLayoutMode.ICONS) == 0) {
// Not supported
return;
}
// Set the flinger listener (only when navigate)
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
if (this.mAdapterView instanceof FlingerListView) {
if (useFlinger) {
((FlingerListView)this.mAdapterView).
setOnItemFlingerListener(this.mOnItemFlingerListener);
} else {
((FlingerListView)this.mAdapterView).setOnItemFlingerListener(null);
}
}
}
}
/**
* Method that forces the view to scroll to the file system object passed.
*
* @param fso The file system object
*/
public void scrollTo(FileSystemObject fso) {
if (fso != null) {
try {
int position = this.mAdapter.getPosition(fso);
this.mAdapterView.setSelection(position);
} catch (Exception e) {
this.mAdapterView.setSelection(0);
}
} else {
this.mAdapterView.setSelection(0);
}
}
/**
* Method that refresh the view data.
*/
public void refresh() {
refresh(false);
}
/**
* Method that refresh the view data.
*
* @param restore Restore previous position
*/
public void refresh(boolean restore) {
FileSystemObject fso = null;
// Try to restore the previous scroll position
if (restore) {
try {
if (this.mAdapterView != null && this.mAdapter != null) {
int position = this.mAdapterView.getFirstVisiblePosition();
fso = this.mAdapter.getItem(position);
}
} catch (Throwable _throw) {/**NON BLOCK**/}
}
refresh(fso);
}
/**
* Method that refresh the view data.
*
* @param scrollTo Scroll to object
*/
public void refresh(FileSystemObject scrollTo) {
//Check that current directory was set
if (this.mCurrentDir == null || this.mFiles == null) {
return;
}
//Reload data
changeCurrentDir(this.mCurrentDir, false, true, false, null, scrollTo);
}
/**
* Method that recycles this object
*/
public void recycle() {
if (this.mAdapter != null) {
this.mAdapter.dispose();
}
}
/**
* Method that change the view mode.
*
* @param newMode The new mode
*/
@SuppressWarnings("unchecked")
public void changeViewMode(final NavigationLayoutMode newMode) {
synchronized (this.mSync) {
//Check that it is really necessary change the mode
if (this.mCurrentMode != null && this.mCurrentMode.compareTo(newMode) == 0) {
return;
}
// If we should set the listview to response to flinger gesture detection
boolean useFlinger =
Preferences.getSharedPreferences().getBoolean(
FileManagerSettings.SETTINGS_USE_FLINGER.getId(),
((Boolean)FileManagerSettings.
SETTINGS_USE_FLINGER.
getDefaultValue()).booleanValue());
//Creates the new layout
AdapterView<ListAdapter> newView = null;
int itemResourceId = -1;
if (newMode.compareTo(NavigationLayoutMode.ICONS) == 0) {
newView = (AdapterView<ListAdapter>)inflate(
getContext(), RESOURCE_MODE_ICONS_LAYOUT, null);
itemResourceId = RESOURCE_MODE_ICONS_ITEM;
} else if (newMode.compareTo(NavigationLayoutMode.SIMPLE) == 0) {
newView = (AdapterView<ListAdapter>)inflate(
getContext(), RESOURCE_MODE_SIMPLE_LAYOUT, null);
itemResourceId = RESOURCE_MODE_SIMPLE_ITEM;
// Set the flinger listener (only when navigate)
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
if (useFlinger && newView instanceof FlingerListView) {
((FlingerListView)newView).
setOnItemFlingerListener(this.mOnItemFlingerListener);
}
}
} else if (newMode.compareTo(NavigationLayoutMode.DETAILS) == 0) {
newView = (AdapterView<ListAdapter>)inflate(
getContext(), RESOURCE_MODE_DETAILS_LAYOUT, null);
itemResourceId = RESOURCE_MODE_DETAILS_ITEM;
// Set the flinger listener (only when navigate)
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
if (useFlinger && newView instanceof FlingerListView) {
((FlingerListView)newView).
setOnItemFlingerListener(this.mOnItemFlingerListener);
}
}
}
//Get the current adapter and its adapter list
List<FileSystemObject> files = new ArrayList<FileSystemObject>(this.mFiles);
final AdapterView<ListAdapter> current =
(AdapterView<ListAdapter>)findViewById(RESOURCE_CURRENT_LAYOUT);
FileSystemObjectAdapter adapter =
new FileSystemObjectAdapter(
getContext(),
new ArrayList<FileSystemObject>(),
itemResourceId,
this.mNavigationMode.compareTo(NAVIGATION_MODE.PICKABLE) == 0);
adapter.setOnSelectionChangedListener(this);
//Remove current layout
if (current != null) {
if (current.getAdapter() != null) {
//Save selected items before dispose adapter
FileSystemObjectAdapter currentAdapter =
((FileSystemObjectAdapter)current.getAdapter());
adapter.setSelectedItems(currentAdapter.getSelectedItems());
currentAdapter.dispose();
}
removeView(current);
}
this.mFiles = files;
adapter.addAll(files);
//Set the adapter
this.mAdapter = adapter;
newView.setAdapter(this.mAdapter);
newView.setOnItemClickListener(NavigationView.this);
//Add the new layout
this.mAdapterView = newView;
addView(newView, 0);
this.mCurrentMode = newMode;
// Pick mode doesn't implements the onlongclick
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
this.mAdapterView.setOnItemLongClickListener(this);
} else {
this.mAdapterView.setOnItemLongClickListener(null);
}
//Save the preference (only in navigation browse mode)
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
try {
Preferences.savePreference(
FileManagerSettings.SETTINGS_LAYOUT_MODE, newMode, true);
} catch (Exception ex) {
Log.e(TAG, "Save of view mode preference fails", ex); //$NON-NLS-1$
}
}
}
}
/**
* Method that removes a {@link FileSystemObject} from the view
*
* @param fso The file system object
*/
public void removeItem(FileSystemObject fso) {
// Delete also from internal list
if (fso != null) {
int cc = this.mFiles.size()-1;
for (int i = cc; i >= 0; i--) {
FileSystemObject f = this.mFiles.get(i);
if (f != null && f.compareTo(fso) == 0) {
this.mFiles.remove(i);
break;
}
}
}
this.mAdapter.remove(fso);
}
/**
* Method that removes a file system object from his path from the view
*
* @param path The file system object path
*/
public void removeItem(String path) {
FileSystemObject fso = this.mAdapter.getItem(path);
if (fso != null) {
this.mAdapter.remove(fso);
}
}
/**
* Method that returns the current directory.
*
* @return String The current directory
*/
public String getCurrentDir() {
return this.mCurrentDir;
}
/**
* Method that changes the current directory of the view.
*
* @param newDir The new directory location
*/
public void changeCurrentDir(final String newDir) {
changeCurrentDir(newDir, true, false, false, null, null);
}
/**
* Method that changes the current directory of the view.
*
* @param newDir The new directory location
* @param searchInfo The search information (if calling activity is {@link "SearchActivity"})
*/
public void changeCurrentDir(final String newDir, SearchInfoParcelable searchInfo) {
changeCurrentDir(newDir, true, false, false, searchInfo, null);
}
/**
* Method that changes the current directory of the view.
*
* @param newDir The new directory location
* @param addToHistory Add the directory to history
* @param reload Force the reload of the data
* @param useCurrent If this method must use the actual data (for back actions)
* @param searchInfo The search information (if calling activity is {@link "SearchActivity"})
* @param scrollTo If not null, then listview must scroll to this item
*/
private void changeCurrentDir(
final String newDir, final boolean addToHistory,
final boolean reload, final boolean useCurrent,
final SearchInfoParcelable searchInfo, final FileSystemObject scrollTo) {
// Check navigation security (don't allow to go outside the ChRooted environment if one
// is created)
final String fNewDir = checkChRootedNavigation(newDir);
// Wait to finalization
synchronized (this.mSync) {
if (mChangingDir) {
try {
mSync.wait();
} catch (InterruptedException iex) {
// Ignore
}
}
mChangingDir = true;
}
//Check that it is really necessary change the directory
if (!reload && this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0) {
+ synchronized (this.mSync) {
+ mChangingDir = false;
+ mSync.notify();
+ }
return;
}
final boolean hasChanged =
!(this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0);
final boolean isNewHistory = (this.mCurrentDir != null);
//Execute the listing in a background process
AsyncTask<String, Integer, List<FileSystemObject>> task =
new AsyncTask<String, Integer, List<FileSystemObject>>() {
/**
* {@inheritDoc}
*/
@Override
protected List<FileSystemObject> doInBackground(String... params) {
try {
//Reset the custom title view and returns to breadcrumb
if (NavigationView.this.mTitle != null) {
NavigationView.this.mTitle.post(new Runnable() {
@Override
public void run() {
try {
NavigationView.this.mTitle.restoreView();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Start of loading data
if (NavigationView.this.mBreadcrumb != null) {
try {
NavigationView.this.mBreadcrumb.startLoading();
} catch (Throwable ex) {
/**NON BLOCK**/
}
}
//Get the files, resolve links and apply configuration
//(sort, hidden, ...)
List<FileSystemObject> files = NavigationView.this.mFiles;
if (!useCurrent) {
files = CommandHelper.listFiles(getContext(), fNewDir, null);
}
return files;
} catch (final ConsoleAllocException e) {
//Show exception and exists
NavigationView.this.post(new Runnable() {
@Override
public void run() {
Context ctx = getContext();
Log.e(TAG, ctx.getString(
R.string.msgs_cant_create_console), e);
DialogHelper.showToast(ctx,
R.string.msgs_cant_create_console,
Toast.LENGTH_LONG);
((Activity)ctx).finish();
}
});
return null;
} catch (Exception ex) {
//End of loading data
if (NavigationView.this.mBreadcrumb != null) {
try {
NavigationView.this.mBreadcrumb.endLoading();
} catch (Throwable ex2) {
/**NON BLOCK**/
}
}
//Capture exception (attach task, and use listener to do the anim)
ExceptionUtil.attachAsyncTask(
ex,
new AsyncTask<Object, Integer, Boolean>() {
private List<FileSystemObject> mTaskFiles = null;
@Override
@SuppressWarnings({
"unchecked", "unqualified-field-access"
})
protected Boolean doInBackground(Object... taskParams) {
mTaskFiles = (List<FileSystemObject>)taskParams[0];
return Boolean.TRUE;
}
@Override
@SuppressWarnings("unqualified-field-access")
protected void onPostExecute(Boolean result) {
if (!result.booleanValue()) {
return;
}
onPostExecuteTask(
mTaskFiles, addToHistory,
isNewHistory, hasChanged,
searchInfo, fNewDir, scrollTo);
}
});
final OnRelaunchCommandResult exListener =
new OnRelaunchCommandResult() {
@Override
public void onSuccess() {
done();
}
@Override
public void onFailed(Throwable cause) {
done();
}
@Override
public void onCancelled() {
done();
}
private void done() {
// Do animation
fadeEfect(false);
synchronized (mSync) {
mChangingDir = false;
mSync.notify();
}
}
};
ExceptionUtil.translateException(
getContext(), ex, false, true, exListener);
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
protected void onPreExecute() {
// Do animation
fadeEfect(true);
}
/**
* {@inheritDoc}
*/
@Override
protected void onPostExecute(List<FileSystemObject> files) {
// This means an exception. This method will be recalled then
if (files != null) {
onPostExecuteTask(
files, addToHistory, isNewHistory,
hasChanged, searchInfo, fNewDir, scrollTo);
// Do animation
fadeEfect(false);
synchronized (mSync) {
mChangingDir = false;
mSync.notify();
}
}
}
/**
* Method that performs a fade animation.
*
* @param out Fade out (true); Fade in (false)
*/
void fadeEfect(final boolean out) {
Activity activity = (Activity)getContext();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Animation fadeAnim = out ?
new AlphaAnimation(1, 0) :
new AlphaAnimation(0, 1);
fadeAnim.setDuration(50L);
fadeAnim.setFillAfter(true);
fadeAnim.setInterpolator(new AccelerateInterpolator());
NavigationView.this.startAnimation(fadeAnim);
}
});
}
};
task.execute(fNewDir);
}
/**
* Method invoked when a execution ends.
*
* @param files The files obtains from the list
* @param addToHistory If add path to history
* @param isNewHistory If is new history
* @param hasChanged If current directory was changed
* @param searchInfo The search information (if calling activity is {@link "SearchActivity"})
* @param newDir The new directory
* @param scrollTo If not null, then listview must scroll to this item
* @hide
*/
void onPostExecuteTask(
List<FileSystemObject> files, boolean addToHistory, boolean isNewHistory,
boolean hasChanged, SearchInfoParcelable searchInfo,
String newDir, final FileSystemObject scrollTo) {
try {
//Check that there is not errors and have some data
if (files == null) {
return;
}
//Apply user preferences
List<FileSystemObject> sortedFiles =
FileHelper.applyUserPreferences(files, this.mRestrictions, this.mChRooted);
//Remove parent directory if we are in the root of a chrooted environment
if (this.mChRooted && StorageHelper.isStorageVolume(newDir)) {
if (files.size() > 0 && files.get(0) instanceof ParentDirectory) {
files.remove(0);
}
}
//Load the data
loadData(sortedFiles);
this.mFiles = sortedFiles;
if (searchInfo != null) {
searchInfo.setSuccessNavigation(true);
}
//Add to history?
if (addToHistory && hasChanged && isNewHistory) {
if (this.mOnHistoryListener != null) {
//Communicate the need of a history change
this.mOnHistoryListener.onNewHistory(onSaveState());
}
}
//Change the breadcrumb
if (this.mBreadcrumb != null) {
this.mBreadcrumb.changeBreadcrumbPath(newDir, this.mChRooted);
}
//Scroll to object?
if (scrollTo != null) {
scrollTo(scrollTo);
}
//The current directory is now the "newDir"
this.mCurrentDir = newDir;
if (this.mOnDirectoryChangedListener != null) {
FileSystemObject dir = FileHelper.createFileSystemObject(new File(newDir));
this.mOnDirectoryChangedListener.onDirectoryChanged(dir);
}
} finally {
//If calling activity is search, then save the search history
if (searchInfo != null) {
this.mOnHistoryListener.onNewHistory(searchInfo);
}
//End of loading data
try {
NavigationView.this.mBreadcrumb.endLoading();
} catch (Throwable ex) {
/**NON BLOCK**/
}
}
}
/**
* Method that loads the files in the adapter.
*
* @param files The files to load in the adapter
* @hide
*/
@SuppressWarnings("unchecked")
private void loadData(final List<FileSystemObject> files) {
//Notify data to adapter view
final AdapterView<ListAdapter> view =
(AdapterView<ListAdapter>)findViewById(RESOURCE_CURRENT_LAYOUT);
FileSystemObjectAdapter adapter = (FileSystemObjectAdapter)view.getAdapter();
adapter.setNotifyOnChange(false);
adapter.clear();
adapter.addAll(files);
adapter.notifyDataSetChanged();
view.setSelection(0);
}
/**
* {@inheritDoc}
*/
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// Different actions depending on user preference
// Get the adapter and the fso
FileSystemObjectAdapter adapter = ((FileSystemObjectAdapter)parent.getAdapter());
FileSystemObject fso = adapter.getItem(position);
// Parent directory hasn't actions
if (fso instanceof ParentDirectory) {
return false;
}
// Pick mode doesn't implements the onlongclick
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.PICKABLE) == 0) {
return false;
}
onRequestMenu(fso);
return true; //Always consume the event
}
/**
* Method that opens or navigates to the {@link FileSystemObject}
*
* @param fso The file system object
*/
public void open(FileSystemObject fso) {
open(fso, null);
}
/**
* Method that opens or navigates to the {@link FileSystemObject}
*
* @param fso The file system object
* @param searchInfo The search info
*/
public void open(FileSystemObject fso, SearchInfoParcelable searchInfo) {
// If is a folder, then navigate to
if (FileHelper.isDirectory(fso)) {
changeCurrentDir(fso.getFullPath(), searchInfo);
} else {
// Open the file with the preferred registered app
IntentsActionPolicy.openFileSystemObject(getContext(), fso, false, null, null);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
FileSystemObject fso = ((FileSystemObjectAdapter)parent.getAdapter()).getItem(position);
if (fso instanceof ParentDirectory) {
changeCurrentDir(fso.getParent(), true, false, false, null, null);
return;
} else if (fso instanceof Directory) {
changeCurrentDir(fso.getFullPath(), true, false, false, null, null);
return;
} else if (fso instanceof Symlink) {
Symlink symlink = (Symlink)fso;
if (symlink.getLinkRef() != null && symlink.getLinkRef() instanceof Directory) {
changeCurrentDir(
symlink.getLinkRef().getFullPath(), true, false, false, null, null);
return;
}
// Open the link ref
fso = symlink.getLinkRef();
}
// Open the file (edit or pick)
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
// Open the file with the preferred registered app
IntentsActionPolicy.openFileSystemObject(getContext(), fso, false, null, null);
} else {
// Request a file pick selection
if (this.mOnFilePickedListener != null) {
this.mOnFilePickedListener.onFilePicked(fso);
}
}
} catch (Throwable ex) {
ExceptionUtil.translateException(getContext(), ex);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onRequestRefresh(Object o, boolean clearSelection) {
if (o instanceof FileSystemObject) {
refresh((FileSystemObject)o);
} else if (o == null) {
refresh();
}
if (clearSelection) {
onDeselectAll();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onRequestRemove(Object o, boolean clearSelection) {
if (o != null && o instanceof FileSystemObject) {
removeItem((FileSystemObject)o);
} else {
onRequestRefresh(null, clearSelection);
}
if (clearSelection) {
onDeselectAll();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onNavigateTo(Object o) {
// Ignored
}
/**
* {@inheritDoc}
*/
@Override
public void onBreadcrumbItemClick(BreadcrumbItem item) {
changeCurrentDir(item.getItemPath(), true, true, false, null, null);
}
/**
* {@inheritDoc}
*/
@Override
public void onSelectionChanged(final List<FileSystemObject> selectedItems) {
if (this.mOnNavigationSelectionChangedListener != null) {
this.mOnNavigationSelectionChangedListener.onSelectionChanged(this, selectedItems);
}
}
/**
* Method invoked when a request to show the menu associated
* with an item is started.
*
* @param item The item for which the request was started
*/
public void onRequestMenu(final FileSystemObject item) {
if (this.mOnNavigationRequestMenuListener != null) {
this.mOnNavigationRequestMenuListener.onRequestMenu(this, item);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onToggleSelection(FileSystemObject fso) {
if (this.mAdapter != null) {
this.mAdapter.toggleSelection(fso);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onDeselectAll() {
if (this.mAdapter != null) {
this.mAdapter.deselectedAll();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onSelectAllVisibleItems() {
if (this.mAdapter != null) {
this.mAdapter.selectedAllVisibleItems();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onDeselectAllVisibleItems() {
if (this.mAdapter != null) {
this.mAdapter.deselectedAllVisibleItems();
}
}
/**
* {@inheritDoc}
*/
@Override
public List<FileSystemObject> onRequestSelectedFiles() {
return this.getSelectedFiles();
}
/**
* {@inheritDoc}
*/
@Override
public List<FileSystemObject> onRequestCurrentItems() {
return this.getFiles();
}
/**
* {@inheritDoc}
*/
@Override
public String onRequestCurrentDir() {
return this.mCurrentDir;
}
/**
* Method that creates a ChRooted environment, protecting the user to break anything
* in the device
* @hide
*/
public void createChRooted() {
// If we are in a ChRooted environment, then do nothing
if (this.mChRooted) return;
this.mChRooted = true;
//Change to first storage volume
StorageVolume[] volumes =
StorageHelper.getStorageVolumes(getContext());
if (volumes != null && volumes.length > 0) {
changeCurrentDir(volumes[0].getPath(), false, true, false, null, null);
}
}
/**
* Method that exits from a ChRooted environment
* @hide
*/
public void exitChRooted() {
// If we aren't in a ChRooted environment, then do nothing
if (!this.mChRooted) return;
this.mChRooted = false;
// Refresh
refresh();
}
/**
* Method that ensures that the user don't go outside the ChRooted environment
*
* @param newDir The new directory to navigate to
* @return String
*/
private String checkChRootedNavigation(String newDir) {
// If we aren't in ChRooted environment, then there is nothing to check
if (!this.mChRooted) return newDir;
// Check if the path is owned by one of the storage volumes
if (!StorageHelper.isPathInStorageVolume(newDir)) {
StorageVolume[] volumes = StorageHelper.getStorageVolumes(getContext());
if (volumes != null && volumes.length > 0) {
return volumes[0].getPath();
}
}
return newDir;
}
/**
* Method that applies the current theme to the activity
*/
public void applyTheme() {
//- Breadcrumb
if (getBreadcrumb() != null) {
getBreadcrumb().applyTheme();
}
//- Redraw the adapter view
Theme theme = ThemeManager.getCurrentTheme(getContext());
theme.setBackgroundDrawable(getContext(), this, "background_drawable"); //$NON-NLS-1$
if (this.mAdapter != null) {
this.mAdapter.notifyThemeChanged();
}
if (this.mAdapterView instanceof ListView) {
((ListView)this.mAdapterView).setDivider(
theme.getDrawable(getContext(), "horizontal_divider_drawable")); //$NON-NLS-1$
}
refresh();
}
}
| true | true | private void changeCurrentDir(
final String newDir, final boolean addToHistory,
final boolean reload, final boolean useCurrent,
final SearchInfoParcelable searchInfo, final FileSystemObject scrollTo) {
// Check navigation security (don't allow to go outside the ChRooted environment if one
// is created)
final String fNewDir = checkChRootedNavigation(newDir);
// Wait to finalization
synchronized (this.mSync) {
if (mChangingDir) {
try {
mSync.wait();
} catch (InterruptedException iex) {
// Ignore
}
}
mChangingDir = true;
}
//Check that it is really necessary change the directory
if (!reload && this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0) {
return;
}
final boolean hasChanged =
!(this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0);
final boolean isNewHistory = (this.mCurrentDir != null);
//Execute the listing in a background process
AsyncTask<String, Integer, List<FileSystemObject>> task =
new AsyncTask<String, Integer, List<FileSystemObject>>() {
/**
* {@inheritDoc}
*/
@Override
protected List<FileSystemObject> doInBackground(String... params) {
try {
//Reset the custom title view and returns to breadcrumb
if (NavigationView.this.mTitle != null) {
NavigationView.this.mTitle.post(new Runnable() {
@Override
public void run() {
try {
NavigationView.this.mTitle.restoreView();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Start of loading data
if (NavigationView.this.mBreadcrumb != null) {
try {
NavigationView.this.mBreadcrumb.startLoading();
} catch (Throwable ex) {
/**NON BLOCK**/
}
}
//Get the files, resolve links and apply configuration
//(sort, hidden, ...)
List<FileSystemObject> files = NavigationView.this.mFiles;
if (!useCurrent) {
files = CommandHelper.listFiles(getContext(), fNewDir, null);
}
return files;
} catch (final ConsoleAllocException e) {
//Show exception and exists
NavigationView.this.post(new Runnable() {
@Override
public void run() {
Context ctx = getContext();
Log.e(TAG, ctx.getString(
R.string.msgs_cant_create_console), e);
DialogHelper.showToast(ctx,
R.string.msgs_cant_create_console,
Toast.LENGTH_LONG);
((Activity)ctx).finish();
}
});
return null;
} catch (Exception ex) {
//End of loading data
if (NavigationView.this.mBreadcrumb != null) {
try {
NavigationView.this.mBreadcrumb.endLoading();
} catch (Throwable ex2) {
/**NON BLOCK**/
}
}
//Capture exception (attach task, and use listener to do the anim)
ExceptionUtil.attachAsyncTask(
ex,
new AsyncTask<Object, Integer, Boolean>() {
private List<FileSystemObject> mTaskFiles = null;
@Override
@SuppressWarnings({
"unchecked", "unqualified-field-access"
})
protected Boolean doInBackground(Object... taskParams) {
mTaskFiles = (List<FileSystemObject>)taskParams[0];
return Boolean.TRUE;
}
@Override
@SuppressWarnings("unqualified-field-access")
protected void onPostExecute(Boolean result) {
if (!result.booleanValue()) {
return;
}
onPostExecuteTask(
mTaskFiles, addToHistory,
isNewHistory, hasChanged,
searchInfo, fNewDir, scrollTo);
}
});
final OnRelaunchCommandResult exListener =
new OnRelaunchCommandResult() {
@Override
public void onSuccess() {
done();
}
@Override
public void onFailed(Throwable cause) {
done();
}
@Override
public void onCancelled() {
done();
}
private void done() {
// Do animation
fadeEfect(false);
synchronized (mSync) {
mChangingDir = false;
mSync.notify();
}
}
};
ExceptionUtil.translateException(
getContext(), ex, false, true, exListener);
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
protected void onPreExecute() {
// Do animation
fadeEfect(true);
}
/**
* {@inheritDoc}
*/
@Override
protected void onPostExecute(List<FileSystemObject> files) {
// This means an exception. This method will be recalled then
if (files != null) {
onPostExecuteTask(
files, addToHistory, isNewHistory,
hasChanged, searchInfo, fNewDir, scrollTo);
// Do animation
fadeEfect(false);
synchronized (mSync) {
mChangingDir = false;
mSync.notify();
}
}
}
/**
* Method that performs a fade animation.
*
* @param out Fade out (true); Fade in (false)
*/
void fadeEfect(final boolean out) {
Activity activity = (Activity)getContext();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Animation fadeAnim = out ?
new AlphaAnimation(1, 0) :
new AlphaAnimation(0, 1);
fadeAnim.setDuration(50L);
fadeAnim.setFillAfter(true);
fadeAnim.setInterpolator(new AccelerateInterpolator());
NavigationView.this.startAnimation(fadeAnim);
}
});
}
};
task.execute(fNewDir);
}
| private void changeCurrentDir(
final String newDir, final boolean addToHistory,
final boolean reload, final boolean useCurrent,
final SearchInfoParcelable searchInfo, final FileSystemObject scrollTo) {
// Check navigation security (don't allow to go outside the ChRooted environment if one
// is created)
final String fNewDir = checkChRootedNavigation(newDir);
// Wait to finalization
synchronized (this.mSync) {
if (mChangingDir) {
try {
mSync.wait();
} catch (InterruptedException iex) {
// Ignore
}
}
mChangingDir = true;
}
//Check that it is really necessary change the directory
if (!reload && this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0) {
synchronized (this.mSync) {
mChangingDir = false;
mSync.notify();
}
return;
}
final boolean hasChanged =
!(this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0);
final boolean isNewHistory = (this.mCurrentDir != null);
//Execute the listing in a background process
AsyncTask<String, Integer, List<FileSystemObject>> task =
new AsyncTask<String, Integer, List<FileSystemObject>>() {
/**
* {@inheritDoc}
*/
@Override
protected List<FileSystemObject> doInBackground(String... params) {
try {
//Reset the custom title view and returns to breadcrumb
if (NavigationView.this.mTitle != null) {
NavigationView.this.mTitle.post(new Runnable() {
@Override
public void run() {
try {
NavigationView.this.mTitle.restoreView();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Start of loading data
if (NavigationView.this.mBreadcrumb != null) {
try {
NavigationView.this.mBreadcrumb.startLoading();
} catch (Throwable ex) {
/**NON BLOCK**/
}
}
//Get the files, resolve links and apply configuration
//(sort, hidden, ...)
List<FileSystemObject> files = NavigationView.this.mFiles;
if (!useCurrent) {
files = CommandHelper.listFiles(getContext(), fNewDir, null);
}
return files;
} catch (final ConsoleAllocException e) {
//Show exception and exists
NavigationView.this.post(new Runnable() {
@Override
public void run() {
Context ctx = getContext();
Log.e(TAG, ctx.getString(
R.string.msgs_cant_create_console), e);
DialogHelper.showToast(ctx,
R.string.msgs_cant_create_console,
Toast.LENGTH_LONG);
((Activity)ctx).finish();
}
});
return null;
} catch (Exception ex) {
//End of loading data
if (NavigationView.this.mBreadcrumb != null) {
try {
NavigationView.this.mBreadcrumb.endLoading();
} catch (Throwable ex2) {
/**NON BLOCK**/
}
}
//Capture exception (attach task, and use listener to do the anim)
ExceptionUtil.attachAsyncTask(
ex,
new AsyncTask<Object, Integer, Boolean>() {
private List<FileSystemObject> mTaskFiles = null;
@Override
@SuppressWarnings({
"unchecked", "unqualified-field-access"
})
protected Boolean doInBackground(Object... taskParams) {
mTaskFiles = (List<FileSystemObject>)taskParams[0];
return Boolean.TRUE;
}
@Override
@SuppressWarnings("unqualified-field-access")
protected void onPostExecute(Boolean result) {
if (!result.booleanValue()) {
return;
}
onPostExecuteTask(
mTaskFiles, addToHistory,
isNewHistory, hasChanged,
searchInfo, fNewDir, scrollTo);
}
});
final OnRelaunchCommandResult exListener =
new OnRelaunchCommandResult() {
@Override
public void onSuccess() {
done();
}
@Override
public void onFailed(Throwable cause) {
done();
}
@Override
public void onCancelled() {
done();
}
private void done() {
// Do animation
fadeEfect(false);
synchronized (mSync) {
mChangingDir = false;
mSync.notify();
}
}
};
ExceptionUtil.translateException(
getContext(), ex, false, true, exListener);
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
protected void onPreExecute() {
// Do animation
fadeEfect(true);
}
/**
* {@inheritDoc}
*/
@Override
protected void onPostExecute(List<FileSystemObject> files) {
// This means an exception. This method will be recalled then
if (files != null) {
onPostExecuteTask(
files, addToHistory, isNewHistory,
hasChanged, searchInfo, fNewDir, scrollTo);
// Do animation
fadeEfect(false);
synchronized (mSync) {
mChangingDir = false;
mSync.notify();
}
}
}
/**
* Method that performs a fade animation.
*
* @param out Fade out (true); Fade in (false)
*/
void fadeEfect(final boolean out) {
Activity activity = (Activity)getContext();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Animation fadeAnim = out ?
new AlphaAnimation(1, 0) :
new AlphaAnimation(0, 1);
fadeAnim.setDuration(50L);
fadeAnim.setFillAfter(true);
fadeAnim.setInterpolator(new AccelerateInterpolator());
NavigationView.this.startAnimation(fadeAnim);
}
});
}
};
task.execute(fNewDir);
}
|
diff --git a/src/jrds/factories/ProbeFactory.java b/src/jrds/factories/ProbeFactory.java
index c3dcc369..539e24f2 100644
--- a/src/jrds/factories/ProbeFactory.java
+++ b/src/jrds/factories/ProbeFactory.java
@@ -1,180 +1,185 @@
/*##########################################################################
_##
_## $Id$
_##
_##########################################################################*/
package jrds.factories;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import jrds.Probe;
import jrds.ProbeDesc;
import jrds.PropertiesManager;
import org.apache.log4j.Logger;
/**
* A class to find probe by their names
* @author Fabrice Bacchella
* @version $Revision$, $Date$
*/
public class ProbeFactory {
private final Logger logger = Logger.getLogger(ProbeFactory.class);
final private List<String> probePackages = new ArrayList<String>(5);
private Map<String, ProbeDesc> probeDescMap;
private GraphFactory gf;
private PropertiesManager pm;
/**
* Private constructor
* @param b
*/
public ProbeFactory(Map<String, ProbeDesc> probeDescMap, GraphFactory gf, PropertiesManager pm) {
this.probeDescMap = probeDescMap;
this.gf = gf;
this.pm = pm;
probePackages.add("");
}
/**
* Create an probe, provided his Class and a list of argument for a constructor
* for this object. It will be found using the default list of possible package
* @param className the probe name
* @param constArgs
* @return
*/
public Probe makeProbe(String className, List<?> constArgs) {
Probe retValue = null;
ProbeDesc pd = (ProbeDesc) probeDescMap.get(className);
if( pd != null) {
retValue = makeProbe(pd, constArgs);
}
else if(pm.legacymode ){
Class<?> probeClass = resolvClass(className, probePackages);
if (probeClass != null) {
Object o = null;
try {
Class<?>[] constArgsType = new Class[constArgs.size()];
Object[] constArgsVal = new Object[constArgs.size()];
int index = 0;
for (Object arg: constArgs) {
constArgsType[index] = arg.getClass();
constArgsVal[index] = arg;
index++;
}
Constructor<?> theConst = probeClass.getConstructor(constArgsType);
o = theConst.newInstance(constArgsVal);
retValue = (Probe) o;
}
catch (ClassCastException ex) {
logger.warn("didn't get a Probe but a " + o.getClass().getName());
}
catch (Exception ex) {
logger.warn("Error during probe creation of type " + className +
": " + ex, ex);
}
}
}
else {
logger.error("Probe named " + className + " not found");
}
//Now we finish the initialization of classes
if(retValue != null) {
retValue.initGraphList(gf);
}
return retValue;
}
/**
* Instanciate a probe using a probedesc
* @param constArgs
* @return
*/
public Probe makeProbe(ProbeDesc pd, List<?> constArgs) {
Class<? extends Probe> probeClass = pd.getProbeClass();
List<?> defaultsArgs = pd.getDefaultArgs();
Probe retValue = null;
if (probeClass != null) {
Object o = null;
try {
if(defaultsArgs != null && constArgs != null && constArgs.size() <= 0)
constArgs = defaultsArgs;
Class<?>[] constArgsType = new Class[constArgs.size()];
Object[] constArgsVal = new Object[constArgs.size()];
int index = 0;
for (Object arg: constArgs) {
constArgsType[index] = arg.getClass();
if(arg instanceof List) {
constArgsType[index] = List.class;
}
constArgsVal[index] = arg;
index++;
}
Constructor<? extends Probe> theConst = probeClass.getConstructor(constArgsType);
o = theConst.newInstance(constArgsVal);
retValue = (Probe) o;
retValue.setPd(pd);
}
catch (ClassCastException ex) {
logger.warn("didn't get a Probe but a " + o.getClass().getName());
+ return null;
}
catch (NoClassDefFoundError ex) {
logger.warn("Missing class for the creation of a probe " + pd.getName());
+ return null;
}
catch(InstantiationException ex) {
if(ex.getCause() != null)
logger.warn("Instantation exception : " + ex.getCause().getMessage(),
ex.getCause());
else {
logger.warn("Instantation exception : " + ex,
ex);
}
+ return null;
}
catch (NoSuchMethodException ex) {
logger.warn("ProbeDescription invalid " + pd.getName() + ": no constructor " + ex.getMessage() + " found");
+ return null;
}
catch (Exception ex) {
Throwable showException = ex;
Throwable t = ex.getCause();
if(t != null)
showException = t;
logger.warn("Error during probe creation of type " + pd.getName() + " with args " + constArgs +
": ", showException);
+ return null;
}
}
if(pm != null) {
logger.trace("Setting time step to " + pm.step + " for " + retValue);
retValue.setStep(pm.step);
}
return retValue;
}
private Class<?> resolvClass(String name, List<String> listPackages) {
Class<?> retValue = null;
for (String packageTry: listPackages) {
try {
retValue = Class.forName(packageTry + name);
}
catch (ClassNotFoundException ex) {
}
catch (NoClassDefFoundError ex) {
}
}
if (retValue == null)
logger.warn("Class " + name + " not found");
return retValue;
}
public ProbeDesc getProbeDesc(String name) {
return probeDescMap.get(name);
}
}
| false | true | public Probe makeProbe(ProbeDesc pd, List<?> constArgs) {
Class<? extends Probe> probeClass = pd.getProbeClass();
List<?> defaultsArgs = pd.getDefaultArgs();
Probe retValue = null;
if (probeClass != null) {
Object o = null;
try {
if(defaultsArgs != null && constArgs != null && constArgs.size() <= 0)
constArgs = defaultsArgs;
Class<?>[] constArgsType = new Class[constArgs.size()];
Object[] constArgsVal = new Object[constArgs.size()];
int index = 0;
for (Object arg: constArgs) {
constArgsType[index] = arg.getClass();
if(arg instanceof List) {
constArgsType[index] = List.class;
}
constArgsVal[index] = arg;
index++;
}
Constructor<? extends Probe> theConst = probeClass.getConstructor(constArgsType);
o = theConst.newInstance(constArgsVal);
retValue = (Probe) o;
retValue.setPd(pd);
}
catch (ClassCastException ex) {
logger.warn("didn't get a Probe but a " + o.getClass().getName());
}
catch (NoClassDefFoundError ex) {
logger.warn("Missing class for the creation of a probe " + pd.getName());
}
catch(InstantiationException ex) {
if(ex.getCause() != null)
logger.warn("Instantation exception : " + ex.getCause().getMessage(),
ex.getCause());
else {
logger.warn("Instantation exception : " + ex,
ex);
}
}
catch (NoSuchMethodException ex) {
logger.warn("ProbeDescription invalid " + pd.getName() + ": no constructor " + ex.getMessage() + " found");
}
catch (Exception ex) {
Throwable showException = ex;
Throwable t = ex.getCause();
if(t != null)
showException = t;
logger.warn("Error during probe creation of type " + pd.getName() + " with args " + constArgs +
": ", showException);
}
}
if(pm != null) {
logger.trace("Setting time step to " + pm.step + " for " + retValue);
retValue.setStep(pm.step);
}
return retValue;
}
| public Probe makeProbe(ProbeDesc pd, List<?> constArgs) {
Class<? extends Probe> probeClass = pd.getProbeClass();
List<?> defaultsArgs = pd.getDefaultArgs();
Probe retValue = null;
if (probeClass != null) {
Object o = null;
try {
if(defaultsArgs != null && constArgs != null && constArgs.size() <= 0)
constArgs = defaultsArgs;
Class<?>[] constArgsType = new Class[constArgs.size()];
Object[] constArgsVal = new Object[constArgs.size()];
int index = 0;
for (Object arg: constArgs) {
constArgsType[index] = arg.getClass();
if(arg instanceof List) {
constArgsType[index] = List.class;
}
constArgsVal[index] = arg;
index++;
}
Constructor<? extends Probe> theConst = probeClass.getConstructor(constArgsType);
o = theConst.newInstance(constArgsVal);
retValue = (Probe) o;
retValue.setPd(pd);
}
catch (ClassCastException ex) {
logger.warn("didn't get a Probe but a " + o.getClass().getName());
return null;
}
catch (NoClassDefFoundError ex) {
logger.warn("Missing class for the creation of a probe " + pd.getName());
return null;
}
catch(InstantiationException ex) {
if(ex.getCause() != null)
logger.warn("Instantation exception : " + ex.getCause().getMessage(),
ex.getCause());
else {
logger.warn("Instantation exception : " + ex,
ex);
}
return null;
}
catch (NoSuchMethodException ex) {
logger.warn("ProbeDescription invalid " + pd.getName() + ": no constructor " + ex.getMessage() + " found");
return null;
}
catch (Exception ex) {
Throwable showException = ex;
Throwable t = ex.getCause();
if(t != null)
showException = t;
logger.warn("Error during probe creation of type " + pd.getName() + " with args " + constArgs +
": ", showException);
return null;
}
}
if(pm != null) {
logger.trace("Setting time step to " + pm.step + " for " + retValue);
retValue.setStep(pm.step);
}
return retValue;
}
|
diff --git a/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java b/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java
index 29c475638..2a77d06f6 100644
--- a/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java
+++ b/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java
@@ -1,63 +1,63 @@
package org.drools.analytics;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.drools.StatelessSession;
import org.drools.analytics.components.AnalyticsRule;
import org.drools.analytics.dao.AnalyticsDataFactory;
import org.drools.analytics.dao.AnalyticsResult;
import org.drools.analytics.report.components.AnalyticsMessage;
import org.drools.analytics.report.components.AnalyticsMessageBase;
import org.drools.base.RuleNameMatchesAgendaFilter;
/**
*
* @author Toni Rikkola
*
*/
public class ConsequenceTest extends TestBase {
public void testMissingConsequence() throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Consequence.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"No action - possibly commented out"));
- AnalyticsDataFactory.getAnalyticsData();
+ AnalyticsDataFactory.clearAnalyticsData();
Collection<? extends Object> testData = getTestData(this.getClass()
.getResourceAsStream("ConsequenceTest.drl"));
AnalyticsDataFactory.clearAnalyticsResult();
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(testData);
Iterator<AnalyticsMessageBase> iter = result.getBySeverity(
AnalyticsMessageBase.Severity.WARNING).iterator();
Set<String> rulesThatHadErrors = new HashSet<String>();
while (iter.hasNext()) {
Object o = (Object) iter.next();
if (o instanceof AnalyticsMessage) {
AnalyticsRule rule = (AnalyticsRule) ((AnalyticsMessage) o)
.getFaulty();
rulesThatHadErrors.add(rule.getRuleName());
}
}
assertFalse(rulesThatHadErrors.contains("Has a consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 2"));
if (!rulesThatHadErrors.isEmpty()) {
for (String string : rulesThatHadErrors) {
fail("Rule " + string + " caused an error.");
}
}
}
}
| true | true | public void testMissingConsequence() throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Consequence.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"No action - possibly commented out"));
AnalyticsDataFactory.getAnalyticsData();
Collection<? extends Object> testData = getTestData(this.getClass()
.getResourceAsStream("ConsequenceTest.drl"));
AnalyticsDataFactory.clearAnalyticsResult();
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(testData);
Iterator<AnalyticsMessageBase> iter = result.getBySeverity(
AnalyticsMessageBase.Severity.WARNING).iterator();
Set<String> rulesThatHadErrors = new HashSet<String>();
while (iter.hasNext()) {
Object o = (Object) iter.next();
if (o instanceof AnalyticsMessage) {
AnalyticsRule rule = (AnalyticsRule) ((AnalyticsMessage) o)
.getFaulty();
rulesThatHadErrors.add(rule.getRuleName());
}
}
assertFalse(rulesThatHadErrors.contains("Has a consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 2"));
if (!rulesThatHadErrors.isEmpty()) {
for (String string : rulesThatHadErrors) {
fail("Rule " + string + " caused an error.");
}
}
}
| public void testMissingConsequence() throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Consequence.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"No action - possibly commented out"));
AnalyticsDataFactory.clearAnalyticsData();
Collection<? extends Object> testData = getTestData(this.getClass()
.getResourceAsStream("ConsequenceTest.drl"));
AnalyticsDataFactory.clearAnalyticsResult();
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(testData);
Iterator<AnalyticsMessageBase> iter = result.getBySeverity(
AnalyticsMessageBase.Severity.WARNING).iterator();
Set<String> rulesThatHadErrors = new HashSet<String>();
while (iter.hasNext()) {
Object o = (Object) iter.next();
if (o instanceof AnalyticsMessage) {
AnalyticsRule rule = (AnalyticsRule) ((AnalyticsMessage) o)
.getFaulty();
rulesThatHadErrors.add(rule.getRuleName());
}
}
assertFalse(rulesThatHadErrors.contains("Has a consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 2"));
if (!rulesThatHadErrors.isEmpty()) {
for (String string : rulesThatHadErrors) {
fail("Rule " + string + " caused an error.");
}
}
}
|
diff --git a/src/web/org/openmrs/web/controller/RegimenPortletController.java b/src/web/org/openmrs/web/controller/RegimenPortletController.java
index 6d77b647..9483859a 100644
--- a/src/web/org/openmrs/web/controller/RegimenPortletController.java
+++ b/src/web/org/openmrs/web/controller/RegimenPortletController.java
@@ -1,99 +1,102 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.controller;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.openmrs.Concept;
import org.openmrs.DrugOrder;
import org.openmrs.api.context.Context;
public class RegimenPortletController extends PortletController {
@SuppressWarnings("unchecked")
protected void populateModel(HttpServletRequest request, Map<String, Object> model) {
String drugSetIds = (String) model.get("displayDrugSetIds");
String cachedDrugSetIds = (String) model.get("cachedDrugSetIds");
if (cachedDrugSetIds == null || !cachedDrugSetIds.equals(drugSetIds)) {
if (drugSetIds != null && drugSetIds.length() > 0) {
Map<String, List<DrugOrder>> patientDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, List<DrugOrder>> currentDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, List<DrugOrder>> completedDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, Collection<Concept>> drugConceptsBySetId = new LinkedHashMap<String, Collection<Concept>>();
boolean includeOther = false;
{
for (String setId : drugSetIds.split(",")) {
if ("*".equals(setId)) {
includeOther = true;
continue;
}
Concept drugSet = Context.getConceptService().getConcept(setId);
Collection<Concept> members = new ArrayList<Concept>();
if (drugSet != null)
members = Context.getConceptService().getConceptsByConceptSet(drugSet);
drugConceptsBySetId.put(setId, members);
}
}
- for (DrugOrder order : ((List<DrugOrder>) model.get("patientDrugOrders"))) {
- String setIdToUse = null;
- if (order.getDrug() != null) {
- Concept orderConcept = order.getDrug().getConcept();
- for (Map.Entry<String, Collection<Concept>> e : drugConceptsBySetId.entrySet()) {
- if (e.getValue().contains(orderConcept)) {
- setIdToUse = e.getKey();
- break;
+ List<DrugOrder> patientDrugOrders = (List<DrugOrder>) model.get("patientDrugOrders");
+ if (patientDrugOrders != null) {
+ for (DrugOrder order : patientDrugOrders) {
+ String setIdToUse = null;
+ if (order.getDrug() != null) {
+ Concept orderConcept = order.getDrug().getConcept();
+ for (Map.Entry<String, Collection<Concept>> e : drugConceptsBySetId.entrySet()) {
+ if (e.getValue().contains(orderConcept)) {
+ setIdToUse = e.getKey();
+ break;
+ }
}
}
- }
- if (setIdToUse == null && includeOther)
- setIdToUse = "*";
- if (setIdToUse != null) {
- helper(patientDrugOrderSets, setIdToUse, order);
- if (order.isCurrent() || order.isFuture())
- helper(currentDrugOrderSets, setIdToUse, order);
- else
- helper(completedDrugOrderSets, setIdToUse, order);
+ if (setIdToUse == null && includeOther)
+ setIdToUse = "*";
+ if (setIdToUse != null) {
+ helper(patientDrugOrderSets, setIdToUse, order);
+ if (order.isCurrent() || order.isFuture())
+ helper(currentDrugOrderSets, setIdToUse, order);
+ else
+ helper(completedDrugOrderSets, setIdToUse, order);
+ }
}
}
model.put("patientDrugOrderSets", patientDrugOrderSets);
model.put("currentDrugOrderSets", currentDrugOrderSets);
model.put("completedDrugOrderSets", completedDrugOrderSets);
model.put("cachedDrugSetIds", drugSetIds);
} // else do nothing - we already have orders in the model
}
}
/**
* Null-safe version of "drugOrderSets.get(setIdToUse).add(order)"
*/
private void helper(Map<String, List<DrugOrder>> drugOrderSets, String setIdToUse, DrugOrder order) {
List<DrugOrder> list = drugOrderSets.get(setIdToUse);
if (list == null) {
list = new ArrayList<DrugOrder>();
drugOrderSets.put(setIdToUse, list);
}
list.add(order);
}
}
| false | true | protected void populateModel(HttpServletRequest request, Map<String, Object> model) {
String drugSetIds = (String) model.get("displayDrugSetIds");
String cachedDrugSetIds = (String) model.get("cachedDrugSetIds");
if (cachedDrugSetIds == null || !cachedDrugSetIds.equals(drugSetIds)) {
if (drugSetIds != null && drugSetIds.length() > 0) {
Map<String, List<DrugOrder>> patientDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, List<DrugOrder>> currentDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, List<DrugOrder>> completedDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, Collection<Concept>> drugConceptsBySetId = new LinkedHashMap<String, Collection<Concept>>();
boolean includeOther = false;
{
for (String setId : drugSetIds.split(",")) {
if ("*".equals(setId)) {
includeOther = true;
continue;
}
Concept drugSet = Context.getConceptService().getConcept(setId);
Collection<Concept> members = new ArrayList<Concept>();
if (drugSet != null)
members = Context.getConceptService().getConceptsByConceptSet(drugSet);
drugConceptsBySetId.put(setId, members);
}
}
for (DrugOrder order : ((List<DrugOrder>) model.get("patientDrugOrders"))) {
String setIdToUse = null;
if (order.getDrug() != null) {
Concept orderConcept = order.getDrug().getConcept();
for (Map.Entry<String, Collection<Concept>> e : drugConceptsBySetId.entrySet()) {
if (e.getValue().contains(orderConcept)) {
setIdToUse = e.getKey();
break;
}
}
}
if (setIdToUse == null && includeOther)
setIdToUse = "*";
if (setIdToUse != null) {
helper(patientDrugOrderSets, setIdToUse, order);
if (order.isCurrent() || order.isFuture())
helper(currentDrugOrderSets, setIdToUse, order);
else
helper(completedDrugOrderSets, setIdToUse, order);
}
}
model.put("patientDrugOrderSets", patientDrugOrderSets);
model.put("currentDrugOrderSets", currentDrugOrderSets);
model.put("completedDrugOrderSets", completedDrugOrderSets);
model.put("cachedDrugSetIds", drugSetIds);
} // else do nothing - we already have orders in the model
}
}
| protected void populateModel(HttpServletRequest request, Map<String, Object> model) {
String drugSetIds = (String) model.get("displayDrugSetIds");
String cachedDrugSetIds = (String) model.get("cachedDrugSetIds");
if (cachedDrugSetIds == null || !cachedDrugSetIds.equals(drugSetIds)) {
if (drugSetIds != null && drugSetIds.length() > 0) {
Map<String, List<DrugOrder>> patientDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, List<DrugOrder>> currentDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, List<DrugOrder>> completedDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, Collection<Concept>> drugConceptsBySetId = new LinkedHashMap<String, Collection<Concept>>();
boolean includeOther = false;
{
for (String setId : drugSetIds.split(",")) {
if ("*".equals(setId)) {
includeOther = true;
continue;
}
Concept drugSet = Context.getConceptService().getConcept(setId);
Collection<Concept> members = new ArrayList<Concept>();
if (drugSet != null)
members = Context.getConceptService().getConceptsByConceptSet(drugSet);
drugConceptsBySetId.put(setId, members);
}
}
List<DrugOrder> patientDrugOrders = (List<DrugOrder>) model.get("patientDrugOrders");
if (patientDrugOrders != null) {
for (DrugOrder order : patientDrugOrders) {
String setIdToUse = null;
if (order.getDrug() != null) {
Concept orderConcept = order.getDrug().getConcept();
for (Map.Entry<String, Collection<Concept>> e : drugConceptsBySetId.entrySet()) {
if (e.getValue().contains(orderConcept)) {
setIdToUse = e.getKey();
break;
}
}
}
if (setIdToUse == null && includeOther)
setIdToUse = "*";
if (setIdToUse != null) {
helper(patientDrugOrderSets, setIdToUse, order);
if (order.isCurrent() || order.isFuture())
helper(currentDrugOrderSets, setIdToUse, order);
else
helper(completedDrugOrderSets, setIdToUse, order);
}
}
}
model.put("patientDrugOrderSets", patientDrugOrderSets);
model.put("currentDrugOrderSets", currentDrugOrderSets);
model.put("completedDrugOrderSets", completedDrugOrderSets);
model.put("cachedDrugSetIds", drugSetIds);
} // else do nothing - we already have orders in the model
}
}
|
diff --git a/connectors/sipgate/src/de/ub0r/android/websms/connector/sipgate/ConnectorSipgate.java b/connectors/sipgate/src/de/ub0r/android/websms/connector/sipgate/ConnectorSipgate.java
index 1662aaa1..faebb4bb 100644
--- a/connectors/sipgate/src/de/ub0r/android/websms/connector/sipgate/ConnectorSipgate.java
+++ b/connectors/sipgate/src/de/ub0r/android/websms/connector/sipgate/ConnectorSipgate.java
@@ -1,224 +1,226 @@
/*
* Copyright (C) 2010 Mirko Weber, Felix Bechstein
*
* This file is part of WebSMS.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; If not, see <http://www.gnu.org/licenses/>.
*/
package de.ub0r.android.websms.connector.sipgate;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;
import org.xmlrpc.android.XMLRPCClient;
import org.xmlrpc.android.XMLRPCException;
import org.xmlrpc.android.XMLRPCFault;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import de.ub0r.android.websms.connector.common.Connector;
import de.ub0r.android.websms.connector.common.ConnectorCommand;
import de.ub0r.android.websms.connector.common.ConnectorSpec;
import de.ub0r.android.websms.connector.common.Utils;
import de.ub0r.android.websms.connector.common.WebSMSException;
import de.ub0r.android.websms.connector.common.ConnectorSpec.SubConnectorSpec;
/**
* AsyncTask to manage XMLRPC-Calls to sipgate.de remote-API.
*
* @author Mirko Weber
*/
public class ConnectorSipgate extends Connector {
/** Tag for output. */
private static final String TAG = "WebSMS.Sipg";
/** Sipgate.de API URL. */
private static final String SIPGATE_URL = "https://"
+ "samurai.sipgate.net/RPC2";
/** Sipfate.de TEAM-API URL. */
private static final String SIPGATE_TEAM_URL = "https://"
+ "api.sipgate.net/RPC2";
/**
* {@inheritDoc}
*/
@Override
public final ConnectorSpec initSpec(final Context context) {
final String name = context.getString(R.string.connector_sipgate_name);
ConnectorSpec c = new ConnectorSpec(TAG, name);
c.setAuthor(// .
context.getString(R.string.connector_sipgate_author));
c.setBalance(null);
c.setPrefsTitle(context
.getString(R.string.connector_sipgate_preferences));
c.setCapabilities(ConnectorSpec.CAPABILITIES_UPDATE
| ConnectorSpec.CAPABILITIES_SEND
| ConnectorSpec.CAPABILITIES_PREFS);
c.addSubConnector(TAG, c.getName(),
SubConnectorSpec.FEATURE_MULTIRECIPIENTS);
return c;
}
/**
* {@inheritDoc}
*/
@Override
public final ConnectorSpec updateSpec(final Context context,
final ConnectorSpec connectorSpec) {
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(context);
if (p.getBoolean(Preferences.PREFS_ENABLE_SIPGATE, false)) {
if (p.getString(Preferences.PREFS_USER_SIPGATE, "").length() > 0
&& p.getString(Preferences.PREFS_PASSWORD_SIPGATE, "") // .
.length() > 0) {
connectorSpec.setReady();
} else {
connectorSpec.setStatus(ConnectorSpec.STATUS_ENABLED);
}
} else {
connectorSpec.setStatus(ConnectorSpec.STATUS_INACTIVE);
}
return connectorSpec;
}
/**
* {@inheritDoc}
*/
@Override
protected final void doSend(final Context context, final Intent intent)
throws WebSMSException {
Log.d(TAG, "doSend()");
Object back;
try {
XMLRPCClient client = this.init(context);
Vector<String> remoteUris = new Vector<String>();
ConnectorCommand command = new ConnectorCommand(intent);
final String defPrefx = command.getDefPrefix();
String u;
- for (String t : command.getRecipients()) {
+ String[] rr = command.getRecipients();
+ for (String t : rr) {
if (t != null && t.length() > 1) {
u = "sip:"
+ Utils.national2international(defPrefx,
Utils.getRecipientsNumber(t)).replaceAll(
"\\+", "") + "@sipgate.net";
remoteUris.add(u);
Log.d(TAG, "Mobile number: " + u);
}
}
u = null;
+ rr = null;
Hashtable<String, Serializable> params = // .
new Hashtable<String, Serializable>();
final String sender = Utils.getSender(context, command
.getDefSender());
if (sender.length() > 6) {
String localUri = "sip:" + sender.replaceAll("\\+", "")
+ "@sipgate.net";
params.put("LocalUri", localUri);
}
params.put("RemoteUri", remoteUris);
params.put("TOS", "text");
- params.put("Content", command.getText());
+ params.put("Content", command.getText().replace("\n", " "));
back = client.call("samurai.SessionInitiateMulti", params);
Log.d(TAG, back.toString());
} catch (XMLRPCFault e) {
Log.e(TAG, null, e);
if (e.getFaultCode() == Utils.HTTP_SERVICE_UNAUTHORIZED) {
throw new WebSMSException(context, R.string.error_pw);
}
throw new WebSMSException(e);
} catch (XMLRPCException e) {
Log.e(TAG, null, e);
throw new WebSMSException(e);
}
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
protected final void doUpdate(final Context context, final Intent intent)
throws WebSMSException {
Log.d(TAG, "doUpdate()");
Map<String, Object> back = null;
try {
XMLRPCClient client = this.init(context);
back = (Map<String, Object>) client.call("samurai.BalanceGet");
Log.d(TAG, back.toString());
if (back.get("StatusCode").equals(
new Integer(Utils.HTTP_SERVICE_OK))) {
final String b = String.format("%.2f \u20AC",
((Double) ((Map<String, Object>) back
.get("CurrentBalance"))
.get("TotalIncludingVat")));
this.getSpec(context).setBalance(b);
}
} catch (XMLRPCFault e) {
Log.e(TAG, null, e);
if (e.getFaultCode() == Utils.HTTP_SERVICE_UNAUTHORIZED) {
throw new WebSMSException(context, R.string.error_pw);
}
throw new WebSMSException(e);
} catch (XMLRPCException e) {
Log.e(TAG, null, e);
throw new WebSMSException(e);
}
}
/**
* Sets up and instance of {@link XMLRPCClient}.
*
* @param context
* {@link Context}
* @return the initialized {@link XMLRPCClient}
* @throws XMLRPCException
* XMLRPCException
*/
private XMLRPCClient init(final Context context) throws XMLRPCException {
Log.d(TAG, "init()");
final String version = context.getString(R.string.app_version);
final String vendor = context
.getString(R.string.connector_sipgate_author);
XMLRPCClient client = null;
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(context);
if (p.getBoolean(Preferences.PREFS_ENABLE_SIPGATE_TEAM, false)) {
client = new XMLRPCClient(SIPGATE_TEAM_URL);
} else {
client = new XMLRPCClient(SIPGATE_URL);
}
client.setBasicAuthentication(p.getString(
Preferences.PREFS_USER_SIPGATE, ""), p.getString(
Preferences.PREFS_PASSWORD_SIPGATE, ""));
Object back;
try {
Hashtable<String, String> ident = new Hashtable<String, String>();
ident.put("ClientName", TAG);
ident.put("ClientVersion", version);
ident.put("ClientVendor", vendor);
back = client.call("samurai.ClientIdentify", ident);
Log.d(TAG, back.toString());
return client;
} catch (XMLRPCException e) {
Log.e(TAG, "XMLRPCExceptin in init()", e);
throw e;
}
}
}
| false | true | protected final void doSend(final Context context, final Intent intent)
throws WebSMSException {
Log.d(TAG, "doSend()");
Object back;
try {
XMLRPCClient client = this.init(context);
Vector<String> remoteUris = new Vector<String>();
ConnectorCommand command = new ConnectorCommand(intent);
final String defPrefx = command.getDefPrefix();
String u;
for (String t : command.getRecipients()) {
if (t != null && t.length() > 1) {
u = "sip:"
+ Utils.national2international(defPrefx,
Utils.getRecipientsNumber(t)).replaceAll(
"\\+", "") + "@sipgate.net";
remoteUris.add(u);
Log.d(TAG, "Mobile number: " + u);
}
}
u = null;
Hashtable<String, Serializable> params = // .
new Hashtable<String, Serializable>();
final String sender = Utils.getSender(context, command
.getDefSender());
if (sender.length() > 6) {
String localUri = "sip:" + sender.replaceAll("\\+", "")
+ "@sipgate.net";
params.put("LocalUri", localUri);
}
params.put("RemoteUri", remoteUris);
params.put("TOS", "text");
params.put("Content", command.getText());
back = client.call("samurai.SessionInitiateMulti", params);
Log.d(TAG, back.toString());
} catch (XMLRPCFault e) {
Log.e(TAG, null, e);
if (e.getFaultCode() == Utils.HTTP_SERVICE_UNAUTHORIZED) {
throw new WebSMSException(context, R.string.error_pw);
}
throw new WebSMSException(e);
} catch (XMLRPCException e) {
Log.e(TAG, null, e);
throw new WebSMSException(e);
}
}
| protected final void doSend(final Context context, final Intent intent)
throws WebSMSException {
Log.d(TAG, "doSend()");
Object back;
try {
XMLRPCClient client = this.init(context);
Vector<String> remoteUris = new Vector<String>();
ConnectorCommand command = new ConnectorCommand(intent);
final String defPrefx = command.getDefPrefix();
String u;
String[] rr = command.getRecipients();
for (String t : rr) {
if (t != null && t.length() > 1) {
u = "sip:"
+ Utils.national2international(defPrefx,
Utils.getRecipientsNumber(t)).replaceAll(
"\\+", "") + "@sipgate.net";
remoteUris.add(u);
Log.d(TAG, "Mobile number: " + u);
}
}
u = null;
rr = null;
Hashtable<String, Serializable> params = // .
new Hashtable<String, Serializable>();
final String sender = Utils.getSender(context, command
.getDefSender());
if (sender.length() > 6) {
String localUri = "sip:" + sender.replaceAll("\\+", "")
+ "@sipgate.net";
params.put("LocalUri", localUri);
}
params.put("RemoteUri", remoteUris);
params.put("TOS", "text");
params.put("Content", command.getText().replace("\n", " "));
back = client.call("samurai.SessionInitiateMulti", params);
Log.d(TAG, back.toString());
} catch (XMLRPCFault e) {
Log.e(TAG, null, e);
if (e.getFaultCode() == Utils.HTTP_SERVICE_UNAUTHORIZED) {
throw new WebSMSException(context, R.string.error_pw);
}
throw new WebSMSException(e);
} catch (XMLRPCException e) {
Log.e(TAG, null, e);
throw new WebSMSException(e);
}
}
|
diff --git a/core/plugins/org.eclipse.dltk.debug.ui/src/org/eclipse/dltk/internal/debug/ui/handlers/DebuggingEngineNotConfiguredStatusHandler.java b/core/plugins/org.eclipse.dltk.debug.ui/src/org/eclipse/dltk/internal/debug/ui/handlers/DebuggingEngineNotConfiguredStatusHandler.java
index 6aef4902e..2e63e4d92 100644
--- a/core/plugins/org.eclipse.dltk.debug.ui/src/org/eclipse/dltk/internal/debug/ui/handlers/DebuggingEngineNotConfiguredStatusHandler.java
+++ b/core/plugins/org.eclipse.dltk.debug.ui/src/org/eclipse/dltk/internal/debug/ui/handlers/DebuggingEngineNotConfiguredStatusHandler.java
@@ -1,43 +1,45 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.dltk.internal.debug.ui.handlers;
import org.eclipse.dltk.launching.DebuggingEngineRunner;
import org.eclipse.dltk.launching.debug.IDebuggingEngine;
/**
* Debugging engine configuration problem that prevents debugging engine from
* starting
*
* @author kds
*
*/
public class DebuggingEngineNotConfiguredStatusHandler extends
AbstractOpenPreferencePageStatusHandler {
protected String getPreferencePageId(Object source) {
if (source instanceof DebuggingEngineRunner) {
final DebuggingEngineRunner runner = (DebuggingEngineRunner) source;
final IDebuggingEngine engine = runner.getDebuggingEngine();
- return engine.getPreferencePageId();
+ if (engine != null) {
+ return engine.getPreferencePageId();
+ }
}
return null;
}
public String getTitle() {
return HandlerMessages.DebuggingEngineNotConfiguredTitle;
}
protected String getQuestion() {
return HandlerMessages.DebuggingEngineNotConfiguredQuestion;
}
}
| true | true | protected String getPreferencePageId(Object source) {
if (source instanceof DebuggingEngineRunner) {
final DebuggingEngineRunner runner = (DebuggingEngineRunner) source;
final IDebuggingEngine engine = runner.getDebuggingEngine();
return engine.getPreferencePageId();
}
return null;
}
| protected String getPreferencePageId(Object source) {
if (source instanceof DebuggingEngineRunner) {
final DebuggingEngineRunner runner = (DebuggingEngineRunner) source;
final IDebuggingEngine engine = runner.getDebuggingEngine();
if (engine != null) {
return engine.getPreferencePageId();
}
}
return null;
}
|
diff --git a/src/com/id/ui/app/AppLayout.java b/src/com/id/ui/app/AppLayout.java
index e0575c6..5f30cc6 100644
--- a/src/com/id/ui/app/AppLayout.java
+++ b/src/com/id/ui/app/AppLayout.java
@@ -1,63 +1,63 @@
package com.id.ui.app;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager;
public class AppLayout implements LayoutManager {
private Component filelist = null;
private Component spotlight = null;
private Component stack = null;
private Component fuzzyFinder;
@Override
public void addLayoutComponent(String name, Component component) {
if (name.equals("filelist")) {
filelist = component;
} else if (name.equals("spotlight")) {
spotlight = component;
} else if (name.equals("stack")) {
stack = component;
} else if (name.equals("fuzzyfinder")) {
fuzzyFinder = component;
}
}
@Override
public void layoutContainer(Container parent) {
int height = parent.getHeight();
- int fileListWidth = filelist.getPreferredSize().width;
+ int fileListWidth = 250;
int remainingWidth = parent.getWidth() - fileListWidth;
int editorWidth = remainingWidth / 2;
filelist.setBounds(0, 0, fileListWidth, height);
spotlight.setBounds(fileListWidth, 0, editorWidth, height);
stack.setBounds(fileListWidth + editorWidth, 0, editorWidth, height);
if (fuzzyFinder != null) {
- fuzzyFinder.setBounds(200, 0, 200, height);
+ fuzzyFinder.setBounds(250, 0, 200, height);
}
}
@Override
public Dimension minimumLayoutSize(Container parent) {
return new Dimension(800, 600);
}
@Override
public Dimension preferredLayoutSize(Container parent) {
return parent.getSize();
}
@Override
public void removeLayoutComponent(Component comp) {
if (filelist == comp) {
filelist = null;
} else if (spotlight == comp) {
spotlight = null;
} else if (stack == comp) {
stack = null;
} else if (fuzzyFinder == comp) {
fuzzyFinder = null;
}
}
}
| false | true | public void layoutContainer(Container parent) {
int height = parent.getHeight();
int fileListWidth = filelist.getPreferredSize().width;
int remainingWidth = parent.getWidth() - fileListWidth;
int editorWidth = remainingWidth / 2;
filelist.setBounds(0, 0, fileListWidth, height);
spotlight.setBounds(fileListWidth, 0, editorWidth, height);
stack.setBounds(fileListWidth + editorWidth, 0, editorWidth, height);
if (fuzzyFinder != null) {
fuzzyFinder.setBounds(200, 0, 200, height);
}
}
| public void layoutContainer(Container parent) {
int height = parent.getHeight();
int fileListWidth = 250;
int remainingWidth = parent.getWidth() - fileListWidth;
int editorWidth = remainingWidth / 2;
filelist.setBounds(0, 0, fileListWidth, height);
spotlight.setBounds(fileListWidth, 0, editorWidth, height);
stack.setBounds(fileListWidth + editorWidth, 0, editorWidth, height);
if (fuzzyFinder != null) {
fuzzyFinder.setBounds(250, 0, 200, height);
}
}
|
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/factory/GTFSPatternHopFactory.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/factory/GTFSPatternHopFactory.java
index 6785b6b32..1a81572e1 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/factory/GTFSPatternHopFactory.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/factory/GTFSPatternHopFactory.java
@@ -1,543 +1,543 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.routing.edgetype.factory;
import java.util.ArrayList;
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.Vector;
import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.gtfs.model.ShapePoint;
import org.onebusaway.gtfs.model.Stop;
import org.onebusaway.gtfs.model.StopTime;
import org.onebusaway.gtfs.model.Transfer;
import org.onebusaway.gtfs.model.Trip;
import org.onebusaway.gtfs.services.GtfsRelationalDao;
import org.opentripplanner.common.geometry.PackedCoordinateSequence;
import org.opentripplanner.gtfs.GtfsContext;
import org.opentripplanner.gtfs.GtfsLibrary;
import org.opentripplanner.routing.core.Graph;
import org.opentripplanner.routing.core.TraverseMode;
import org.opentripplanner.routing.core.Vertex;
import org.opentripplanner.routing.edgetype.Alight;
import org.opentripplanner.routing.edgetype.Board;
import org.opentripplanner.routing.edgetype.Dwell;
import org.opentripplanner.routing.edgetype.Hop;
import org.opentripplanner.routing.edgetype.PatternAlight;
import org.opentripplanner.routing.edgetype.PatternBoard;
import org.opentripplanner.routing.edgetype.PatternDwell;
import org.opentripplanner.routing.edgetype.PatternHop;
import org.opentripplanner.routing.edgetype.TripPattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.linearref.LinearLocation;
import com.vividsolutions.jts.linearref.LocationIndexedLine;
class StopPattern2 {
Vector<Stop> stops;
AgencyAndId calendarId;
public StopPattern2(Vector<Stop> stops, AgencyAndId calendarId) {
this.stops = stops;
this.calendarId = calendarId;
}
public boolean equals(Object other) {
if (other instanceof StopPattern2) {
StopPattern2 pattern = (StopPattern2) other;
return pattern.stops.equals(stops) && pattern.calendarId.equals(calendarId);
} else {
return false;
}
}
public int hashCode() {
return this.stops.hashCode() ^ this.calendarId.hashCode();
}
public String toString() {
return "StopPattern(" + stops + ", " + calendarId + ")";
}
}
class EncodedTrip {
Trip trip;
int patternIndex;
TripPattern pattern;
public EncodedTrip(Trip trip, int i, TripPattern pattern) {
this.trip = trip;
this.patternIndex = i;
this.pattern = pattern;
}
public boolean equals(Object o) {
if (!(o instanceof EncodedTrip))
return false;
EncodedTrip eto = (EncodedTrip) o;
return trip.equals(eto.trip) && patternIndex == eto.patternIndex
&& pattern.equals(eto.pattern);
}
public String toString() {
return "EncodedTrip(" + this.trip + ", " + this.patternIndex + ", " + this.pattern + ")";
}
}
public class GTFSPatternHopFactory {
private final Logger _log = LoggerFactory.getLogger(GTFSPatternHopFactory.class);
private static GeometryFactory _factory = new GeometryFactory();
private GtfsRelationalDao _dao;
private Map<ShapeSegmentKey, LineString> _geometriesByShapeSegmentKey = new HashMap<ShapeSegmentKey, LineString>();
private Map<AgencyAndId, LineString> _geometriesByShapeId = new HashMap<AgencyAndId, LineString>();
private Map<AgencyAndId, double[]> _distancesByShapeId = new HashMap<AgencyAndId, double[]>();
public GTFSPatternHopFactory(GtfsContext context) throws Exception {
_dao = context.getDao();
}
public static StopPattern2 stopPatternfromTrip(Trip trip, GtfsRelationalDao dao) {
Vector<Stop> stops = new Vector<Stop>();
for (StopTime stoptime : dao.getStopTimesForTrip(trip)) {
stops.add(stoptime.getStop());
}
StopPattern2 pattern = new StopPattern2(stops, trip.getServiceId());
return pattern;
}
private String id(AgencyAndId id) {
return GtfsLibrary.convertIdToString(id);
}
public void run(Graph graph) throws Exception {
clearCachedData();
/*
* For each trip, create either pattern edges, the entries in a trip pattern's list of
* departures, or simple hops
*/
// Load hops
Collection<Trip> trips = _dao.getAllTrips();
HashMap<StopPattern2, TripPattern> patterns = new HashMap<StopPattern2, TripPattern>();
int index = 0;
HashMap<String, ArrayList<EncodedTrip>> tripsByBlock = new HashMap<String, ArrayList<EncodedTrip>>();
for (Trip trip : trips) {
if (index % 100 == 0)
_log.debug("trips=" + index + "/" + trips.size());
index++;
List<StopTime> stopTimes = _dao.getStopTimesForTrip(trip);
if (stopTimes.isEmpty())
continue;
StopPattern2 stopPattern = stopPatternfromTrip(trip, _dao);
TripPattern tripPattern = patterns.get(stopPattern);
int lastStop = stopTimes.size() - 1;
TraverseMode mode = GtfsLibrary.getTraverseMode(trip.getRoute());
if (tripPattern == null) {
tripPattern = new TripPattern(trip, stopTimes);
int patternIndex = -1;
for (int i = 0; i < lastStop; i++) {
StopTime st0 = stopTimes.get(i);
Stop s0 = st0.getStop();
StopTime st1 = stopTimes.get(i + 1);
Stop s1 = st1.getStop();
int dwellTime = st0.getDepartureTime() - st0.getArrivalTime();
int runningTime = st1.getArrivalTime() - st0.getDepartureTime();
// create journey vertices
Vertex startJourneyDepart = graph.addVertex(id(s0.getId()) + "_"
+ id(trip.getId()) + "_D", s0.getLon(), s0.getLat());
Vertex endJourneyArrive = graph.addVertex(id(s1.getId()) + "_"
+ id(trip.getId()) + "_A", s1.getLon(), s1.getLat());
Vertex startJourneyArrive;
if (i != 0) {
startJourneyArrive = graph.addVertex(id(s0.getId()) + "_"
+ id(trip.getId()) + "_A", s0.getLon(), s0.getLat());
PatternDwell dwell = new PatternDwell(startJourneyArrive,
startJourneyDepart, i, tripPattern);
graph.addEdge(dwell);
}
PatternHop hop = new PatternHop(startJourneyDepart, endJourneyArrive, s0, s1,
i, tripPattern);
hop.setGeometry(getHopGeometry(trip.getShapeId(), st0, st1, startJourneyDepart,
endJourneyArrive));
patternIndex = tripPattern.addHop(i, 0, st0.getDepartureTime(), runningTime,
st1.getArrivalTime(), dwellTime);
graph.addEdge(hop);
Vertex startStation = graph.getVertex(id(s0.getId()));
Vertex endStation = graph.getVertex(id(s1.getId()));
PatternBoard boarding = new PatternBoard(startStation, startJourneyDepart,
tripPattern, i, mode);
graph.addEdge(boarding);
graph.addEdge(new PatternAlight(endJourneyArrive, endStation, tripPattern, i, mode));
}
patterns.put(stopPattern, tripPattern);
String blockId = trip.getBlockId();
if (blockId != null && !blockId.equals("")) {
ArrayList<EncodedTrip> blockTrips = tripsByBlock.get(blockId);
if (blockTrips == null) {
blockTrips = new ArrayList<EncodedTrip>();
tripsByBlock.put(blockId, blockTrips);
}
blockTrips.add(new EncodedTrip(trip, patternIndex, tripPattern));
}
} else {
int insertionPoint = tripPattern.getDepartureTimeInsertionPoint(stopTimes.get(0)
.getDepartureTime());
if (insertionPoint < 0) {
// There's already a departure at this time on this trip pattern. This means
// that either (a) this will have all the same stop times as that one, and thus
// will be a duplicate of it, or (b) it will have different stops, and thus
// break the assumption that trips are non-overlapping.
_log.warn("duplicate first departure time for trip " + trip.getId()
+ ". This will be handled correctly but inefficiently.");
createSimpleHops(graph, trip, stopTimes);
} else {
// try to insert this trip at this location
boolean simple = false;
for (int i = 0; i < lastStop; i++) {
StopTime st0 = stopTimes.get(i);
StopTime st1 = stopTimes.get(i + 1);
int dwellTime = st0.getDepartureTime() - st0.getArrivalTime();
int runningTime = st1.getArrivalTime() - st0.getDepartureTime();
try {
tripPattern.addHop(i, insertionPoint, st0.getDepartureTime(),
runningTime, st1.getArrivalTime(), dwellTime);
} catch (TripOvertakingException e) {
_log
.warn("trip "
+ trip.getId()
+ " overtakes another trip with the same stops. This will be handled correctly but inefficiently.");
// back out trips and revert to the simple method
for (i=i-1; i >= 0; --i) {
tripPattern.removeHop(i, insertionPoint);
}
createSimpleHops(graph, trip, stopTimes);
simple = true;
break;
}
}
if (!simple) {
String blockId = trip.getBlockId();
if (blockId != null && !blockId.equals("")) {
ArrayList<EncodedTrip> blockTrips = tripsByBlock.get(blockId);
if (blockTrips == null) {
blockTrips = new ArrayList<EncodedTrip>();
tripsByBlock.put(blockId, blockTrips);
}
blockTrips.add(new EncodedTrip(trip, 0, tripPattern));
}
}
}
}
}
/* for interlined trips, add final dwell edge */
for (ArrayList<EncodedTrip> blockTrips : tripsByBlock.values()) {
HashMap<Stop, EncodedTrip> starts = new HashMap<Stop, EncodedTrip>();
for (EncodedTrip encoded : blockTrips) {
Trip trip = encoded.trip;
List<StopTime> stopTimes = _dao.getStopTimesForTrip(trip);
Stop start = stopTimes.get(0).getStop();
starts.put(start, encoded);
}
for (EncodedTrip encoded : blockTrips) {
Trip trip = encoded.trip;
List<StopTime> stopTimes = _dao.getStopTimesForTrip(trip);
StopTime endTime = stopTimes.get(stopTimes.size() - 1);
Stop end = endTime.getStop();
if (starts.containsKey(end)) {
EncodedTrip nextTrip = starts.get(end);
Vertex arrive = graph.addVertex(
id(end.getId()) + "_" + id(trip.getId()) + "_A", end.getLon(), end
.getLat());
Vertex depart = graph.addVertex(id(end.getId()) + "_"
+ id(nextTrip.trip.getId()) + "_D", end.getLon(), end.getLat());
PatternDwell dwell = new PatternDwell(arrive, depart, nextTrip.patternIndex,
encoded.pattern);
graph.addEdge(dwell);
List<StopTime> nextStopTimes = _dao.getStopTimesForTrip(nextTrip.trip);
StopTime startTime = nextStopTimes.get(0);
- int dwellTime = startTime.getDepartureTime() - endTime.getArrivalTime();
+ int dwellTime = startTime.getDepartureTime() - startTime.getArrivalTime();
encoded.pattern.setDwellTime(stopTimes.size() - 2, encoded.patternIndex,
dwellTime);
}
}
}
loadTransfers(graph);
clearCachedData();
}
private void clearCachedData() {
_log.debug("shapes=" + _geometriesByShapeId.size());
_log.debug("segments=" + _geometriesByShapeSegmentKey.size());
_geometriesByShapeId.clear();
_distancesByShapeId.clear();
_geometriesByShapeSegmentKey.clear();
}
private void loadTransfers(Graph graph) {
Collection<Transfer> transfers = _dao.getAllTransfers();
Set<org.opentripplanner.routing.edgetype.Transfer> createdTransfers = new HashSet<org.opentripplanner.routing.edgetype.Transfer>();
for (Transfer t : transfers) {
Stop fromStop = t.getFromStop();
Stop toStop = t.getToStop();
Vertex fromStation = graph.getVertex(id(fromStop.getId()));
Vertex toStation = graph.getVertex(id(toStop.getId()));
int transferTime = 0;
if (t.getTransferType() < 3) {
if (t.getTransferType() == 2) {
transferTime = t.getMinTransferTime();
}
org.opentripplanner.routing.edgetype.Transfer edge = new org.opentripplanner.routing.edgetype.Transfer(
fromStation, toStation, transferTime);
if (createdTransfers.contains(edge)) {
continue;
}
GeometryFactory factory = new GeometryFactory();
LineString geometry = factory.createLineString(new Coordinate[] {
new Coordinate(fromStop.getLon(), fromStop.getLat()),
new Coordinate(toStop.getLon(), toStop.getLat()) });
edge.setGeometry(geometry);
createdTransfers.add(edge);
graph.addEdge(edge);
}
}
}
private void createSimpleHops(Graph graph, Trip trip, List<StopTime> stopTimes)
throws Exception {
String tripId = id(trip.getId());
ArrayList<Hop> hops = new ArrayList<Hop>();
for (int i = 0; i < stopTimes.size() - 1; i++) {
StopTime st0 = stopTimes.get(i);
Stop s0 = st0.getStop();
StopTime st1 = stopTimes.get(i + 1);
Stop s1 = st1.getStop();
Vertex startStation = graph.getVertex(id(s0.getId()));
Vertex endStation = graph.getVertex(id(s1.getId()));
// create journey vertices
Vertex startJourneyArrive = graph.addVertex(id(s0.getId()) + "_" + tripId, s0.getLon(),
s0.getLat());
Vertex startJourneyDepart = graph.addVertex(id(s0.getId()) + "_" + tripId, s0.getLon(),
s0.getLat());
Vertex endJourney = graph.addVertex(id(s1.getId()) + "_" + tripId, s1.getLon(), s1
.getLat());
Dwell dwell = new Dwell(startJourneyArrive, startJourneyDepart, st0);
graph.addEdge(dwell);
Hop hop = new Hop(startJourneyDepart, endJourney, st0, st1);
hop.setGeometry(getHopGeometry(trip.getShapeId(), st0, st1, startJourneyDepart,
endJourney));
hops.add(hop);
Board boarding = new Board(startStation, startJourneyDepart, hop);
graph.addEdge(boarding);
graph.addEdge(new Alight(endJourney, endStation, hop));
}
}
private Geometry getHopGeometry(AgencyAndId shapeId, StopTime st0, StopTime st1,
Vertex startJourney, Vertex endJourney) {
if (shapeId == null || shapeId.getId() == null || shapeId.getId().equals(""))
return null;
double startDistance = st0.getShapeDistTraveled();
double endDistance = st1.getShapeDistTraveled();
boolean hasShapeDist = startDistance != -1 && endDistance != -1;
if (hasShapeDist) {
ShapeSegmentKey key = new ShapeSegmentKey(shapeId, startDistance, endDistance);
LineString geometry = _geometriesByShapeSegmentKey.get(key);
if (geometry != null)
return geometry;
double[] distances = getDistanceForShapeId(shapeId);
if (distances != null) {
LinearLocation startIndex = getSegmentFraction(distances, startDistance);
LinearLocation endIndex = getSegmentFraction(distances, endDistance);
LineString line = getLineStringForShapeId(shapeId);
LocationIndexedLine lol = new LocationIndexedLine(line);
return getSegmentGeometry(shapeId, lol, startIndex, endIndex, startDistance,
endDistance);
}
}
LineString line = getLineStringForShapeId(shapeId);
LocationIndexedLine lol = new LocationIndexedLine(line);
LinearLocation startCoord = lol.indexOf(startJourney.getCoordinate());
LinearLocation endCoord = lol.indexOf(endJourney.getCoordinate());
double distanceFrom = startCoord.getSegmentLength(line);
double distanceTo = endCoord.getSegmentLength(line);
return getSegmentGeometry(shapeId, lol, startCoord, endCoord, distanceFrom, distanceTo);
}
private Geometry getSegmentGeometry(AgencyAndId shapeId,
LocationIndexedLine locationIndexedLine, LinearLocation startIndex,
LinearLocation endIndex, double startDistance, double endDistance) {
ShapeSegmentKey key = new ShapeSegmentKey(shapeId, startDistance, endDistance);
LineString geometry = _geometriesByShapeSegmentKey.get(key);
if (geometry == null) {
geometry = (LineString) locationIndexedLine.extractLine(startIndex, endIndex);
// Pack the resulting line string
CoordinateSequence sequence = new PackedCoordinateSequence.Float(geometry
.getCoordinates(), 2);
geometry = _factory.createLineString(sequence);
_geometriesByShapeSegmentKey.put(key, geometry);
}
return geometry;
}
private LineString getLineStringForShapeId(AgencyAndId shapeId) {
LineString geometry = _geometriesByShapeId.get(shapeId);
if (geometry != null)
return geometry;
List<ShapePoint> points = _dao.getShapePointsForShapeId(shapeId);
Coordinate[] coordinates = new Coordinate[points.size()];
double[] distances = new double[points.size()];
boolean hasAllDistances = true;
int i = 0;
for (ShapePoint point : points) {
coordinates[i] = new Coordinate(point.getLon(), point.getLat());
distances[i] = point.getDistTraveled();
if (point.getDistTraveled() == -1)
hasAllDistances = false;
i++;
}
/**
* If we don't have distances here, we can't calculate them ourselves because we can't
* assume the units will match
*/
if (!hasAllDistances) {
distances = null;
}
CoordinateSequence sequence = new PackedCoordinateSequence.Float(coordinates, 2);
geometry = _factory.createLineString(sequence);
_geometriesByShapeId.put(shapeId, geometry);
_distancesByShapeId.put(shapeId, distances);
return geometry;
}
private double[] getDistanceForShapeId(AgencyAndId shapeId) {
getLineStringForShapeId(shapeId);
return _distancesByShapeId.get(shapeId);
}
private LinearLocation getSegmentFraction(double[] distances, double distance) {
int index = Arrays.binarySearch(distances, distance);
if (index < 0)
index = -(index + 1);
if (index == 0)
return new LinearLocation(0, 0.0);
if (index == distances.length)
return new LinearLocation(distances.length, 0.0);
double indexPart = (distance - distances[index - 1])
/ (distances[index] - distances[index - 1]);
return new LinearLocation(index - 1, indexPart);
}
}
| true | true | public void run(Graph graph) throws Exception {
clearCachedData();
/*
* For each trip, create either pattern edges, the entries in a trip pattern's list of
* departures, or simple hops
*/
// Load hops
Collection<Trip> trips = _dao.getAllTrips();
HashMap<StopPattern2, TripPattern> patterns = new HashMap<StopPattern2, TripPattern>();
int index = 0;
HashMap<String, ArrayList<EncodedTrip>> tripsByBlock = new HashMap<String, ArrayList<EncodedTrip>>();
for (Trip trip : trips) {
if (index % 100 == 0)
_log.debug("trips=" + index + "/" + trips.size());
index++;
List<StopTime> stopTimes = _dao.getStopTimesForTrip(trip);
if (stopTimes.isEmpty())
continue;
StopPattern2 stopPattern = stopPatternfromTrip(trip, _dao);
TripPattern tripPattern = patterns.get(stopPattern);
int lastStop = stopTimes.size() - 1;
TraverseMode mode = GtfsLibrary.getTraverseMode(trip.getRoute());
if (tripPattern == null) {
tripPattern = new TripPattern(trip, stopTimes);
int patternIndex = -1;
for (int i = 0; i < lastStop; i++) {
StopTime st0 = stopTimes.get(i);
Stop s0 = st0.getStop();
StopTime st1 = stopTimes.get(i + 1);
Stop s1 = st1.getStop();
int dwellTime = st0.getDepartureTime() - st0.getArrivalTime();
int runningTime = st1.getArrivalTime() - st0.getDepartureTime();
// create journey vertices
Vertex startJourneyDepart = graph.addVertex(id(s0.getId()) + "_"
+ id(trip.getId()) + "_D", s0.getLon(), s0.getLat());
Vertex endJourneyArrive = graph.addVertex(id(s1.getId()) + "_"
+ id(trip.getId()) + "_A", s1.getLon(), s1.getLat());
Vertex startJourneyArrive;
if (i != 0) {
startJourneyArrive = graph.addVertex(id(s0.getId()) + "_"
+ id(trip.getId()) + "_A", s0.getLon(), s0.getLat());
PatternDwell dwell = new PatternDwell(startJourneyArrive,
startJourneyDepart, i, tripPattern);
graph.addEdge(dwell);
}
PatternHop hop = new PatternHop(startJourneyDepart, endJourneyArrive, s0, s1,
i, tripPattern);
hop.setGeometry(getHopGeometry(trip.getShapeId(), st0, st1, startJourneyDepart,
endJourneyArrive));
patternIndex = tripPattern.addHop(i, 0, st0.getDepartureTime(), runningTime,
st1.getArrivalTime(), dwellTime);
graph.addEdge(hop);
Vertex startStation = graph.getVertex(id(s0.getId()));
Vertex endStation = graph.getVertex(id(s1.getId()));
PatternBoard boarding = new PatternBoard(startStation, startJourneyDepart,
tripPattern, i, mode);
graph.addEdge(boarding);
graph.addEdge(new PatternAlight(endJourneyArrive, endStation, tripPattern, i, mode));
}
patterns.put(stopPattern, tripPattern);
String blockId = trip.getBlockId();
if (blockId != null && !blockId.equals("")) {
ArrayList<EncodedTrip> blockTrips = tripsByBlock.get(blockId);
if (blockTrips == null) {
blockTrips = new ArrayList<EncodedTrip>();
tripsByBlock.put(blockId, blockTrips);
}
blockTrips.add(new EncodedTrip(trip, patternIndex, tripPattern));
}
} else {
int insertionPoint = tripPattern.getDepartureTimeInsertionPoint(stopTimes.get(0)
.getDepartureTime());
if (insertionPoint < 0) {
// There's already a departure at this time on this trip pattern. This means
// that either (a) this will have all the same stop times as that one, and thus
// will be a duplicate of it, or (b) it will have different stops, and thus
// break the assumption that trips are non-overlapping.
_log.warn("duplicate first departure time for trip " + trip.getId()
+ ". This will be handled correctly but inefficiently.");
createSimpleHops(graph, trip, stopTimes);
} else {
// try to insert this trip at this location
boolean simple = false;
for (int i = 0; i < lastStop; i++) {
StopTime st0 = stopTimes.get(i);
StopTime st1 = stopTimes.get(i + 1);
int dwellTime = st0.getDepartureTime() - st0.getArrivalTime();
int runningTime = st1.getArrivalTime() - st0.getDepartureTime();
try {
tripPattern.addHop(i, insertionPoint, st0.getDepartureTime(),
runningTime, st1.getArrivalTime(), dwellTime);
} catch (TripOvertakingException e) {
_log
.warn("trip "
+ trip.getId()
+ " overtakes another trip with the same stops. This will be handled correctly but inefficiently.");
// back out trips and revert to the simple method
for (i=i-1; i >= 0; --i) {
tripPattern.removeHop(i, insertionPoint);
}
createSimpleHops(graph, trip, stopTimes);
simple = true;
break;
}
}
if (!simple) {
String blockId = trip.getBlockId();
if (blockId != null && !blockId.equals("")) {
ArrayList<EncodedTrip> blockTrips = tripsByBlock.get(blockId);
if (blockTrips == null) {
blockTrips = new ArrayList<EncodedTrip>();
tripsByBlock.put(blockId, blockTrips);
}
blockTrips.add(new EncodedTrip(trip, 0, tripPattern));
}
}
}
}
}
/* for interlined trips, add final dwell edge */
for (ArrayList<EncodedTrip> blockTrips : tripsByBlock.values()) {
HashMap<Stop, EncodedTrip> starts = new HashMap<Stop, EncodedTrip>();
for (EncodedTrip encoded : blockTrips) {
Trip trip = encoded.trip;
List<StopTime> stopTimes = _dao.getStopTimesForTrip(trip);
Stop start = stopTimes.get(0).getStop();
starts.put(start, encoded);
}
for (EncodedTrip encoded : blockTrips) {
Trip trip = encoded.trip;
List<StopTime> stopTimes = _dao.getStopTimesForTrip(trip);
StopTime endTime = stopTimes.get(stopTimes.size() - 1);
Stop end = endTime.getStop();
if (starts.containsKey(end)) {
EncodedTrip nextTrip = starts.get(end);
Vertex arrive = graph.addVertex(
id(end.getId()) + "_" + id(trip.getId()) + "_A", end.getLon(), end
.getLat());
Vertex depart = graph.addVertex(id(end.getId()) + "_"
+ id(nextTrip.trip.getId()) + "_D", end.getLon(), end.getLat());
PatternDwell dwell = new PatternDwell(arrive, depart, nextTrip.patternIndex,
encoded.pattern);
graph.addEdge(dwell);
List<StopTime> nextStopTimes = _dao.getStopTimesForTrip(nextTrip.trip);
StopTime startTime = nextStopTimes.get(0);
int dwellTime = startTime.getDepartureTime() - endTime.getArrivalTime();
encoded.pattern.setDwellTime(stopTimes.size() - 2, encoded.patternIndex,
dwellTime);
}
}
}
loadTransfers(graph);
clearCachedData();
}
| public void run(Graph graph) throws Exception {
clearCachedData();
/*
* For each trip, create either pattern edges, the entries in a trip pattern's list of
* departures, or simple hops
*/
// Load hops
Collection<Trip> trips = _dao.getAllTrips();
HashMap<StopPattern2, TripPattern> patterns = new HashMap<StopPattern2, TripPattern>();
int index = 0;
HashMap<String, ArrayList<EncodedTrip>> tripsByBlock = new HashMap<String, ArrayList<EncodedTrip>>();
for (Trip trip : trips) {
if (index % 100 == 0)
_log.debug("trips=" + index + "/" + trips.size());
index++;
List<StopTime> stopTimes = _dao.getStopTimesForTrip(trip);
if (stopTimes.isEmpty())
continue;
StopPattern2 stopPattern = stopPatternfromTrip(trip, _dao);
TripPattern tripPattern = patterns.get(stopPattern);
int lastStop = stopTimes.size() - 1;
TraverseMode mode = GtfsLibrary.getTraverseMode(trip.getRoute());
if (tripPattern == null) {
tripPattern = new TripPattern(trip, stopTimes);
int patternIndex = -1;
for (int i = 0; i < lastStop; i++) {
StopTime st0 = stopTimes.get(i);
Stop s0 = st0.getStop();
StopTime st1 = stopTimes.get(i + 1);
Stop s1 = st1.getStop();
int dwellTime = st0.getDepartureTime() - st0.getArrivalTime();
int runningTime = st1.getArrivalTime() - st0.getDepartureTime();
// create journey vertices
Vertex startJourneyDepart = graph.addVertex(id(s0.getId()) + "_"
+ id(trip.getId()) + "_D", s0.getLon(), s0.getLat());
Vertex endJourneyArrive = graph.addVertex(id(s1.getId()) + "_"
+ id(trip.getId()) + "_A", s1.getLon(), s1.getLat());
Vertex startJourneyArrive;
if (i != 0) {
startJourneyArrive = graph.addVertex(id(s0.getId()) + "_"
+ id(trip.getId()) + "_A", s0.getLon(), s0.getLat());
PatternDwell dwell = new PatternDwell(startJourneyArrive,
startJourneyDepart, i, tripPattern);
graph.addEdge(dwell);
}
PatternHop hop = new PatternHop(startJourneyDepart, endJourneyArrive, s0, s1,
i, tripPattern);
hop.setGeometry(getHopGeometry(trip.getShapeId(), st0, st1, startJourneyDepart,
endJourneyArrive));
patternIndex = tripPattern.addHop(i, 0, st0.getDepartureTime(), runningTime,
st1.getArrivalTime(), dwellTime);
graph.addEdge(hop);
Vertex startStation = graph.getVertex(id(s0.getId()));
Vertex endStation = graph.getVertex(id(s1.getId()));
PatternBoard boarding = new PatternBoard(startStation, startJourneyDepart,
tripPattern, i, mode);
graph.addEdge(boarding);
graph.addEdge(new PatternAlight(endJourneyArrive, endStation, tripPattern, i, mode));
}
patterns.put(stopPattern, tripPattern);
String blockId = trip.getBlockId();
if (blockId != null && !blockId.equals("")) {
ArrayList<EncodedTrip> blockTrips = tripsByBlock.get(blockId);
if (blockTrips == null) {
blockTrips = new ArrayList<EncodedTrip>();
tripsByBlock.put(blockId, blockTrips);
}
blockTrips.add(new EncodedTrip(trip, patternIndex, tripPattern));
}
} else {
int insertionPoint = tripPattern.getDepartureTimeInsertionPoint(stopTimes.get(0)
.getDepartureTime());
if (insertionPoint < 0) {
// There's already a departure at this time on this trip pattern. This means
// that either (a) this will have all the same stop times as that one, and thus
// will be a duplicate of it, or (b) it will have different stops, and thus
// break the assumption that trips are non-overlapping.
_log.warn("duplicate first departure time for trip " + trip.getId()
+ ". This will be handled correctly but inefficiently.");
createSimpleHops(graph, trip, stopTimes);
} else {
// try to insert this trip at this location
boolean simple = false;
for (int i = 0; i < lastStop; i++) {
StopTime st0 = stopTimes.get(i);
StopTime st1 = stopTimes.get(i + 1);
int dwellTime = st0.getDepartureTime() - st0.getArrivalTime();
int runningTime = st1.getArrivalTime() - st0.getDepartureTime();
try {
tripPattern.addHop(i, insertionPoint, st0.getDepartureTime(),
runningTime, st1.getArrivalTime(), dwellTime);
} catch (TripOvertakingException e) {
_log
.warn("trip "
+ trip.getId()
+ " overtakes another trip with the same stops. This will be handled correctly but inefficiently.");
// back out trips and revert to the simple method
for (i=i-1; i >= 0; --i) {
tripPattern.removeHop(i, insertionPoint);
}
createSimpleHops(graph, trip, stopTimes);
simple = true;
break;
}
}
if (!simple) {
String blockId = trip.getBlockId();
if (blockId != null && !blockId.equals("")) {
ArrayList<EncodedTrip> blockTrips = tripsByBlock.get(blockId);
if (blockTrips == null) {
blockTrips = new ArrayList<EncodedTrip>();
tripsByBlock.put(blockId, blockTrips);
}
blockTrips.add(new EncodedTrip(trip, 0, tripPattern));
}
}
}
}
}
/* for interlined trips, add final dwell edge */
for (ArrayList<EncodedTrip> blockTrips : tripsByBlock.values()) {
HashMap<Stop, EncodedTrip> starts = new HashMap<Stop, EncodedTrip>();
for (EncodedTrip encoded : blockTrips) {
Trip trip = encoded.trip;
List<StopTime> stopTimes = _dao.getStopTimesForTrip(trip);
Stop start = stopTimes.get(0).getStop();
starts.put(start, encoded);
}
for (EncodedTrip encoded : blockTrips) {
Trip trip = encoded.trip;
List<StopTime> stopTimes = _dao.getStopTimesForTrip(trip);
StopTime endTime = stopTimes.get(stopTimes.size() - 1);
Stop end = endTime.getStop();
if (starts.containsKey(end)) {
EncodedTrip nextTrip = starts.get(end);
Vertex arrive = graph.addVertex(
id(end.getId()) + "_" + id(trip.getId()) + "_A", end.getLon(), end
.getLat());
Vertex depart = graph.addVertex(id(end.getId()) + "_"
+ id(nextTrip.trip.getId()) + "_D", end.getLon(), end.getLat());
PatternDwell dwell = new PatternDwell(arrive, depart, nextTrip.patternIndex,
encoded.pattern);
graph.addEdge(dwell);
List<StopTime> nextStopTimes = _dao.getStopTimesForTrip(nextTrip.trip);
StopTime startTime = nextStopTimes.get(0);
int dwellTime = startTime.getDepartureTime() - startTime.getArrivalTime();
encoded.pattern.setDwellTime(stopTimes.size() - 2, encoded.patternIndex,
dwellTime);
}
}
}
loadTransfers(graph);
clearCachedData();
}
|
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/objectmanager/ContainerAdapter.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/objectmanager/ContainerAdapter.java
index 6323d1462..d9e6e2765 100644
--- a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/objectmanager/ContainerAdapter.java
+++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/objectmanager/ContainerAdapter.java
@@ -1,776 +1,780 @@
/*
* ContainerAdapter.java
*
* Version: $Revision: 1.6 $
*
* Date: $Date: 2006/05/02 01:24:11 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.xmlui.objectmanager;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.SQLException;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.ItemCounter;
import org.dspace.browse.ItemCountException;
import org.dspace.content.Bitstream;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.content.crosswalk.CrosswalkException;
import org.dspace.content.crosswalk.DisseminationCrosswalk;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.SAXOutputter;
import org.xml.sax.SAXException;
/**
* This is an adapter which translates DSpace containers
* (communities & collections) into METS documents. This adapter follows
* the DSpace METS profile however that profile does not define how a
* community or collection should be described, but we make the obvious
* decisions to deviate when nessasary from the profile.
*
* The METS document consists of three parts: descriptive metadata section,
* file section, and a structural map. The descriptive metadata sections holds
* metadata about the item being adapted using DSpace crosswalks. This is the
* same way the item adapter works.
*
* However the file section and structural map are a bit different. In these
* casses the the only files listed is the one logo that may be attached to
* a community or collection.
*
* @author Scott Phillips
*/
public class ContainerAdapter extends AbstractAdapter
{
/** The community or collection this adapter represents. */
private DSpaceObject dso;
/** A space seperated list of descriptive metadata sections */
private StringBuffer dmdSecIDS;
/** Current DSpace context **/
private Context dspaceContext;
/**
* Construct a new CommunityCollectionMETSAdapter.
*
* @param dso
* A DSpace Community or Collection to adapt.
* @param contextPath
* The contextPath of this webapplication.
*/
public ContainerAdapter(Context context, DSpaceObject dso,String contextPath)
{
super(contextPath);
this.dso = dso;
this.dspaceContext = context;
}
/** Return the container, community or collection, object */
public DSpaceObject getContainer()
{
return this.dso;
}
/**
*
*
*
* Required abstract methods
*
*
*
*/
/**
* Return the URL of this community/collection in the interface
*/
protected String getMETSOBJID()
{
if (dso.getHandle() != null)
return contextPath+"/handle/" + dso.getHandle();
return null;
}
/**
* @return Return the URL for editing this item
*/
protected String getMETSOBJEDIT()
{
return null;
}
/**
* Use the handle as the id for this METS document
*/
protected String getMETSID()
{
if (dso.getHandle() == null)
{
if (dso instanceof Collection)
return "collection:"+dso.getID();
else
return "community:"+dso.getID();
}
else
return "hdl:"+dso.getHandle();
}
/**
* Return the profile to use for communities and collections.
*
*/
protected String getMETSProfile() throws WingException
{
return "DSPACE METS SIP Profile 1.0";
}
/**
* Return a friendly label for the METS document to say we are a community
* or collection.
*/
protected String getMETSLabel()
{
if (dso instanceof Community)
return "DSpace Community";
else
return "DSpace Collection";
}
/**
* Return a unique id for the given bitstream
*/
protected String getFileID(Bitstream bitstream)
{
return "file_" + bitstream.getID();
}
/**
* Return a group id for the given bitstream
*/
protected String getGroupFileID(Bitstream bitstream)
{
return "group_file_" + bitstream.getID();
}
/**
*
*
*
* METS structural methods
*
*
*
*/
/**
* Render the METS descriptive section. This will create a new metadata
* section for each crosswalk configured.
*
* Example:
* <dmdSec>
* <mdWrap MDTYPE="MODS">
* <xmlData>
* ... content from the crosswalk ...
* </xmlDate>
* </mdWrap>
* </dmdSec
*/
protected void renderDescriptiveSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException
{
AttributeMap attributes;
String groupID = getGenericID("group_dmd_");
dmdSecIDS = new StringBuffer();
// Add DIM descriptive metadata if it was requested or if no metadata types
// were specified. Further more since this is the default type we also use a
// faster rendering method that the crosswalk API.
if(dmdTypes.size() == 0 || dmdTypes.contains("DIM"))
{
// Metadata element's ID
String dmdID = getGenericID("dmd_");
// Keep track of all descriptive sections
dmdSecIDS.append(dmdID);
// ////////////////////////////////
// Start a new dmdSec for each crosswalk.
attributes = new AttributeMap();
attributes.put("ID", dmdID);
attributes.put("GROUPID", groupID);
startElement(METS,"dmdSec",attributes);
// ////////////////////////////////
// Start metadata wrapper
attributes = new AttributeMap();
attributes.put("MDTYPE", "OTHER");
attributes.put("OTHERMDTYPE", "DIM");
startElement(METS,"mdWrap",attributes);
// ////////////////////////////////
// Start the xml data
startElement(METS,"xmlData");
// ///////////////////////////////
// Start the DIM element
attributes = new AttributeMap();
attributes.put("dspaceType", Constants.typeText[dso.getType()]);
startElement(DIM,"dim",attributes);
// Add each field for this collection
if (dso.getType() == Constants.COLLECTION)
{
Collection collection = (Collection) dso;
String description = collection.getMetadata("introductory_text");
String description_abstract = collection.getMetadata("short_description");
String description_table = collection.getMetadata("side_bar_text");
String identifier_uri = "http://hdl.handle.net/" + collection.getHandle();
String provenance = collection.getMetadata("provenance_description");
String rights = collection.getMetadata("copyright_text");
String rights_license = collection.getMetadata("license");
String title = collection.getMetadata("name");
createField("dc","description",null,null,description);
createField("dc","description","abstract",null,description_abstract);
createField("dc","description","tableofcontents",null,description_table);
createField("dc","identifier","uri",null,identifier_uri);
createField("dc","provenance",null,null,provenance);
createField("dc","rights",null,null,rights);
createField("dc","rights","license",null,rights_license);
createField("dc","title",null,null,title);
boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache");
//To improve scalability, XMLUI only adds item counts if they are cached
if (useCache)
{
try
{ //try to determine Collection size (i.e. # of items)
int size = new ItemCounter(this.dspaceContext).getCount(collection);
createField("dc","format","extent",null, String.valueOf(size));
}
catch(ItemCountException e)
{
- throw new IOException("Could not obtain Collection item-count: ", e);
+ IOException ioe = new IOException("Could not obtain Collection item-count");
+ ioe.initCause(e);
+ throw ioe;
}
}
}
else if (dso.getType() == Constants.COMMUNITY)
{
Community community = (Community) dso;
String description = community.getMetadata("introductory_text");
String description_abstract = community.getMetadata("short_description");
String description_table = community.getMetadata("side_bar_text");
String identifier_uri = "http://hdl.handle.net/" + community.getHandle();
String rights = community.getMetadata("copyright_text");
String title = community.getMetadata("name");
createField("dc","description",null,null,description);
createField("dc","description","abstract",null,description_abstract);
createField("dc","description","tableofcontents",null,description_table);
createField("dc","identifier","uri",null,identifier_uri);
createField("dc","rights",null,null,rights);
createField("dc","title",null,null,title);
boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache");
//To improve scalability, XMLUI only adds item counts if they are cached
if (useCache)
{
try
{ //try to determine Community size (i.e. # of items)
int size = new ItemCounter(this.dspaceContext).getCount(community);
createField("dc","format","extent",null, String.valueOf(size));
}
catch(ItemCountException e)
{
- throw new IOException("Could not obtain Community item-count: ", e);
+ IOException ioe = new IOException("Could not obtain Collection item-count");
+ ioe.initCause(e);
+ throw ioe;
}
}
}
// ///////////////////////////////
// End the DIM element
endElement(DIM,"dim");
// ////////////////////////////////
// End elements
endElement(METS,"xmlData");
endElement(METS,"mdWrap");
endElement(METS, "dmdSec");
}
for (String dmdType : dmdTypes)
{
// If DIM was requested then it was generated above without using
// the crosswalk API. So we can skip this one.
if ("DIM".equals(dmdType))
continue;
DisseminationCrosswalk crosswalk = getDisseminationCrosswalk(dmdType);
if (crosswalk == null)
continue;
String dmdID = getGenericID("dmd_");
// Add our id to the list.
dmdSecIDS.append(" " + dmdID);
// ////////////////////////////////
// Start a new dmdSec for each crosswalk.
attributes = new AttributeMap();
attributes.put("ID", dmdID);
attributes.put("GROUPID", groupID);
startElement(METS,"dmdSec",attributes);
// ////////////////////////////////
// Start metadata wrapper
attributes = new AttributeMap();
if (isDefinedMETStype(dmdType))
{
attributes.put("MDTYPE", dmdType);
}
else
{
attributes.put("MDTYPE", "OTHER");
attributes.put("OTHERMDTYPE", dmdType);
}
startElement(METS,"mdWrap",attributes);
// ////////////////////////////////
// Start the xml data
startElement(METS,"xmlData");
// ///////////////////////////////
// Send the actual XML content
try {
Element dissemination = crosswalk.disseminateElement(dso);
SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces);
// Allow the basics for XML
filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings();
SAXOutputter outputter = new SAXOutputter();
outputter.setContentHandler(filter);
outputter.setLexicalHandler(filter);
outputter.output(dissemination);
}
catch (JDOMException jdome)
{
throw new WingException(jdome);
}
catch (AuthorizeException ae)
{
// just ignore the authorize exception and continue on with
//out parsing the xml document.
}
// ////////////////////////////////
// End elements
endElement(METS,"xmlData");
endElement(METS,"mdWrap");
endElement(METS, "dmdSec");
// Record keeping
if (dmdSecIDS == null)
{
dmdSecIDS = new StringBuffer(dmdID);
}
else
{
dmdSecIDS.append(" " + dmdID);
}
}
}
/**
* Render the METS file section. If a logo is present for this
* container then that single bitstream is listed in the
* file section.
*
* Example:
* <fileSec>
* <fileGrp USE="LOGO">
* <file ... >
* <fLocate ... >
* </file>
* </fileGrp>
* </fileSec>
*/
protected void renderFileSection() throws SAXException
{
AttributeMap attributes;
// Get the Community or Collection logo.
Bitstream logo = getLogo();
if (logo != null)
{
// ////////////////////////////////
// Start the file section
startElement(METS,"fileSec");
// ////////////////////////////////
// Start a new fileGrp for the logo.
attributes = new AttributeMap();
attributes.put("USE", "LOGO");
startElement(METS,"fileGrp",attributes);
// ////////////////////////////////
// Add the actual file element
String fileID = getFileID(logo);
String groupID = getGroupFileID(logo);
renderFile(null, logo, fileID, groupID);
// ////////////////////////////////
// End th file group and file section
endElement(METS,"fileGrp");
endElement(METS,"fileSec");
}
}
/**
* Render the container's structural map. This includes a refrence
* to the container's logo, if available, otherwise it is an empty
* division that just states it is a DSpace community or Collection.
*
* Examlpe:
* <structMap TYPE="LOGICAL" LABEL="DSpace">
* <div TYPE="DSpace Collection" DMDID="space seperated list of ids">
* <fptr FILEID="logo id"/>
* </div>
* </structMap>
*/
protected void renderStructureMap() throws SQLException, SAXException
{
AttributeMap attributes;
// ///////////////////////
// Start a new structure map
attributes = new AttributeMap();
attributes.put("TYPE", "LOGICAL");
attributes.put("LABEL", "DSpace");
startElement(METS,"structMap",attributes);
// ////////////////////////////////
// Start the special first division
attributes = new AttributeMap();
attributes.put("TYPE", getMETSLabel());
// add references to the Descriptive metadata
if (dmdSecIDS != null)
attributes.put("DMDID", dmdSecIDS.toString());
startElement(METS,"div",attributes);
// add a fptr pointer to the logo.
Bitstream logo = getLogo();
if (logo != null)
{
// ////////////////////////////////
// Add a refrence to the logo as the primary bitstream.
attributes = new AttributeMap();
attributes.put("FILEID",getFileID(logo));
startElement(METS,"fptr",attributes);
endElement(METS,"fptr");
// ///////////////////////////////////////////////
// Add a div for the publicaly viewable bitstreams (i.e. the logo)
attributes = new AttributeMap();
attributes.put("ID", getGenericID("div_"));
attributes.put("TYPE", "DSpace Content Bitstream");
startElement(METS,"div",attributes);
// ////////////////////////////////
// Add a refrence to the logo as the primary bitstream.
attributes = new AttributeMap();
attributes.put("FILEID",getFileID(logo));
startElement(METS,"fptr",attributes);
endElement(METS,"fptr");
// //////////////////////////
// End the logo division
endElement(METS,"div");
}
// ////////////////////////////////
// End the special first division
endElement(METS,"div");
// ///////////////////////
// End the structure map
endElement(METS,"structMap");
}
/**
*
*
*
* Private helpfull methods
*
*
*
*/
/**
* Return the logo bitstream associated with this community or collection.
* If there is no logo then null is returned.
*/
private Bitstream getLogo()
{
if (dso instanceof Community)
{
Community community = (Community) dso;
return community.getLogo();
}
else if (dso instanceof Collection)
{
Collection collection = (Collection) dso;
return collection.getLogo();
}
return null;
}
/**
* Count how many occurance there is of the given
* character in the given string.
*
* @param string The string value to be counted.
* @param character the character to count in the string.
*/
private int countOccurances(String string, char character)
{
if (string == null || string.length() == 0)
return 0;
int fromIndex = -1;
int count = 0;
while (true)
{
fromIndex = string.indexOf('>', fromIndex+1);
if (fromIndex == -1)
break;
count++;
}
return count;
}
/**
* Check if the given character sequence is located in the given
* string at the specified index. If it is then return true, otherwise false.
*
* @param string The string to test against
* @param index The location within the string
* @param characters The character sequence to look for.
* @return true if the character sequence was found, otherwise false.
*/
private boolean substringCompare(String string, int index, char ... characters)
{
// Is the string long enough?
if (string.length() <= index + characters.length)
return false;
// Do all the characters match?
for (char character : characters)
{
if (string.charAt(index) != character)
return false;
index++;
}
return false;
}
/**
* Create a new DIM field element with the given attributes.
*
* @param schema The schema the DIM field belongs too.
* @param element The element the DIM field belongs too.
* @param qualifier The qualifier the DIM field belongs too.
* @param language The language the DIM field belongs too.
* @param value The value of the DIM field.
* @return A new DIM field element
* @throws SAXException
*/
private void createField(String schema, String element, String qualifier, String language, String value) throws SAXException
{
// ///////////////////////////////
// Field element for each metadata field.
AttributeMap attributes = new AttributeMap();
attributes.put("mdschema",schema);
attributes.put("element", element);
if (qualifier != null)
attributes.put("qualifier", qualifier);
if (language != null)
attributes.put("language", language);
startElement(DIM,"field",attributes);
// Only try and add the metadata's value, but only if it is non null.
if (value != null)
{
// First, preform a queck check to see if the value may be XML.
int countOpen = countOccurances(value,'<');
int countClose = countOccurances(value, '>');
// If it passed the quick test, then try and parse the value.
Element xmlDocument = null;
if (countOpen > 0 && countOpen == countClose)
{
// This may be XML, First try and remove any bad entity refrences.
int amp = -1;
while ((amp = value.indexOf('&', amp+1)) > -1)
{
// Is it an xml entity named by number?
if (substringCompare(value,amp+1,'#'))
continue;
// &
if (substringCompare(value,amp+1,'a','m','p',';'))
continue;
// '
if (substringCompare(value,amp+1,'a','p','o','s',';'))
continue;
// "
if (substringCompare(value,amp+1,'q','u','o','t',';'))
continue;
// <
if (substringCompare(value,amp+1,'l','t',';'))
continue;
// >
if (substringCompare(value,amp+1,'g','t',';'))
continue;
// Replace the ampersand with an XML entity.
value = value.substring(0,amp) + "&" + value.substring(amp+1);
}
// Second try and parse the XML into a mini-dom
try {
// Wrap the value inside a root element (which will be trimed out
// by the SAX filter and set the default namespace to XHTML.
String xml = "<fragment xmlns=\"http://www.w3.org/1999/xhtml\">"+value+"</fragment>";
ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(inputStream);
xmlDocument = document.getRootElement();
}
catch (Exception e)
{
// ignore any errors we get, and just add the string literaly.
}
}
// Third, If we have xml, attempt to serialize the dom.
if (xmlDocument != null)
{
SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces);
// Allow the basics for XML
filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings();
// Special option, only allow elements below the second level to pass through. This
// will trim out the METS declaration and only leave the actual METS parts to be
// included.
filter.allowElements(1);
SAXOutputter outputter = new SAXOutputter();
outputter.setContentHandler(filter);
outputter.setLexicalHandler(filter);
try {
outputter.output(xmlDocument);
}
catch (JDOMException jdome)
{
// serialization failed so let's just fallback sending the plain characters.
sendCharacters(value);
}
}
else
{
// We don't have XML, so just send the plain old characters.
sendCharacters(value);
}
}
// //////////////////////////////
// Close out field
endElement(DIM,"field");
}
}
| false | true | protected void renderDescriptiveSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException
{
AttributeMap attributes;
String groupID = getGenericID("group_dmd_");
dmdSecIDS = new StringBuffer();
// Add DIM descriptive metadata if it was requested or if no metadata types
// were specified. Further more since this is the default type we also use a
// faster rendering method that the crosswalk API.
if(dmdTypes.size() == 0 || dmdTypes.contains("DIM"))
{
// Metadata element's ID
String dmdID = getGenericID("dmd_");
// Keep track of all descriptive sections
dmdSecIDS.append(dmdID);
// ////////////////////////////////
// Start a new dmdSec for each crosswalk.
attributes = new AttributeMap();
attributes.put("ID", dmdID);
attributes.put("GROUPID", groupID);
startElement(METS,"dmdSec",attributes);
// ////////////////////////////////
// Start metadata wrapper
attributes = new AttributeMap();
attributes.put("MDTYPE", "OTHER");
attributes.put("OTHERMDTYPE", "DIM");
startElement(METS,"mdWrap",attributes);
// ////////////////////////////////
// Start the xml data
startElement(METS,"xmlData");
// ///////////////////////////////
// Start the DIM element
attributes = new AttributeMap();
attributes.put("dspaceType", Constants.typeText[dso.getType()]);
startElement(DIM,"dim",attributes);
// Add each field for this collection
if (dso.getType() == Constants.COLLECTION)
{
Collection collection = (Collection) dso;
String description = collection.getMetadata("introductory_text");
String description_abstract = collection.getMetadata("short_description");
String description_table = collection.getMetadata("side_bar_text");
String identifier_uri = "http://hdl.handle.net/" + collection.getHandle();
String provenance = collection.getMetadata("provenance_description");
String rights = collection.getMetadata("copyright_text");
String rights_license = collection.getMetadata("license");
String title = collection.getMetadata("name");
createField("dc","description",null,null,description);
createField("dc","description","abstract",null,description_abstract);
createField("dc","description","tableofcontents",null,description_table);
createField("dc","identifier","uri",null,identifier_uri);
createField("dc","provenance",null,null,provenance);
createField("dc","rights",null,null,rights);
createField("dc","rights","license",null,rights_license);
createField("dc","title",null,null,title);
boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache");
//To improve scalability, XMLUI only adds item counts if they are cached
if (useCache)
{
try
{ //try to determine Collection size (i.e. # of items)
int size = new ItemCounter(this.dspaceContext).getCount(collection);
createField("dc","format","extent",null, String.valueOf(size));
}
catch(ItemCountException e)
{
throw new IOException("Could not obtain Collection item-count: ", e);
}
}
}
else if (dso.getType() == Constants.COMMUNITY)
{
Community community = (Community) dso;
String description = community.getMetadata("introductory_text");
String description_abstract = community.getMetadata("short_description");
String description_table = community.getMetadata("side_bar_text");
String identifier_uri = "http://hdl.handle.net/" + community.getHandle();
String rights = community.getMetadata("copyright_text");
String title = community.getMetadata("name");
createField("dc","description",null,null,description);
createField("dc","description","abstract",null,description_abstract);
createField("dc","description","tableofcontents",null,description_table);
createField("dc","identifier","uri",null,identifier_uri);
createField("dc","rights",null,null,rights);
createField("dc","title",null,null,title);
boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache");
//To improve scalability, XMLUI only adds item counts if they are cached
if (useCache)
{
try
{ //try to determine Community size (i.e. # of items)
int size = new ItemCounter(this.dspaceContext).getCount(community);
createField("dc","format","extent",null, String.valueOf(size));
}
catch(ItemCountException e)
{
throw new IOException("Could not obtain Community item-count: ", e);
}
}
}
// ///////////////////////////////
// End the DIM element
endElement(DIM,"dim");
// ////////////////////////////////
// End elements
endElement(METS,"xmlData");
endElement(METS,"mdWrap");
endElement(METS, "dmdSec");
}
for (String dmdType : dmdTypes)
{
// If DIM was requested then it was generated above without using
// the crosswalk API. So we can skip this one.
if ("DIM".equals(dmdType))
continue;
DisseminationCrosswalk crosswalk = getDisseminationCrosswalk(dmdType);
if (crosswalk == null)
continue;
String dmdID = getGenericID("dmd_");
// Add our id to the list.
dmdSecIDS.append(" " + dmdID);
// ////////////////////////////////
// Start a new dmdSec for each crosswalk.
attributes = new AttributeMap();
attributes.put("ID", dmdID);
attributes.put("GROUPID", groupID);
startElement(METS,"dmdSec",attributes);
// ////////////////////////////////
// Start metadata wrapper
attributes = new AttributeMap();
if (isDefinedMETStype(dmdType))
{
attributes.put("MDTYPE", dmdType);
}
else
{
attributes.put("MDTYPE", "OTHER");
attributes.put("OTHERMDTYPE", dmdType);
}
startElement(METS,"mdWrap",attributes);
// ////////////////////////////////
// Start the xml data
startElement(METS,"xmlData");
// ///////////////////////////////
// Send the actual XML content
try {
Element dissemination = crosswalk.disseminateElement(dso);
SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces);
// Allow the basics for XML
filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings();
SAXOutputter outputter = new SAXOutputter();
outputter.setContentHandler(filter);
outputter.setLexicalHandler(filter);
outputter.output(dissemination);
}
catch (JDOMException jdome)
{
throw new WingException(jdome);
}
catch (AuthorizeException ae)
{
// just ignore the authorize exception and continue on with
//out parsing the xml document.
}
// ////////////////////////////////
// End elements
endElement(METS,"xmlData");
endElement(METS,"mdWrap");
endElement(METS, "dmdSec");
// Record keeping
if (dmdSecIDS == null)
{
dmdSecIDS = new StringBuffer(dmdID);
}
else
{
dmdSecIDS.append(" " + dmdID);
}
}
}
| protected void renderDescriptiveSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException
{
AttributeMap attributes;
String groupID = getGenericID("group_dmd_");
dmdSecIDS = new StringBuffer();
// Add DIM descriptive metadata if it was requested or if no metadata types
// were specified. Further more since this is the default type we also use a
// faster rendering method that the crosswalk API.
if(dmdTypes.size() == 0 || dmdTypes.contains("DIM"))
{
// Metadata element's ID
String dmdID = getGenericID("dmd_");
// Keep track of all descriptive sections
dmdSecIDS.append(dmdID);
// ////////////////////////////////
// Start a new dmdSec for each crosswalk.
attributes = new AttributeMap();
attributes.put("ID", dmdID);
attributes.put("GROUPID", groupID);
startElement(METS,"dmdSec",attributes);
// ////////////////////////////////
// Start metadata wrapper
attributes = new AttributeMap();
attributes.put("MDTYPE", "OTHER");
attributes.put("OTHERMDTYPE", "DIM");
startElement(METS,"mdWrap",attributes);
// ////////////////////////////////
// Start the xml data
startElement(METS,"xmlData");
// ///////////////////////////////
// Start the DIM element
attributes = new AttributeMap();
attributes.put("dspaceType", Constants.typeText[dso.getType()]);
startElement(DIM,"dim",attributes);
// Add each field for this collection
if (dso.getType() == Constants.COLLECTION)
{
Collection collection = (Collection) dso;
String description = collection.getMetadata("introductory_text");
String description_abstract = collection.getMetadata("short_description");
String description_table = collection.getMetadata("side_bar_text");
String identifier_uri = "http://hdl.handle.net/" + collection.getHandle();
String provenance = collection.getMetadata("provenance_description");
String rights = collection.getMetadata("copyright_text");
String rights_license = collection.getMetadata("license");
String title = collection.getMetadata("name");
createField("dc","description",null,null,description);
createField("dc","description","abstract",null,description_abstract);
createField("dc","description","tableofcontents",null,description_table);
createField("dc","identifier","uri",null,identifier_uri);
createField("dc","provenance",null,null,provenance);
createField("dc","rights",null,null,rights);
createField("dc","rights","license",null,rights_license);
createField("dc","title",null,null,title);
boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache");
//To improve scalability, XMLUI only adds item counts if they are cached
if (useCache)
{
try
{ //try to determine Collection size (i.e. # of items)
int size = new ItemCounter(this.dspaceContext).getCount(collection);
createField("dc","format","extent",null, String.valueOf(size));
}
catch(ItemCountException e)
{
IOException ioe = new IOException("Could not obtain Collection item-count");
ioe.initCause(e);
throw ioe;
}
}
}
else if (dso.getType() == Constants.COMMUNITY)
{
Community community = (Community) dso;
String description = community.getMetadata("introductory_text");
String description_abstract = community.getMetadata("short_description");
String description_table = community.getMetadata("side_bar_text");
String identifier_uri = "http://hdl.handle.net/" + community.getHandle();
String rights = community.getMetadata("copyright_text");
String title = community.getMetadata("name");
createField("dc","description",null,null,description);
createField("dc","description","abstract",null,description_abstract);
createField("dc","description","tableofcontents",null,description_table);
createField("dc","identifier","uri",null,identifier_uri);
createField("dc","rights",null,null,rights);
createField("dc","title",null,null,title);
boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache");
//To improve scalability, XMLUI only adds item counts if they are cached
if (useCache)
{
try
{ //try to determine Community size (i.e. # of items)
int size = new ItemCounter(this.dspaceContext).getCount(community);
createField("dc","format","extent",null, String.valueOf(size));
}
catch(ItemCountException e)
{
IOException ioe = new IOException("Could not obtain Collection item-count");
ioe.initCause(e);
throw ioe;
}
}
}
// ///////////////////////////////
// End the DIM element
endElement(DIM,"dim");
// ////////////////////////////////
// End elements
endElement(METS,"xmlData");
endElement(METS,"mdWrap");
endElement(METS, "dmdSec");
}
for (String dmdType : dmdTypes)
{
// If DIM was requested then it was generated above without using
// the crosswalk API. So we can skip this one.
if ("DIM".equals(dmdType))
continue;
DisseminationCrosswalk crosswalk = getDisseminationCrosswalk(dmdType);
if (crosswalk == null)
continue;
String dmdID = getGenericID("dmd_");
// Add our id to the list.
dmdSecIDS.append(" " + dmdID);
// ////////////////////////////////
// Start a new dmdSec for each crosswalk.
attributes = new AttributeMap();
attributes.put("ID", dmdID);
attributes.put("GROUPID", groupID);
startElement(METS,"dmdSec",attributes);
// ////////////////////////////////
// Start metadata wrapper
attributes = new AttributeMap();
if (isDefinedMETStype(dmdType))
{
attributes.put("MDTYPE", dmdType);
}
else
{
attributes.put("MDTYPE", "OTHER");
attributes.put("OTHERMDTYPE", dmdType);
}
startElement(METS,"mdWrap",attributes);
// ////////////////////////////////
// Start the xml data
startElement(METS,"xmlData");
// ///////////////////////////////
// Send the actual XML content
try {
Element dissemination = crosswalk.disseminateElement(dso);
SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces);
// Allow the basics for XML
filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings();
SAXOutputter outputter = new SAXOutputter();
outputter.setContentHandler(filter);
outputter.setLexicalHandler(filter);
outputter.output(dissemination);
}
catch (JDOMException jdome)
{
throw new WingException(jdome);
}
catch (AuthorizeException ae)
{
// just ignore the authorize exception and continue on with
//out parsing the xml document.
}
// ////////////////////////////////
// End elements
endElement(METS,"xmlData");
endElement(METS,"mdWrap");
endElement(METS, "dmdSec");
// Record keeping
if (dmdSecIDS == null)
{
dmdSecIDS = new StringBuffer(dmdID);
}
else
{
dmdSecIDS.append(" " + dmdID);
}
}
}
|