lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
4dd6ddac10e780fb90a294541efdb4d2c0fcbc6c
0
3dcitydb/importer-exporter,3dcitydb/importer-exporter,3dcitydb/importer-exporter
package org.citydb.query.builder.sql; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.citydb.database.adapter.AbstractSQLAdapter; import org.citydb.database.schema.mapping.AbstractJoin; import org.citydb.database.schema.mapping.AbstractProperty; import org.citydb.database.schema.mapping.AbstractType; import org.citydb.database.schema.mapping.AbstractTypeProperty; import org.citydb.database.schema.mapping.ComplexAttribute; import org.citydb.database.schema.mapping.Condition; import org.citydb.database.schema.mapping.Join; import org.citydb.database.schema.mapping.JoinTable; import org.citydb.database.schema.mapping.MappingConstants; import org.citydb.database.schema.mapping.PathElementType; import org.citydb.database.schema.mapping.SimpleAttribute; import org.citydb.database.schema.path.InvalidSchemaPathException; import org.citydb.database.schema.path.SchemaPath; import org.citydb.query.builder.QueryBuildException; import org.citydb.query.filter.selection.expression.AbstractLiteral; import org.citydb.query.filter.selection.expression.Expression; import org.citydb.query.filter.selection.expression.ExpressionName; import org.citydb.query.filter.selection.expression.LiteralType; import org.citydb.query.filter.selection.expression.StringLiteral; import org.citydb.query.filter.selection.expression.TimestampLiteral; import org.citydb.query.filter.selection.expression.ValueReference; import org.citydb.query.filter.selection.operator.comparison.AbstractComparisonOperator; import org.citydb.query.filter.selection.operator.comparison.BetweenOperator; import org.citydb.query.filter.selection.operator.comparison.BinaryComparisonOperator; import org.citydb.query.filter.selection.operator.comparison.ComparisonOperatorName; import org.citydb.query.filter.selection.operator.comparison.LikeOperator; import org.citydb.query.filter.selection.operator.comparison.NullOperator; import org.citydb.sqlbuilder.expression.AbstractSQLLiteral; import org.citydb.sqlbuilder.expression.PlaceHolder; import org.citydb.sqlbuilder.schema.Table; import org.citydb.sqlbuilder.select.PredicateToken; import org.citydb.sqlbuilder.select.Select; import org.citydb.sqlbuilder.select.operator.comparison.ComparisonFactory; import org.citydb.sqlbuilder.select.operator.logical.LogicalOperationFactory; import org.citydb.sqlbuilder.select.projection.ConstantColumn; import org.citydb.sqlbuilder.select.projection.Function; public class ComparisonOperatorBuilder { private final SchemaPathBuilder schemaPathBuilder; private final AbstractSQLAdapter sqlAdapter; private final Set<Integer> objectclassIds; private final String schemaName; protected ComparisonOperatorBuilder(SchemaPathBuilder schemaPathBuilder, Set<Integer> objectclassIds, AbstractSQLAdapter sqlAdapter, String schemaName) { this.schemaPathBuilder = schemaPathBuilder; this.objectclassIds = objectclassIds; this.sqlAdapter = sqlAdapter; this.schemaName = schemaName; } protected SQLQueryContext buildComparisonOperator(AbstractComparisonOperator operator, boolean negate) throws QueryBuildException { SQLQueryContext queryContext = null; switch (operator.getOperatorName()) { case EQUAL_TO: case NOT_EQUAL_TO: case LESS_THAN: case GREATER_THAN: case LESS_THAN_OR_EQUAL_TO: case GREATER_THAN_OR_EQUAL_TO: queryContext = buildBinaryOperator((BinaryComparisonOperator)operator, negate); break; case BETWEEN: queryContext = buildBetweenOperator((BetweenOperator)operator, negate); break; case LIKE: queryContext = buildLikeOperator((LikeOperator)operator, negate); break; case NULL: queryContext = buildNullComparison((NullOperator)operator, negate); break; } return queryContext; } private SQLQueryContext buildBinaryOperator(BinaryComparisonOperator operator, boolean negate) throws QueryBuildException { if (!ComparisonOperatorName.BINARY_COMPARISONS.contains(operator.getOperatorName())) throw new QueryBuildException(operator + " is not a binary comparison operator."); if (!operator.isSetLeftOperand() || !operator.isSetRightOperand()) throw new QueryBuildException("Only one operand found for binary comparison operator."); // we currently only support a combination of ValueReference and Literal as operands ValueReference valueReference = null; AbstractLiteral<?> literal = null; for (Expression expression : operator.getOperands()) { switch (expression.getExpressionName()) { case VALUE_REFERENCE: valueReference = (ValueReference)expression; break; case LITERAL: literal = (AbstractLiteral<?>)expression; break; case FUNCTION: break; } } if (valueReference == null || literal == null) throw new QueryBuildException("Only combinations of ValueReference and Literal are supported as operands of a binary comparison operator."); // build the value reference SQLQueryContext queryContext = schemaPathBuilder.buildSchemaPath(valueReference.getSchemaPath(), objectclassIds, operator.isMatchCase()); // check for type mismatch of literal SimpleAttribute attribute = (SimpleAttribute)valueReference.getTarget(); if (!literal.evalutesToSchemaType(attribute.getType())) throw new QueryBuildException("Type mismatch between provided literal and database representation."); // map operands org.citydb.sqlbuilder.expression.Expression rightOperand = literal.convertToSQLPlaceHolder(); org.citydb.sqlbuilder.expression.Expression leftOperand = queryContext.targetColumn; // consider match case if (!operator.isMatchCase() && ((PlaceHolder<?>)rightOperand).getValue() instanceof String) { rightOperand = new Function(sqlAdapter.resolveDatabaseOperationName("string.upper"), rightOperand); leftOperand = new Function(sqlAdapter.resolveDatabaseOperationName("string.upper"), leftOperand); } // implicit conversion from timestamp to date if (literal.getLiteralType() == LiteralType.TIMESTAMP && ((TimestampLiteral)literal).isDate()) leftOperand = new Function(sqlAdapter.resolveDatabaseOperationName("timestamp.to_date"), leftOperand); // finally, create equivalent sql operation switch (operator.getOperatorName()) { case EQUAL_TO: queryContext.select.addSelection(ComparisonFactory.equalTo(leftOperand, rightOperand, negate)); break; case NOT_EQUAL_TO: queryContext.select.addSelection(ComparisonFactory.notEqualTo(leftOperand, rightOperand, negate)); break; case LESS_THAN: queryContext.select.addSelection(ComparisonFactory.lessThan(leftOperand, rightOperand, negate)); break; case GREATER_THAN: queryContext.select.addSelection(ComparisonFactory.greaterThan(leftOperand, rightOperand, negate)); break; case LESS_THAN_OR_EQUAL_TO: queryContext.select.addSelection(ComparisonFactory.lessThanOrEqualTo(leftOperand, rightOperand, negate)); break; case GREATER_THAN_OR_EQUAL_TO: queryContext.select.addSelection(ComparisonFactory.greaterThanOrEqual(leftOperand, rightOperand, negate)); break; default: break; } return queryContext; } private SQLQueryContext buildBetweenOperator(BetweenOperator operator, boolean negate) throws QueryBuildException { if (operator.getOperand().getExpressionName() != ExpressionName.VALUE_REFERENCE) throw new QueryBuildException("Only ValueRefernce is supported as operand of a between operator."); if (operator.getLowerBoundary().getExpressionName() != ExpressionName.LITERAL || operator.getUpperBoundary().getExpressionName() != ExpressionName.LITERAL) throw new QueryBuildException("Only Literal values are supported as lower and upper boundary of a between operator."); ValueReference valueReference = (ValueReference)operator.getOperand(); AbstractLiteral<?> lowerBoundary = (AbstractLiteral<?>)operator.getLowerBoundary(); AbstractLiteral<?> upperBoundary = (AbstractLiteral<?>)operator.getUpperBoundary(); // build the value reference SQLQueryContext queryContext = schemaPathBuilder.buildSchemaPath(valueReference.getSchemaPath(), objectclassIds); // check for type mismatch of literal SimpleAttribute attribute = (SimpleAttribute)valueReference.getTarget(); if (!lowerBoundary.evalutesToSchemaType(attribute.getType())) throw new QueryBuildException("Type mismatch between provided lower boundary literal and database representation."); // check for type mismatch of literal if (!upperBoundary.evalutesToSchemaType(attribute.getType())) throw new QueryBuildException("Type mismatch between provided upper boundary literal and database representation."); // map operands PlaceHolder<?> lowerBoundaryLiteral = lowerBoundary.convertToSQLPlaceHolder(); PlaceHolder<?> upperBoundaryLiteral = upperBoundary.convertToSQLPlaceHolder(); // finally, create equivalent sql operation queryContext.select.addSelection(ComparisonFactory.between(queryContext.targetColumn, lowerBoundaryLiteral, upperBoundaryLiteral, negate)); return queryContext; } private SQLQueryContext buildLikeOperator(LikeOperator operator, boolean negate) throws QueryBuildException { if (!operator.isSetLeftOperand() || !operator.isSetRightOperand()) throw new QueryBuildException("Only one operand found for like comparison operator."); // we currently only support a combination of ValueReference and Literal as operands ValueReference valueReference = null; StringLiteral literal = null; for (Expression expression : operator.getOperands()) { switch (expression.getExpressionName()) { case VALUE_REFERENCE: valueReference = (ValueReference)expression; break; case LITERAL: // we only support string literals if (((AbstractLiteral<?>)expression).getLiteralType() != LiteralType.STRING) throw new QueryBuildException("Only string literals are supported for a like operator."); literal = (StringLiteral)expression; break; case FUNCTION: break; } } if (valueReference == null || literal == null) throw new QueryBuildException("Only combinations of ValueReference and Literal are supported as operands of a like operator."); // build the value reference SQLQueryContext queryContext = schemaPathBuilder.buildSchemaPath(valueReference.getSchemaPath(), objectclassIds, operator.isMatchCase()); // check for type mismatch of literal SimpleAttribute attribute = (SimpleAttribute)valueReference.getTarget(); if (!literal.evalutesToSchemaType(attribute.getType())) throw new QueryBuildException("Type mismatch between provided literal and database representation."); // check wildcard and escape characters String wildCard = operator.getWildCard(); String singleCharacter = operator.getSingleCharacter(); String escapeCharacter = operator.getEscapeCharacter(); if (wildCard == null || wildCard.length() > 1) throw new QueryBuildException("Wildcards must be defined by a single character."); if (singleCharacter == null || singleCharacter.length() > 1) throw new QueryBuildException("Wildcards must be defined by a single character."); if (escapeCharacter == null || escapeCharacter.length() > 1) throw new QueryBuildException("An escape character must be defined by a single character."); // replace wild cards String value = replaceWildCards(literal.getValue(), wildCard.charAt(0), singleCharacter.charAt(0), escapeCharacter.charAt(0)); // map operands org.citydb.sqlbuilder.expression.Expression rightOperand = new PlaceHolder<>(value); org.citydb.sqlbuilder.expression.Expression leftOperand = queryContext.targetColumn; // consider match case if (!operator.isMatchCase()) { rightOperand = new Function(sqlAdapter.resolveDatabaseOperationName("string.upper"), rightOperand); leftOperand = new Function(sqlAdapter.resolveDatabaseOperationName("string.upper"), leftOperand); } // finally, create equivalent sql operation queryContext.select.addSelection(ComparisonFactory.like(leftOperand, rightOperand, value.contains(escapeCharacter) ? new org.citydb.sqlbuilder.expression.StringLiteral(escapeCharacter) : null, negate)); return queryContext; } private SQLQueryContext buildNullComparison(NullOperator operator, boolean negate) throws QueryBuildException { if (operator.getOperand().getExpressionName() != ExpressionName.VALUE_REFERENCE) throw new QueryBuildException("Only ValueRefernce is supported as operand of a null operator."); ValueReference valueReference = (ValueReference)operator.getOperand(); // create a copy of the schema path and create an is null check // the schema path might be changed by this operation SchemaPath schemaPath = valueReference.getSchemaPath().copy(); PredicateToken token = buildIsNullPredicate((AbstractProperty)valueReference.getTarget(), schemaPath, negate); // finally, create equivalent sql operation SQLQueryContext queryContext = schemaPathBuilder.buildSchemaPath(schemaPath, objectclassIds); queryContext.select.addSelection(token); return queryContext; } private PredicateToken buildIsNullPredicate(AbstractProperty property, SchemaPath schemaPath, boolean negate) throws QueryBuildException { if (property.getElementType() == PathElementType.SIMPLE_ATTRIBUTE || property.getElementType() == PathElementType.GEOMETRY_PROPERTY) { // for simple properties, we just check whether the column is null SQLQueryContext queryContext = schemaPathBuilder.buildSchemaPath(schemaPath, objectclassIds); return ComparisonFactory.isNull(queryContext.targetColumn, negate); } else if (property.getElementType() == PathElementType.COMPLEX_ATTRIBUTE || PathElementType.TYPE_PROPERTIES.contains(property.getElementType())) { AbstractJoin abstractJoin = property.getJoin(); if (abstractJoin != null) { // for complex properties that involve a join, we check whether // there is no foreign key reference from the join table to the target table. // we therefore remove the complex property from the schema // path and create an exists clause schemaPath.removeLastPathElement(); SQLQueryContext queryContext = schemaPathBuilder.buildSchemaPath(schemaPath, objectclassIds); // derive join information String toTable; String toColumn; String fromColumn; List<Condition> conditions; if (abstractJoin instanceof Join) { Join join = (Join)abstractJoin; toTable = join.getTable(); toColumn = join.getToColumn(); fromColumn = join.getFromColumn(); conditions = join.getConditions(); } else if (abstractJoin instanceof JoinTable) { JoinTable joinTable = (JoinTable)abstractJoin; toTable = joinTable.getTable(); Join join = joinTable.getJoin(); toColumn = join.getFromColumn(); fromColumn = join.getToColumn(); conditions = join.getConditions(); } else throw new QueryBuildException("Failed to build null operator for property '" + property + "'."); // create select based on join information Table table = new Table(toTable, schemaName, schemaPathBuilder.geAliasGenerator()); Select select = new Select() .addProjection(new ConstantColumn(1).withFromTable(table)) .addSelection(ComparisonFactory.equalTo(table.getColumn(toColumn), queryContext.toTable.getColumn(fromColumn))); // add join conditions if required if (conditions != null) { for (Condition condition : conditions) { String value = condition.getValue(); // we can skip this token since we do not care about the referenced object type if (value.equals(MappingConstants.TARGET_OBJECTCLASS_ID_TOKEN)) continue; else if (value.equals(MappingConstants.TARGET_ID_TOKEN)) { select.addSelection(ComparisonFactory.equalTo(table.getColumn(condition.getColumn()), table.getColumn(MappingConstants.ID))); continue; } AbstractSQLLiteral<?> literal = schemaPathBuilder.convertToSQLLiteral(value, condition.getType()); select.addSelection(ComparisonFactory.equalTo(table.getColumn(condition.getColumn()), literal)); } } // finally, create exists clause from select return ComparisonFactory.exists(select, !negate); } else { try { // if we deal with a complex property without a join, then we have // found a type whose properties are stored inline the same table. // checking whether the complex property is null therefore requires checking // whether all its properties are null. List<? extends AbstractProperty> innerProperties; if (property.getElementType() == PathElementType.COMPLEX_ATTRIBUTE) { innerProperties = ((ComplexAttribute)property).getType().getAttributes(); } else { AbstractType<?> type = ((AbstractTypeProperty<?>)property).getType(); innerProperties = type.getProperties(); // add the inline object or data type to the schema path schemaPath.appendChild(type); } // we iterate over all type properties and recursively create // an is null check predicate using copies of the schema path List<PredicateToken> tokens = new ArrayList<>(); for (AbstractProperty innerProperty : innerProperties) { SchemaPath innerPath = schemaPath.copy(); innerPath.appendChild(innerProperty); tokens.add(buildIsNullPredicate(innerProperty, innerPath, negate)); } return LogicalOperationFactory.AND(tokens); } catch (InvalidSchemaPathException e) { // } } } throw new QueryBuildException("Failed to build null operator for property '" + property + "'."); } private String replaceWildCards(String value, char wildCard, char singleChar, char escapeChar) { boolean escapeSQLWildCard = wildCard != '%' && singleChar != '%'; boolean espaceSQLSingleChar = wildCard != '_' && singleChar != '_'; StringBuilder tmp = new StringBuilder(); for (int offset = 0; offset < value.length(); offset++) { char ch = value.charAt(offset); if (ch == escapeChar) { // keep escaped chars as is tmp.append(ch); if (++offset < value.length()) tmp.append(value.charAt(offset)); } else if ((ch == '%' && escapeSQLWildCard) || (ch == '_' && espaceSQLSingleChar)) { // escape SQL wild cards tmp.append(escapeChar); tmp.append(ch); } else if (ch == wildCard) { // replace user-defined wild card tmp.append('%'); } else if (ch == singleChar) { // replace user-defined single char tmp.append('_'); } else tmp.append(ch); } return tmp.toString(); } }
impexp-core/src/main/java/org/citydb/query/builder/sql/ComparisonOperatorBuilder.java
package org.citydb.query.builder.sql; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.citydb.database.adapter.AbstractSQLAdapter; import org.citydb.database.schema.mapping.AbstractJoin; import org.citydb.database.schema.mapping.AbstractProperty; import org.citydb.database.schema.mapping.AbstractType; import org.citydb.database.schema.mapping.AbstractTypeProperty; import org.citydb.database.schema.mapping.ComplexAttribute; import org.citydb.database.schema.mapping.Condition; import org.citydb.database.schema.mapping.Join; import org.citydb.database.schema.mapping.JoinTable; import org.citydb.database.schema.mapping.MappingConstants; import org.citydb.database.schema.mapping.PathElementType; import org.citydb.database.schema.mapping.SimpleAttribute; import org.citydb.database.schema.path.InvalidSchemaPathException; import org.citydb.database.schema.path.SchemaPath; import org.citydb.query.builder.QueryBuildException; import org.citydb.query.filter.selection.expression.AbstractLiteral; import org.citydb.query.filter.selection.expression.Expression; import org.citydb.query.filter.selection.expression.ExpressionName; import org.citydb.query.filter.selection.expression.LiteralType; import org.citydb.query.filter.selection.expression.StringLiteral; import org.citydb.query.filter.selection.expression.TimestampLiteral; import org.citydb.query.filter.selection.expression.ValueReference; import org.citydb.query.filter.selection.operator.comparison.AbstractComparisonOperator; import org.citydb.query.filter.selection.operator.comparison.BetweenOperator; import org.citydb.query.filter.selection.operator.comparison.BinaryComparisonOperator; import org.citydb.query.filter.selection.operator.comparison.ComparisonOperatorName; import org.citydb.query.filter.selection.operator.comparison.LikeOperator; import org.citydb.query.filter.selection.operator.comparison.NullOperator; import org.citydb.sqlbuilder.expression.AbstractSQLLiteral; import org.citydb.sqlbuilder.expression.PlaceHolder; import org.citydb.sqlbuilder.schema.Table; import org.citydb.sqlbuilder.select.PredicateToken; import org.citydb.sqlbuilder.select.Select; import org.citydb.sqlbuilder.select.operator.comparison.ComparisonFactory; import org.citydb.sqlbuilder.select.operator.logical.LogicalOperationFactory; import org.citydb.sqlbuilder.select.projection.ConstantColumn; import org.citydb.sqlbuilder.select.projection.Function; public class ComparisonOperatorBuilder { private final SchemaPathBuilder schemaPathBuilder; private final AbstractSQLAdapter sqlAdapter; private final Set<Integer> objectclassIds; private final String schemaName; protected ComparisonOperatorBuilder(SchemaPathBuilder schemaPathBuilder, Set<Integer> objectclassIds, AbstractSQLAdapter sqlAdapter, String schemaName) { this.schemaPathBuilder = schemaPathBuilder; this.objectclassIds = objectclassIds; this.sqlAdapter = sqlAdapter; this.schemaName = schemaName; } protected SQLQueryContext buildComparisonOperator(AbstractComparisonOperator operator, boolean negate) throws QueryBuildException { SQLQueryContext queryContext = null; switch (operator.getOperatorName()) { case EQUAL_TO: case NOT_EQUAL_TO: case LESS_THAN: case GREATER_THAN: case LESS_THAN_OR_EQUAL_TO: case GREATER_THAN_OR_EQUAL_TO: queryContext = buildBinaryOperator((BinaryComparisonOperator)operator, negate); break; case BETWEEN: queryContext = buildBetweenOperator((BetweenOperator)operator, negate); break; case LIKE: queryContext = buildLikeOperator((LikeOperator)operator, negate); break; case NULL: queryContext = buildNullComparison((NullOperator)operator, negate); break; } return queryContext; } private SQLQueryContext buildBinaryOperator(BinaryComparisonOperator operator, boolean negate) throws QueryBuildException { if (!ComparisonOperatorName.BINARY_COMPARISONS.contains(operator.getOperatorName())) throw new QueryBuildException(operator + " is not a binary comparison operator."); if (!operator.isSetLeftOperand() || !operator.isSetRightOperand()) throw new QueryBuildException("Only one operand found for binary comparison operator."); // we currently only support a combination of ValueReference and Literal as operands ValueReference valueReference = null; AbstractLiteral<?> literal = null; for (Expression expression : operator.getOperands()) { switch (expression.getExpressionName()) { case VALUE_REFERENCE: valueReference = (ValueReference)expression; break; case LITERAL: literal = (AbstractLiteral<?>)expression; break; case FUNCTION: break; } } if (valueReference == null || literal == null) throw new QueryBuildException("Only combinations of ValueReference and Literal are supported as operands of a binary comparison operator."); // build the value reference SQLQueryContext queryContext = schemaPathBuilder.buildSchemaPath(valueReference.getSchemaPath(), objectclassIds, operator.isMatchCase()); // check for type mismatch of literal SimpleAttribute attribute = (SimpleAttribute)valueReference.getTarget(); if (!literal.evalutesToSchemaType(attribute.getType())) throw new QueryBuildException("Type mismatch between provided literal and database representation."); // map operands org.citydb.sqlbuilder.expression.Expression rightOperand = literal.convertToSQLPlaceHolder(); org.citydb.sqlbuilder.expression.Expression leftOperand = queryContext.targetColumn; // consider match case if (!operator.isMatchCase() && ((PlaceHolder<?>)rightOperand).getValue() instanceof String) { rightOperand = new Function(sqlAdapter.resolveDatabaseOperationName("string.upper"), rightOperand); leftOperand = new Function(sqlAdapter.resolveDatabaseOperationName("string.upper"), leftOperand); } // implicit conversion from timestamp to date if (literal.getLiteralType() == LiteralType.TIMESTAMP && ((TimestampLiteral)literal).isDate()) leftOperand = new Function(sqlAdapter.resolveDatabaseOperationName("timestamp.to_date"), leftOperand); // finally, create equivalent sql operation switch (operator.getOperatorName()) { case EQUAL_TO: queryContext.select.addSelection(ComparisonFactory.equalTo(leftOperand, rightOperand, negate)); break; case NOT_EQUAL_TO: queryContext.select.addSelection(ComparisonFactory.notEqualTo(leftOperand, rightOperand, negate)); break; case LESS_THAN: queryContext.select.addSelection(ComparisonFactory.lessThan(leftOperand, rightOperand, negate)); break; case GREATER_THAN: queryContext.select.addSelection(ComparisonFactory.greaterThan(leftOperand, rightOperand, negate)); break; case LESS_THAN_OR_EQUAL_TO: queryContext.select.addSelection(ComparisonFactory.lessThanOrEqualTo(leftOperand, rightOperand, negate)); break; case GREATER_THAN_OR_EQUAL_TO: queryContext.select.addSelection(ComparisonFactory.greaterThanOrEqual(leftOperand, rightOperand, negate)); break; default: break; } return queryContext; } private SQLQueryContext buildBetweenOperator(BetweenOperator operator, boolean negate) throws QueryBuildException { if (operator.getOperand().getExpressionName() != ExpressionName.VALUE_REFERENCE) throw new QueryBuildException("Only ValueRefernce is supported as operand of a between operator."); if (operator.getLowerBoundary().getExpressionName() != ExpressionName.LITERAL || operator.getUpperBoundary().getExpressionName() != ExpressionName.LITERAL) throw new QueryBuildException("Only Literal values are supported as lower and upper boundary of a between operator."); ValueReference valueReference = (ValueReference)operator.getOperand(); AbstractLiteral<?> lowerBoundary = (AbstractLiteral<?>)operator.getLowerBoundary(); AbstractLiteral<?> upperBoundary = (AbstractLiteral<?>)operator.getUpperBoundary(); // build the value reference SQLQueryContext queryContext = schemaPathBuilder.buildSchemaPath(valueReference.getSchemaPath(), objectclassIds); // check for type mismatch of literal SimpleAttribute attribute = (SimpleAttribute)valueReference.getTarget(); if (!lowerBoundary.evalutesToSchemaType(attribute.getType())) throw new QueryBuildException("Type mismatch between provided lower boundary literal and database representation."); // check for type mismatch of literal if (!upperBoundary.evalutesToSchemaType(attribute.getType())) throw new QueryBuildException("Type mismatch between provided upper boundary literal and database representation."); // map operands PlaceHolder<?> lowerBoundaryLiteral = lowerBoundary.convertToSQLPlaceHolder(); PlaceHolder<?> upperBoundaryLiteral = upperBoundary.convertToSQLPlaceHolder(); // finally, create equivalent sql operation queryContext.select.addSelection(ComparisonFactory.between(queryContext.targetColumn, lowerBoundaryLiteral, upperBoundaryLiteral, negate)); return queryContext; } private SQLQueryContext buildLikeOperator(LikeOperator operator, boolean negate) throws QueryBuildException { if (!operator.isSetLeftOperand() || !operator.isSetRightOperand()) throw new QueryBuildException("Only one operand found for like comparison operator."); // we currently only support a combination of ValueReference and Literal as operands ValueReference valueReference = null; StringLiteral literal = null; for (Expression expression : operator.getOperands()) { switch (expression.getExpressionName()) { case VALUE_REFERENCE: valueReference = (ValueReference)expression; break; case LITERAL: // we only support string literals if (((AbstractLiteral<?>)expression).getLiteralType() != LiteralType.STRING) throw new QueryBuildException("Only string literals are supported for a like operator."); literal = (StringLiteral)expression; break; case FUNCTION: break; } } if (valueReference == null || literal == null) throw new QueryBuildException("Only combinations of ValueReference and Literal are supported as operands of a like operator."); // build the value reference SQLQueryContext queryContext = schemaPathBuilder.buildSchemaPath(valueReference.getSchemaPath(), objectclassIds, operator.isMatchCase()); // check for type mismatch of literal SimpleAttribute attribute = (SimpleAttribute)valueReference.getTarget(); if (!literal.evalutesToSchemaType(attribute.getType())) throw new QueryBuildException("Type mismatch between provided literal and database representation."); // check wildcard and escape characters String wildCard = operator.getWildCard(); String singleCharacter = operator.getSingleCharacter(); String escapeCharacter = operator.getEscapeCharacter(); if (wildCard == null || wildCard.length() > 1) throw new QueryBuildException("Wildcards must be defined by a single character."); if (singleCharacter == null || singleCharacter.length() > 1) throw new QueryBuildException("Wildcards must be defined by a single character."); if (escapeCharacter == null || escapeCharacter.length() > 1) throw new QueryBuildException("An escape character must be defined by a single character."); // replace wild cards String value = replaceWildCards(literal.getValue(), wildCard.charAt(0), singleCharacter.charAt(0), escapeCharacter.charAt(0)); // map operands org.citydb.sqlbuilder.expression.Expression rightOperand = new PlaceHolder<>(value); org.citydb.sqlbuilder.expression.Expression leftOperand = queryContext.targetColumn; // consider match case if (!operator.isMatchCase() && ((PlaceHolder<?>)rightOperand).getValue() instanceof String) { rightOperand = new Function(sqlAdapter.resolveDatabaseOperationName("string.upper"), rightOperand); leftOperand = new Function(sqlAdapter.resolveDatabaseOperationName("string.upper"), leftOperand); } // finally, create equivalent sql operation queryContext.select.addSelection(ComparisonFactory.like(leftOperand, rightOperand, value.contains(escapeCharacter) ? new org.citydb.sqlbuilder.expression.StringLiteral(escapeCharacter) : null, negate)); return queryContext; } private SQLQueryContext buildNullComparison(NullOperator operator, boolean negate) throws QueryBuildException { if (operator.getOperand().getExpressionName() != ExpressionName.VALUE_REFERENCE) throw new QueryBuildException("Only ValueRefernce is supported as operand of a null operator."); ValueReference valueReference = (ValueReference)operator.getOperand(); // create a copy of the schema path and create an is null check // the schema path might be changed by this operation SchemaPath schemaPath = valueReference.getSchemaPath().copy(); PredicateToken token = buildIsNullPredicate((AbstractProperty)valueReference.getTarget(), schemaPath, negate); // finally, create equivalent sql operation SQLQueryContext queryContext = schemaPathBuilder.buildSchemaPath(schemaPath, objectclassIds); queryContext.select.addSelection(token); return queryContext; } private PredicateToken buildIsNullPredicate(AbstractProperty property, SchemaPath schemaPath, boolean negate) throws QueryBuildException { if (property.getElementType() == PathElementType.SIMPLE_ATTRIBUTE || property.getElementType() == PathElementType.GEOMETRY_PROPERTY) { // for simple properties, we just check whether the column is null SQLQueryContext queryContext = schemaPathBuilder.buildSchemaPath(schemaPath, objectclassIds); return ComparisonFactory.isNull(queryContext.targetColumn, negate); } else if (property.getElementType() == PathElementType.COMPLEX_ATTRIBUTE || PathElementType.TYPE_PROPERTIES.contains(property.getElementType())) { AbstractJoin abstractJoin = property.getJoin(); if (abstractJoin != null) { // for complex properties that involve a join, we check whether // there is no foreign key reference from the join table to the target table. // we therefore remove the complex property from the schema // path and create an exists clause schemaPath.removeLastPathElement(); SQLQueryContext queryContext = schemaPathBuilder.buildSchemaPath(schemaPath, objectclassIds); // derive join information String toTable; String toColumn; String fromColumn; List<Condition> conditions; if (abstractJoin instanceof Join) { Join join = (Join)abstractJoin; toTable = join.getTable(); toColumn = join.getToColumn(); fromColumn = join.getFromColumn(); conditions = join.getConditions(); } else if (abstractJoin instanceof JoinTable) { JoinTable joinTable = (JoinTable)abstractJoin; toTable = joinTable.getTable(); Join join = joinTable.getJoin(); toColumn = join.getFromColumn(); fromColumn = join.getToColumn(); conditions = join.getConditions(); } else throw new QueryBuildException("Failed to build null operator for property '" + property + "'."); // create select based on join information Table table = new Table(toTable, schemaName, schemaPathBuilder.geAliasGenerator()); Select select = new Select() .addProjection(new ConstantColumn(1).withFromTable(table)) .addSelection(ComparisonFactory.equalTo(table.getColumn(toColumn), queryContext.toTable.getColumn(fromColumn))); // add join conditions if required if (conditions != null) { for (Condition condition : conditions) { String value = condition.getValue(); // we can skip this token since we do not care about the referenced object type if (value.equals(MappingConstants.TARGET_OBJECTCLASS_ID_TOKEN)) continue; else if (value.equals(MappingConstants.TARGET_ID_TOKEN)) { select.addSelection(ComparisonFactory.equalTo(table.getColumn(condition.getColumn()), table.getColumn(MappingConstants.ID))); continue; } AbstractSQLLiteral<?> literal = schemaPathBuilder.convertToSQLLiteral(value, condition.getType()); select.addSelection(ComparisonFactory.equalTo(table.getColumn(condition.getColumn()), literal)); } } // finally, create exists clause from select return ComparisonFactory.exists(select, !negate); } else { try { // if we deal with a complex property without a join, then we have // found a type whose properties are stored inline the same table. // checking whether the complex property is null therefore requires checking // whether all its properties are null. List<? extends AbstractProperty> innerProperties; if (property.getElementType() == PathElementType.COMPLEX_ATTRIBUTE) { innerProperties = ((ComplexAttribute)property).getType().getAttributes(); } else { AbstractType<?> type = ((AbstractTypeProperty<?>)property).getType(); innerProperties = type.getProperties(); // add the inline object or data type to the schema path schemaPath.appendChild(type); } // we iterate over all type properties and recursively create // an is null check predicate using copies of the schema path List<PredicateToken> tokens = new ArrayList<>(); for (AbstractProperty innerProperty : innerProperties) { SchemaPath innerPath = schemaPath.copy(); innerPath.appendChild(innerProperty); tokens.add(buildIsNullPredicate(innerProperty, innerPath, negate)); } return LogicalOperationFactory.AND(tokens); } catch (InvalidSchemaPathException e) { // } } } throw new QueryBuildException("Failed to build null operator for property '" + property + "'."); } private String replaceWildCards(String value, char wildCard, char singleChar, char escapeChar) { boolean escapeSQLWildCard = wildCard != '%' && singleChar != '%'; boolean espaceSQLSingleChar = wildCard != '_' && singleChar != '_'; StringBuilder tmp = new StringBuilder(); for (int offset = 0; offset < value.length(); offset++) { char ch = value.charAt(offset); if (ch == escapeChar) { // keep escaped chars as is tmp.append(ch); if (++offset < value.length()) tmp.append(value.charAt(offset)); } else if ((ch == '%' && escapeSQLWildCard) || (ch == '_' && espaceSQLSingleChar)) { // escape SQL wild cards tmp.append(escapeChar); tmp.append(ch); } else if (ch == wildCard) { // replace user-defined wild card tmp.append('%'); } else if (ch == singleChar) { // replace user-defined single char tmp.append('_'); } else tmp.append(ch); } return tmp.toString(); } }
removed redundant check
impexp-core/src/main/java/org/citydb/query/builder/sql/ComparisonOperatorBuilder.java
removed redundant check
<ide><path>mpexp-core/src/main/java/org/citydb/query/builder/sql/ComparisonOperatorBuilder.java <ide> org.citydb.sqlbuilder.expression.Expression leftOperand = queryContext.targetColumn; <ide> <ide> // consider match case <del> if (!operator.isMatchCase() && ((PlaceHolder<?>)rightOperand).getValue() instanceof String) { <add> if (!operator.isMatchCase()) { <ide> rightOperand = new Function(sqlAdapter.resolveDatabaseOperationName("string.upper"), rightOperand); <ide> leftOperand = new Function(sqlAdapter.resolveDatabaseOperationName("string.upper"), leftOperand); <ide> }
JavaScript
mit
7118fb585db209c949f64786251f9889eb99a2c4
0
kentaiwami/FiNote,kentaiwami/FiNote,kentaiwami/FiNote,kentaiwami/FiNote
var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); setTimeout(function() { navigator.splashscreen.hide();}, 500); }, onDeviceReady: function() { //データベースのテーブルを構築する var db = utility.get_database(); db.transaction(function(tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS movie (id integer primary key, title text unique, tmdb_id integer unique, genre_id text, onomatopoeia_id text, poster blob)'); tx.executeSql('CREATE TABLE IF NOT EXISTS genre (id integer primary key, name text unique)'); tx.executeSql('CREATE TABLE IF NOT EXISTS onomatopoeia (id integer primary Key, name text)'); }, function(err) { console.log('Open database ERROR: ' +JSON.stringify(err) +' ' + err.message); }); }, }; /** * indexで使用する関数をまとめたオブジェクト * @type {Object} */ var index = { formcheck: [false,false], //[0]はユーザ名とパスワード、[1]は生年月日に対応している /** * サインアップしているかを確認する */ check_signup: function(){ var storage = window.localStorage; var signup_flag = storage.getItem('signup_flag'); //ユーザ情報が登録されている場合は自動ログインを行う if (signup_flag == 'true') { movie.draw_movie_content(); //ユーザ情報が登録されていない場合はsignupへ遷移 }else { utility.pushpage('signup.html','fade',1000); //イベント登録 var addevent = function(){ document.getElementById('username').addEventListener('keyup',index.check_usernameAndpassword_form); document.getElementById('password').addEventListener('keyup',index.check_usernameAndpassword_form); }; utility.check_page_init('signup',addevent); } }, /** * ユーザ名とパスワード入力フォームのkeyupイベントが起きるたびに入力文字数を確認する */ check_usernameAndpassword_form: function(){ var username = document.getElementById('username').value; var password = document.getElementById('password').value; if (username.length === 0 || password.length < 6) { index.formcheck[0] = false; }else{ index.formcheck[0] = true; } index.change_abled_signup_button(); }, /** * formcheck配列を確認して全てtrueならボタンをabledに、そうでなければdisabledにする */ change_abled_signup_button: function(){ if (index.formcheck[0] === true && index.formcheck[1] === true) { document.getElementById('signup_button').removeAttribute('disabled'); }else{ document.getElementById('signup_button').setAttribute('disabled'); } }, }; /** * サインアップ画面で使用する関数をまとめたオブジェクト * @type {Object} */ var Signup = { usersignup: function() { //mobile backendアプリとの連携 var ncmb = utility.get_ncmb(); var user = new ncmb.User(); //性別のチェック状態を確認 var sex = Signup.get_sex(); //ユーザー名・パスワードを設定 user.set('userName', document.getElementById('username').value) .set('password', document.getElementById('password').value) .set('birthday', Number(document.getElementById('birthday').value)) .set('sex', sex); // 新規登録 user.signUpByAccount() .then(function(){ /*登録後処理*/ //ローカルにユーザ名とパスワードを保存する。 var username = document.getElementById('username').value; var password = document.getElementById('password').value; var birthday = Number(document.getElementById('birthday').value); var sex = Signup.get_sex(); var storage = window.localStorage; storage.setItem('username', username); storage.setItem('password', password); storage.setItem('birthday', birthday); storage.setItem('sex', sex); //同時にこれらの情報が記録されているかを判断するフラグも保存する storage.setItem('signup_flag', true); document.getElementById('signup-alert-success').show(); }) .catch(function(err){ // エラー処理 document.getElementById('signup-alert-error').show(); var info = document.getElementById('error-message'); var textNode; if (err.name == "NoUserNameError") { textNode = document.createTextNode('ユーザ名を入力してください'); }else if (err.name == "NoPasswordError") { textNode = document.createTextNode('パスワードを入力してください'); }else if (err.message.indexOf('cannot POST') > -1) { textNode = document.createTextNode('入力したユーザ名は既に使用されています'); }else if (err.message.indexOf('Request has been terminated') > -1) { textNode = document.createTextNode('ネットワーク接続がオフラインのため登録ができません'); } info.appendChild(textNode); }); }, alert_hide: function(id) { //成功時にはindex.htmlへ遷移 if (id == 'signup-alert-success') { var pushpage_tabbar = function(){ function autoLink(){ location.href='index.html'; } setTimeout(autoLink(),0); }; document.getElementById(id).hide(pushpage_tabbar()); //追加したエラーメッセージ(子ノード)を削除する }else if (id == 'signup-alert-error') { document.getElementById(id).hide(); var info = document.getElementById('error-message'); var childNode = info.firstChild; info.removeChild(childNode); } }, /** * 生年月日を選択させるフォーム */ birthday_pickerview: function(){ cordova.plugins.Keyboard.close(); //今年から100年前までの年テキストをオブジェクトとして生成する var birthday = document.getElementById('birthday'); var time = new Date(); var year = time.getFullYear(); var items_array = []; //フォーカスした際にpickerviewデフォルド選択の値を決める var fastvalue = ''; if (birthday.value.length === 0) { fastvalue = String(year); }else{ fastvalue = birthday.value; } for (var i = year; i >= year-100; i--) { var obj = {text: String(i), value: String(i)}; items_array.push(obj); } var config = { title: '', items: items_array, selectedValue: fastvalue, doneButtonLabel: 'Done', cancelButtonLabel: 'Cancel' }; window.plugins.listpicker.showPicker(config, function(item) { birthday.value = item; index.formcheck[1] = true; index.change_abled_signup_button(); }, function() { console.log("You have cancelled"); }); }, /** * 性別を選択するチェックボックスの状態から性別の識別子を返す * @return {[string]} [M or F] */ get_sex: function(){ var M = document.getElementById('radio_m').checked; if (M === true) { return 'M'; }else{ return 'F'; } }, }; /** * movieで使用する関数をまとめたオブジェクト * @type {Object} */ var movie = { /** * 自動ログイン後に映画一覧画面の表示を行う */ draw_movie_content: function() { //自動ログイン var ncmb = utility.get_ncmb(); var storage = window.localStorage; var username = storage.getItem('username'); var password = storage.getItem('password'); ncmb.User.login(username, password).then(function(data){ // ログイン後に映画情報をデータベースから取得 var db = utility.get_database(); db.transaction(function(tx) { db.executeSql('SELECT COUNT(*) AS movie_count FROM movie', [], function(res) { utility.pushpage('tab.html','fade',0); var movie_count = res.rows.item(0).movie_count; var draw_content = function(){}; //ローカルに保存されている映画情報の件数で表示内容を変える if (movie_count === 0) { draw_content = function(){ document.getElementById('nodata_message').innerHTML = '登録された映画はありません'; movie.pullhook_setting(); }; }else { draw_content = function(){ var infiniteList = document.getElementById('infinite-list'); var movie_title = 'タイトルがここに入るタイトルがここに入る'; var movie_thumbnail_path = 'http://placekitten.com/g/40/40'; var movie_subtitle = '追加日:yyyy/mm/dd'; infiniteList.delegate = { createItemContent: function(i) { return ons._util.createElement( '<ons-list-item><div class="left"><img class="list__item__thumbnail_movie" src="' + movie_thumbnail_path +'"></div><div class="center"><span class="list__item__title">' + movie_title +'</span><span class="list__item__subtitle">' +movie_subtitle +'</span></div></ons-list-item>' ); }, countItems: function() { return movie_count; }, calculateItemHeight: function() { return ons.platform.isAndroid() ? 48 : 100; } }; infiniteList.refresh(); movie.pullhook_setting(); }; } utility.check_page_init('movies',draw_content); }); }, function(err) { //SELECT文のエラー処理 console.log('SELECT movie ERROR: ' +JSON.stringify(err) +' ' + err.message); }); }).catch(function(err){ // ログインエラー処理 console.log(err); }); }, /** * 映画一覧画面のpullhookにイベントを登録する */ pullhook_setting: function() { var pullHook = document.getElementById('pull-hook'); pullHook.thresholdHeight = 150; pullHook.addEventListener('changestate', function(event) { var pullhook_message = ''; switch (event.state){ case 'initial': pullhook_message = 'Pull to refresh'; break; case 'preaction': pullhook_message = 'Release'; break; case 'action': pullhook_message = 'Loading...'; break; } pullHook.innerHTML = pullhook_message; }); pullHook.onAction = function(done) { setTimeout(done, 1000); }; }, }; var movieadd_search = { /** * Searchボタン(改行)を押した際に動作 */ click_done: function(){ //console.log('click_done'); cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); document.getElementById('search_movie_title').blur(); movieadd_search.get_search_movie_title_val(); }, /** * バツボタンをタップした際に動作 */ tap_reset: function(){ //formのテキストを初期化、バツボタンの削除、検索結果なしメッセージの削除 document.getElementById('search_movie_title').value = ''; document.getElementById('movieadd_search_reset').innerHTML = ''; document.getElementById('movieadd_no_match_message').innerHTML = ''; movieadd_search.not_show_list(); //テキスト未確定入力時にリセットボタンを押した時 if ($(':focus').attr('id') == 'search_movie_title') { document.getElementById('search_movie_title').blur(); document.getElementById('search_movie_title').focus(); //テキスト入力確定後にリセットボタンを押した時 }else { document.getElementById('search_movie_title').focus(); } }, /** * movieadd_searchのsearch-input横にあるキャンセルボタンをタップした際に前のページへ画面遷移する */ tap_cancel: function(){ document.getElementById('myNavigator').popPage(); //console.log("tap_cancel"); }, /** * 検索フォームにフォーカス時、フォーカスが外れた時のアニメーションを設定する * @param {[string]} event_name [focusまたはblurを受け取る] */ set_animation_movieadd_search_input: function(event_name) { //検索フィールドにフォーカスした時のアニメーション if (event_name == 'focus') { //console.log("focus"); //検索窓の入力を監視するイベントを追加する $('#search_movie_title').on('input', movieadd_search.get_search_movie_title_val); $('#movieadd_search_backbutton').fadeTo(100,0); $('#movieadd_search_backbutton').animate({marginLeft: '-40px'},{queue: false , duration: 200}); $('#search_movie_title').animate({width: '150%'},{queue: false, duration: 200}); $('#movieadd_search_cancel_button').html('キャンセル'); $('#movieadd_search_cancel_button').animate({marginLeft: '45px'},{queue: false, duration: 200}); $('#movieadd_search_cancel_button').fadeTo(100,1); $('#movieadd_reset_button').animate({margin: '0px 0px 0px -100px'},{queue: false, duration: 200}); //検索フィールドのフォーカスが外れた時のアニメーション } else if (event_name == 'blur') { //console.log("blur"); movieadd_search.get_search_movie_title_val(); //検索窓の入力を監視するイベントを削除する $('#search_movie_title').off('input', movieadd_search.get_search_movie_title_val); $('#movieadd_search_backbutton').fadeTo(100,1); $('#movieadd_search_backbutton').animate({marginLeft: '0px'},{queue: false , duration: 200}); $('#search_movie_title').animate({width: '170%'},{queue: false, duration: 200}); $('#movieadd_search_cancel_button').animate({marginLeft: '500px'},{queue: false, duration: 200}); $('#movieadd_search_cancel_button').fadeTo(100,0); $('#movieadd_reset_button').animate({margin: '0px 0px 0px -60px'},{queue: false, duration: 200}); } }, show_list_data: [], //listに表示中のデータを格納する /** * 検索窓にテキストを入力するたびに入力したテキストを取得する * 検索窓の文字数が1以上ならリセットボタンを表示させる */ get_search_movie_title_val: function(){ var text = document.getElementById('search_movie_title').value; var resetbutton = document.getElementById('movieadd_search_reset'); var no_match_message = document.getElementById('movieadd_no_match_message'); if (text.length > 0) { //テキストエリアのリセットボタン表示、スピナー表示 resetbutton.innerHTML = '<ons-button id="movieadd_reset_button" onclick="movieadd_search.tap_reset()" style="margin: 0px 0px 0px -100px;" modifier="quiet"><ons-icon icon="ion-close-circled"></ons-icon></ons-button>'; utility.show_spinner('movieadd_no_match_message'); //日本語と英語のリクエストを行う var promises = [movieadd_search.create_request_movie_search(text,'ja'),movieadd_search.create_request_movie_search(text,'en')]; Promise.all(promises).then(function(results) { utility.stop_spinner(); //検索結果として表示するデータを生成する var list_data = movieadd_search.create_list_data(results); movieadd_search.show_list_data = list_data; //データによって表示するコンテンツを動的に変える if (list_data.length === 0) { no_match_message.innerHTML = '検索結果なし'; $('#movieadd_no_match_message').css('height', '100%'); movieadd_search.not_show_list(); }else{ no_match_message.innerHTML = ''; $('#movieadd_no_match_message').css('height', '0%'); var list_data_poster = movieadd_search.get_poster(list_data); //サムネイル取得後にリストを表示する var infiniteList = document.getElementById('movieadd_search_list'); var movie_subtitle = '公開日:'; infiniteList.delegate = { createItemContent: function(i) { var date = list_data[i].release_date; if (date.length === 0) { list_data[i].release_date = '情報なし'; } return ons._util.createElement( '<ons-list-item id="' + i + '" onclick="movieadd_search.tap_list(this)" modifier="chevron" class="list-item-container"><ons-row><ons-col width="95px"><img style="background:url(img/loading.gif) no-repeat center" class="thumbnail" src="' + list_data_poster[i] +'"></ons-col><ons-col><div class="name">' + list_data[i].title +'</div><div class="desc">' +movie_subtitle+list_data[i].release_date +'</div></ons-col><ons-col width="40px"></ons-col></ons-row></ons-list-item>' ); }, countItems: function() { return list_data.length; }, calculateItemHeight: function() { return ons.platform.isAndroid() ? 48 : 100; } }; } }, function(reason) { console.log(reason); }); } else { resetbutton.innerHTML = ''; no_match_message.innerHTML = ''; movieadd_search.not_show_list(); } }, /** * 映画をタイトルで検索するリクエストを生成して実行する * @param {[string]} movie_title [検索したい映画タイトル] * @param {[string]} language [jaで日本語情報、enで英語情報] * @return {[json]} [検索結果をjsonに変換したもの] */ create_request_movie_search: function(movie_title, language){ return new Promise(function(resolve, reject) { var request = new XMLHttpRequest(); var api_key = utility.get_tmdb_apikey(); var request_url = 'http://api.themoviedb.org/3/search/movie?query=' +movie_title +'&api_key=' + api_key + '&language=' +language; request.open('GET', request_url); request.setRequestHeader('Accept', 'application/json'); request.onreadystatechange = function () { if (this.readyState === 4) { var contact = JSON.parse(this.responseText); resolve(contact); } }; request.send(); }); }, /** * jaとenの検索結果を1つの配列にまとめる * @param {[array]} array [[0]にjaリクエストの配列、[1]にenリクエストの配列] * @return {[array]} [jaとen検索結果をまとめた配列] */ create_list_data: function(array){ if (array.length === 0) { return []; }else{ var list_data = []; //overviewが空文字でないオブジェクトを格納する var overview_nodata = []; //overviewが空文字のオブジェクトのidプロパティを格納する var ja_results = array[0].results; var en_results = array[1].results; /*ja_resutlsの中でoverviewが空文字でないオブジェクトをlist_dataに格納する overviewが空文字のオブジェクトidをoverview_nodataに格納する*/ for(var i = 0; i < ja_results.length; i++){ var ja_overview_text = ja_results[i].overview; if (ja_overview_text.length !== 0) { list_data.push(ja_results[i]); }else{ overview_nodata.push(ja_results[i].id); } } //en_resultsの中からoverview_nodataに格納されているidと一致したオブジェクトをlist_dataに格納する for(var j = 0; j < overview_nodata.length; j++){ for(var k = 0; k < en_results.length; k++){ var nodata_id = overview_nodata[j]; var en_id = en_results[k].id; if (nodata_id == en_id) { list_data.push(en_results[k]); } } } return list_data; } }, /** * サムネイルとして表示する画像を取得する * @param {[array]} list_data [映画オブジェクトの配列] * @return {[string]} [画像のパス] */ get_poster: function(list_data){ var image_url_array = []; //画像を配列に格納する for(var i = 0; i < list_data.length; i++){ var poster_path = list_data[i].poster_path; var url = ''; if (poster_path !== null) { url = 'https://image.tmdb.org/t/p/w300_and_h450_bestv2' + poster_path; image_url_array.push(url); }else{ url = 'img/noimage.png'; image_url_array.push(url); } } return image_url_array; }, /** * リストのコンテンツを非表示にする */ not_show_list: function(){ var infiniteList = document.getElementById('movieadd_search_list'); infiniteList.delegate = { createItemContent: function(i) { return ons._util.createElement(); }, countItems: function() { return 0; }, calculateItemHeight: function() { return ons.platform.isAndroid() ? 48 : 100; } }; }, /** * リストをタップした際に動作する * @param {[object]} obj [タップしたオブジェクト] */ tap_list: function(obj){ var list_data = movieadd_search.show_list_data; var tap_id = obj.id; var myNavigator = document.getElementById('myNavigator'); //movieaddの画面初期化後に動作する関数を定義 var callback = function(){ movieadd.show_contents(list_data,tap_id); }; utility.check_page_init('movieadd',callback); movieadd.current_movie = list_data[tap_id]; //映画追加画面へ遷移 myNavigator.pushPage('movieadd.html', {}); }, }; var movieadd = { userdata: {feeling_name_list: [], dvd: false}, current_movie: {}, taped: false, //falseなら映画の情報が表示されていない、trueは表示済み(表示中) /** * [映画追加画面のコンテンツを表示する] * @param {[array]} list_data [検索結果の映画オブジェクトが格納された配列] * @param {[number]} tap_id [映画検索画面のリストのうちタップされたリスト番号] */ show_contents: function(list_data,tap_id){ //映画のユーザデータを初期化する movieadd.userdata.feeling_name_list = []; movieadd.userdata.dvd = false; //card部分に表示する画像を取得して表示 var card = document.getElementById('movieadd_card'); var tap_list_obj = document.getElementById(tap_id); var img_url = tap_list_obj.children[0].children[0].children[0].children[0].getAttribute('src'); $('#movieadd_card').css('backgroundImage' ,'url('+img_url+')'); //noimageとサムネイルでサイズ設定を変える if (img_url.indexOf('noimage.png') != -1) { $('#movieadd_card').css('backgroundSize' ,'contain'); }else { $('#movieadd_card').css('backgroundSize' ,'cover'); } //card部分や吹き出しタップ時に表示する情報の取得と追加 var title = list_data[tap_id].title; var overview = list_data[tap_id].overview; var release_date = list_data[tap_id].release_date; card.innerHTML = '<div class="modal" id="movie_detail_info" style="height: 87%; opacity: 0.0;"><div class="modal__content"><p>'+ title +'</p><p>'+ overview +'</p><p>'+ release_date +'</p></div></div>'; movieadd.show_vote_average(list_data[tap_id].vote_average); }, /** * 映画追加画面上部のツールバーにあるバックボタンをタップした際にpopPageを行う */ tap_backbutton: function(){ document.getElementById('myNavigator').popPage(); }, /** * card部分や吹き出しタップ時にアニメーション表示を行う */ fadeTo_detail_info: function(){ if (movieadd.taped === false) { $('#movie_detail_info').fadeTo(300,1); movieadd.taped = true; }else { $('#movie_detail_info').fadeTo(300,0); movieadd.taped = false; } }, /** * 映画のレーティングを最大評価5に合うように計算して表示する * @param {[number]} vote_average [最大評価10.0の評価値] */ show_vote_average: function(vote_average){ //検索結果のvote_averageはMAX10なので半分にする var ave = vote_average / 2.0; //小数点第2位で四捨五入をする var pow = Math.pow(10,1); ave = Math.round(ave*pow) / pow; //整数部分に0.5を足してx.5という形にする var pivot = Math.floor(ave) + 0.5; //x.5より大きいか小さいかで(x.5〜x.5+0.5)か(x.0〜x.5)の上限と下限を決定する var under_limit = 0.0; var over_limit = 0.0; if (ave < pivot) { under_limit = pivot - 0.5; over_limit = pivot; }else { under_limit = pivot; over_limit = pivot + 0.5; } //上限と下限に近い方の値をvote_averageとする var result = 0.0; if (Math.abs(ave-under_limit) < Math.abs(ave-over_limit)) { result = under_limit; }else { result = over_limit; } //整数部と少数部を取得 var integer = Math.floor(result); var few = String(result).split(".")[1]; //星と数値を書き込む var rating_num = document.getElementById('movieadd_rating'); var innerHTML_string = ''; var few_write = false; for(var i = 0; i < 5; i++){ if (i < integer) { innerHTML_string += '<ons-icon icon="ion-ios-star" fixed-width="false"></ons-icon>'; }else if (few == 5 && few_write === false) { innerHTML_string += '<ons-icon icon="ion-ios-star-half" fixed-width="false"></ons-icon>'; few_write = true; }else{ innerHTML_string += '<ons-icon icon="ion-ios-star-outline" fixed-width="false"></ons-icon>'; } } innerHTML_string += result; rating_num.innerHTML = innerHTML_string; }, //映画追加ボタンを押したら動作 add_movie: function(){ var userdata = movieadd.userdata; if (userdata.feeling_name_list.length === 0) { ons.notification.alert({ title: '映画追加エラー', message: '気分リストに気分が追加されていません', buttonLabel: 'OK'}); }else { //utility.show_spinner('movieadd_card'); //オノマトペをuserdataから取得 var onomatopoeia_list = movieadd.userdata.feeling_name_list; //表示中の映画オブジェクトを取得 var movie = movieadd.current_movie; var promises = [movieadd.genre(movie.genre_ids),movieadd.onomatopoeia(onomatopoeia_list)]; //ジャンル関係とオノマトペ関係の処理を実行 Promise.all(promises).then(function(results) { console.log(results); }) .catch(function(err){ switch(err) { case 'NCMB_Get_Genre_Error': utility.show_error_alert('NCMB GetGenre Error','再度やり直してください','OK'); break; case 'NCMB_Get_Onomatopoeia_Error': utility.show_error_alert('NCMB GetOnomatopoeia Error','再度やり直してください','OK'); break; case 'NCMB_Set_Genre_Error': utility.show_error_alert('NCMB SetGenre Error','再度やり直してください','OK'); break; case 'NCMB_Get_Onomatopoeia_Error': utility.show_error_alert('NCMB GetOnomatopoeia Error','再度やり直して下さい','OK'); break; case 'NCMB_Set_Onomatopoeia_Error': utility.show_error_alert('NCMB SetOnomatopoeia Error','再度やり直して下さい','OK'); break; default: utility.show_tmdb_error(err); break; } }); //ローカルのジャンル内リストを取得する /* ・取得したリスト内になかったらIDとジャンル名を新規追加(Local DB Write) */ //ローカルのオノマトペリストを取得する /* ・取得したリスト内と同じオノマトペが含まれていなかったら新規追加(Local DB Write) */ //NCMBから映画リストを取得する /* ・リストに同じ映画が存在する場合 ・該当レコードを取得 ・オノマトペリストを取得 ・UserNameに自分のユーザを追加 ・取得したオノマトペリストからIDを割り出す ・(新規追加)オノマトペIDに割り出したIDを追加してcountを1にする ・(上書き追加)オノマトペIDと一致したcountを1増やす ・NCMB DB Write /* ・リストに同じ映画が存在しない場合 ・レコードを生成 ・あとは上記と同じかな */ //スピナー非表示 //アラート表示 //OKタップ後、検索画面に遷移 } }, /** * ジャンル関係の処理を行う * @param {[array]} genre_id_list [ユーザが追加しようとしている映画に付与済みのジャンルIDArray] * @return {[promise]} [成功時:LocalDBに記録するジャンルオブジェクト配列,失敗時:エラーステータス] */ genre: function(genre_id_list){ return new Promise(function(resolve,reject) { var genre_id_list_bridge = {}; //ジャンルIDをまたいで使用するために格納する var genre_obj_list = []; //LocalDBに記録する用のジャンルオブジェクト //NCMBからジャンルリストを取得 movieadd.get_ncmb_genres() .then(function(ncmb_genre_list) { //映画オブジェクトのジャンルIDがNCMBに存在していたら削除する for(var i = genre_id_list.length - 1; i >= 0; i--) { for(var j = 0; j < ncmb_genre_list.length; j++) { if (genre_id_list[i] == ncmb_genre_list[j].ID) { genre_id_list.splice(i,1); genre_obj_list.push({id:ncmb_genre_list[j].ID, name: ncmb_genre_list[j].Name}); } } } /*テストコード*/ // genre_id_list.push(99999); // genre_id_list.push(12345); // genre_id_list.push(88888); // genre_id_list.push(77777); return genre_id_list; }) .then(function(genre_id_list){ //NCMBに登録されていないジャンルIDが存在する場合 if (genre_id_list.length !== 0) { genre_id_list_bridge = genre_id_list; return movieadd.get_tmdb_genre_list(); }else { return {genres: []}; } }) .then(function(tmdb_genre_obj){ var tmdb_genre_list = tmdb_genre_obj.genres; //idだけの配列を作成 var tmdb_genre_id_list = []; for(var i = 0; i < tmdb_genre_list.length; i++) { tmdb_genre_id_list.push(tmdb_genre_list[i].id); } /*テストコード*/ // tmdb_genre_id_list.push(99999); // tmdb_genre_id_list.push(88888); // tmdb_genre_id_list.push(77777); // var test_obj1 = {}; // test_obj1.id = 99999; // test_obj1.name = 'hoge1'; // tmdb_genre_list.push(test_obj1); // var test_obj2 = {}; // test_obj2.id = 88888; // test_obj2.name = 'hoge2'; // tmdb_genre_list.push(test_obj2); // var test_obj5 = {}; // test_obj5.id = 12345; // test_obj5.name = 'test_obj5'; // tmdb_genre_list.push(test_obj5); // var test_obj3 = {}; // test_obj3.id = 77777; // test_obj3.name = 'hoge3'; // tmdb_genre_list.push(test_obj3); //tmdbジャンルリスト内にあったらidと名前をncmbへ新規追加する var promises = []; for(var j = 0; j < genre_id_list_bridge.length; j++) { var tmdb_index = tmdb_genre_id_list.indexOf(genre_id_list_bridge[j]); if (tmdb_index != -1) { var id = tmdb_genre_list[tmdb_index].id; var name = tmdb_genre_list[tmdb_index].name; genre_obj_list.push({id:id, name: name}); promises.push(movieadd.set_genre_ncmb(id,name)); } } return promises; }) .then(function(promises){ Promise.all(promises).then(function(results){ resolve(genre_obj_list); }) .catch(function(err){ console.log(err); reject(err); }); }) .catch(function(err){ console.log(err); reject(err); }); }); }, onomatopoeia: function(onomatopoeia_list) { return new Promise(function(resolve,reject) { var onomatopoeia_obj_list = []; //クラウドからオノマトペリストを取得 movieadd.get_ncmb_onomatopoeia() .then(function(ncmb_onomatopoeia_list) { //オノマトペ名だけの配列を作成 var onomatopoeia_name_list = []; for(var i = 0; i < ncmb_onomatopoeia_list.length; i++) { onomatopoeia_name_list.push(ncmb_onomatopoeia_list[i].Name); } var promises = []; var id_count = ncmb_onomatopoeia_list.length; for(var j = 0; j < onomatopoeia_list.length; j++) { var index = onomatopoeia_name_list.indexOf(onomatopoeia_list[j]); //NCMBのオノマトペリスト内になかったらNCMBへ新規追加 if (index == -1) { var new_id = String(id_count); var new_name = onomatopoeia_list[j]; onomatopoeia_obj_list.push({id:new_id, name:new_name}); promises.push(movieadd.set_onomatopoeia_ncmb(new_id,new_name)); id_count += 1; //存在したらNCMBからIDと名前を取得 }else { var old_id = String(ncmb_onomatopoeia_list[index].ID); var old_name = ncmb_onomatopoeia_list[index].Name; onomatopoeia_obj_list.push({id:old_id,name:old_name}); } } return promises; }) .then(function(promises) { Promise.all(promises).then(function(results) { resolve(onomatopoeia_obj_list); }) .catch(function(err){ console.log(err); reject(err); }); }) .catch(function(err){ console.log(err); reject(err); }); }); }, /** * NCMBのGenreデータクラス全体を取得する * @return {[object]} [Genreレコードオブジェクトが格納された1次元配列] */ get_ncmb_genres: function(){ return new Promise(function(resolve,reject) { var ncmb = utility.get_ncmb(); var Genre = ncmb.DataStore('Genre'); Genre.fetchAll().then(function(results){ resolve(results); }).catch(function(err){ reject('NCMB_Get_Genre_Error'); }); }); }, /** * NCMBのOnomatopoeiaデータクラス全体を取得する * @return {[object]} [Onomatopoeiaレコードオブジェクトが格納された1次元配列] */ get_ncmb_onomatopoeia: function(){ return new Promise(function(resolve,reject) { var ncmb = utility.get_ncmb(); var Onomatopoeia = ncmb.DataStore('Onomatopoeia'); Onomatopoeia.fetchAll().then(function(results){ resolve(results); }).catch(function(err){ reject('NCMB_Get_Onomatopoeia_Error'); }); }); }, /** * TMDBのジャンルリストを取得する * @return {[array]} [idとnameが格納されたオブジェクトArray] */ get_tmdb_genre_list: function(){ return new Promise(function(resolve, reject) { var request = new XMLHttpRequest(); var api_key = utility.get_tmdb_apikey(); var request_url = 'http://api.themoviedb.org/3/genre/movie/list?api_key=' + api_key + '&language=ja'; request.open('GET', request_url); request.setRequestHeader('Accept', 'application/json'); request.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 0) { reject(0); }else { if (this.status === 200) { var contact = JSON.parse(this.responseText); resolve(contact); }else { reject(this.status); } } } }; request.send(); }); }, /** * NCMBのGenreデータクラスへ指定されたidとnameを新規追加する * @param {[number]} id [ジャンルを識別するid(TMDBと同一)] * @param {[string]} name [日本語で表記されたジャンル名] */ set_genre_ncmb: function(id,name) { return new Promise(function(resolve,reject) { var ncmb = utility.get_ncmb(); var Genre = ncmb.DataStore('Genre'); var genre = new Genre(); genre.set('ID', id) .set('Name', name) .save() .then(function(){ resolve('OK'); }) .catch(function(err){ reject('NCMB_Set_Genre_Error'); }); }); }, set_onomatopoeia_ncmb: function(id,name) { return new Promise(function(resolve,reject) { var ncmb = utility.get_ncmb(); var Onomatopoeia = ncmb.DataStore('Onomatopoeia'); var onomatopoeia = new Onomatopoeia(); onomatopoeia.set('ID', id) .set('Name', name) .save() .then(function(){ resolve('OK'); }) .catch(function(err){ reject('NCMB_Set_Onomatopoeia_Error'); }); }); }, /** * 映画の詳細を表示している画面の気分リストをタップした際に画面遷移する */ pushpage_feeling: function(){ var callback = function(){ movieadd_feeling.show_contents(); }; utility.check_page_init('movieadd_feeling', callback); utility.pushpage('movieadd_feeling.html', 'lift', 0); }, /** * 映画の詳細を表示している画面のDVDをタップした際に画面遷移する */ pushpage_dvd: function(){ var callback = function(){ movieadd_dvd.show_contents(); }; utility.check_page_init('movieadd_dvd', callback); utility.pushpage('movieadd_dvd.html', 'lift', 0); }, /** * 登録されたリストの件数とDVD所持情報をもとにラベルを更新する関数 */ show_feelingAnddvd_label: function(){ var list_length = movieadd.userdata.feeling_name_list.length; var dvd_flag = movieadd.userdata.dvd; var dvd = 'No'; if (dvd_flag) { dvd = 'Yes'; }else { dvd = 'No'; } var list_number = document.getElementById('list_number'); var have_dvd = document.getElementById('have_dvd'); list_number.innerHTML = list_length + '件'; have_dvd.innerHTML = dvd; }, }; var movieadd_feeling = { show_contents: function(){ //アラート表示後に自動フォーカスするためのイベントを登録する movieadd_feeling.feeling_input_name_addEvent(); var nodata_message = document.getElementById('movieadd_feeling_nodata_message'); var length = movieadd.userdata.feeling_name_list.length; if (length === 0) { $('#movieadd_feeling_nodata_message').css('height', '100%'); nodata_message.innerHTML = '感情を1件以上登録してください<br>(1件につき6文字以内)'; }else { $('#movieadd_feeling_nodata_message').css('height', '0%'); nodata_message.innerHTML = ''; //リスト表示 var feeling_list = document.getElementById('feeling_list'); feeling_list.innerHTML = ''; for(var i = 0; i < length; i++) { feeling_list.innerHTML += '<h3 class="feeling_film" style="opacity: 0; margin-top: 40px;">' + movieadd.userdata.feeling_name_list[i] + '</h3>'; } //アニメーション表示 var delaySpeed = 50; var fadeSpeed = 400; $('.feeling_film').each(function(index) { $(this).delay(index*delaySpeed).animate({opacity:'1', marginTop: '20px'},fadeSpeed); }); } }, /** * アラート表示後にフォーカスを当てる処理を行う */ feeling_input_name_addEvent: function(){ document.addEventListener('postshow', function(event) { if (event.target.id == 'feeling_add_dialog') { document.getElementById('feeling_input_name').focus(); } }); }, /** * 気分を入力するアラートを表示してinputのvalueを初期化する */ show_input_alert: function(){ document.getElementById('feeling_add_dialog').show(); var input_form = document.getElementById('feeling_input_name'); input_form.value = ''; input_form.addEventListener('keyup', movieadd_feeling.check_input_form); }, /** * フォームの値を監視して登録ボタンの有効・無効を設定する関数 * @return {[type]} [description] */ check_input_form: function(){ var value = document.getElementById('feeling_input_name').value; var add_button = document.getElementById('feeling_add_button'); if (value !== '') { add_button.removeAttribute('disabled'); }else { add_button.setAttribute('disabled'); } }, /** * アラートを閉じるor閉じてリストへ追加する関数 * @param {[string]} id [cancelかadd] */ hide_input_alert: function(id){ if (id == 'cancel') { document.getElementById('feeling_add_dialog').hide(); }else { //リストへ登録して気分を表示する var feeling_name = document.getElementById('feeling_input_name').value; movieadd_feeling.add_list(feeling_name); document.getElementById('feeling_add_dialog').hide(); } }, /** * 引き数で渡された気分の文字列をリストに表示する * @param {[string]} feeling_name [ユーザが入力した気分] */ add_list: function(feeling_name){ //リスト表示 movieadd.userdata.feeling_name_list.push(feeling_name); movieadd_feeling.show_contents(); //ラベルの更新 movieadd.show_feelingAnddvd_label(); }, }; var movieadd_dvd = { /** * 保存しているラジオボタンの状態をもとにチェックをつける */ show_contents: function(){ var dvd_check = movieadd.userdata.dvd; var radio_dvd_yes = document.getElementById('radio_dvd_yes'); if (dvd_check === true) { radio_dvd_yes.checked = true; }else { radio_dvd_yes.checked = false; } }, /** * movieadd_dvd.html(DVDの所持確認画面)を閉じる時の関数 */ close_movieadd_dvd: function(){ //チェックボタンの状態を保存する var yes = document.getElementById('radio_dvd_yes').checked; if (yes === true) { movieadd.userdata.dvd = true; }else { movieadd.userdata.dvd = false; } //ラベルの更新 movieadd.show_feelingAnddvd_label(); utility.popPage(); }, }; /** * 便利関数をまとめたオブジェクト * @type {Object} */ var utility = { /** * ncmbを生成して返す * @return {[object]} [生成したncmb] */ get_ncmb: function(){ var ncmb = new NCMB('f5f6c2e3aa823eea2c500446a62c5645c04fc2fbfd9833cb173e1d876f464f6c','605298c95c0ba9c654315f11c6817e790f21f83a0e9ff60dc2fdf626b1485899'); return ncmb; }, /** * ローカルストレージの初期化をする */ delete_localstorage: function(){ var storage = window.localStorage; storage.removeItem('username'); storage.removeItem('password'); storage.removeItem('birthday'); storage.removeItem('sex'); storage.removeItem('signup_flag'); }, /** * ローカルストレージの状態を表示する */ show_localstorage: function(){ var storage = window.localStorage; var username = storage.getItem('username'); var password = storage.getItem('password'); var birthday = storage.getItem('birthday'); var sex = storage.getItem('sex'); var signup_flag = storage.getItem('signup_flag'); var obj = {'username':username, 'password':password, 'birthday':birthday, 'sex':sex, 'signup_flag':signup_flag}; console.log(obj); }, /** * 指定したページの読み込み終了後に指定したcallbackを実行する * @param {[string]} pageid [pageのid] * @param {Function} callback [読み込み終了後に実行したいコールバック関数] */ check_page_init: function(pageid,callback){ document.addEventListener('init', function(event) { if (event.target.id == pageid) { console.log(pageid + ' is inited'); callback(); } }); }, /** * データベースのオブジェクトを返す * @return {[type]} [description] */ get_database: function(){ var db = window.sqlitePlugin.openDatabase({name: 'my_db', location: 'default'}); return db; }, /** * TMDBのAPIキーを返す * @return {[string]} [TMDBのAPIキー] */ get_tmdb_apikey: function(){ return 'dcf593b3416b09594c1f13fabd1b9802'; }, /** * htmlファイル、アニメーション、delay時間を指定するとアニメーションを行って画面遷移する * @param {[string]} html_name [画面遷移したいhtmlファイル名] * @param {[string]} animation_name [アニメーション名] * @param {[number]} delaytime [Timeoutの時間] */ pushpage: function(html_name, animation_name, delaytime) { var showpage = function(){ document.getElementById('myNavigator').pushPage(html_name, { animation : animation_name }); }; setTimeout(showpage, delaytime); }, /** * onsen uiのpopPageを実行する関数 */ popPage: function(){ document.getElementById('myNavigator').popPage(); }, /** * 画面のwidth,heightを取得する * @return {[object]} [widthとheightが格納されたオブジェクト] */ getScreenSize: function() { var w = window.parent.screen.width; var h = window.parent.screen.height; var obj = {w:w,h:h}; return obj; }, /** * ブラウザで強制的にログインするための関数 * @return {[type]} [description] */ browser_signup: function(){ var callback = function(){ document.getElementById('username').value = 'ブラウザユーザ'; document.getElementById('password').value = 'password'; document.getElementById('birthday').value = '1994'; index.formcheck[0] = true; index.formcheck[1] = true; var storage = window.localStorage; storage.setItem('username', document.getElementById('username').value); storage.setItem('password', document.getElementById('password').value); storage.setItem('birthday', Number(document.getElementById('birthday').value)); storage.setItem('sex', 'M'); storage.setItem('signup_flag', true); }; utility.check_page_init('signup',callback); }, spinner: {}, //spinnerオブジェクト格納用 /** * 指定した親要素にスピナーを表示する * @param {[string]} parent [親要素のid] */ show_spinner: function(parent){ var opts = { lines: 13, //線の数 length: 8, //線の長さ width: 3, //線の幅 radius: 16, //スピナーの内側の広さ corners: 1, //角の丸み rotate: 74, //向き(あんまり意味が無い・・) direction: 1, //1:時計回り -1:反時計回り color: '#000', // 色 speed: 2.0, // 一秒間に回転する回数 trail: 71, //残像の長さ shadow: true, // 影 hwaccel: true, // ? className: 'spinner', // クラス名 zIndex: 2e9, // Z-index top: '50%', // relative TOP left: '50%', // relative LEFT opacity: 0.25, //透明度 fps: 40 //fps }; //描画先の親要素 var spin_target = document.getElementById(parent); //スピナーオブジェクト var spinner = new Spinner(opts); utility.spinner = spinner; //スピナー描画 spinner.spin(spin_target); }, /** * [スピナーの表示を止める] */ stop_spinner: function(){ utility.spinner.spin(); }, /** * エラーのアラートを表示する * @param {[string]} title [タイトル] * @param {[string]} message [メッセージ] * @param {[string]} buttonLabel [ボタンのラベル] */ show_error_alert: function(title,message,buttonLabel) { ons.notification.alert({ title: title, message: message, buttonLabel: buttonLabel}); }, /** * TMDBに関するエラーアラートを表示する * @param {[number]} err_status [エラーのHTTPstatus] */ show_tmdb_error: function(err_status) { switch(err_status) { case 0: utility.show_error_alert('通信エラー','ネットワーク接続を確認して下さい','OK'); break; case 401: utility.show_error_alert('APIエラー','有効なAPIキーを設定して下さい','OK'); break; case 404: utility.show_error_alert('Not found','リソースが見つかりませんでした','OK'); break; default: utility.show_error_alert('不明なエラー','不明なエラーが発生しました','OK'); break; } }, }; // //ローカルのデータベースにサーバから取得したmovieを記録する // function insert_movie(movies){ // var db = this.get_database(); // for (var i = 0; i < movies.length; i++) { // console.log(movies[i]); // db.executeSql("INSERT INTO movie(title, tmdb_id, genre_id, keyword_id, onomatopoeia_id, thumbnail_path, username) VALUES('title', 'tmdb_id', 'genre_id')"); // //id integer primary key, title text unique, tmdb_id integer unique, genre_id text, keyword_id text, onomatopoeia_id text, thumbnail_path text, username text // } // // db.transaction(function(tx) { // // // console.log('Open database success'); // // for (var i = 0; i >= 0; i--) { // // Things[i] // // } // // tx.executeSql('CREATE TABLE IF NOT EXISTS movie (id integer primary key, title text, tmdb_id text, genre_id text, keyword_id text, onomatopoeia_id text, thumbnail text, username text)'); // // tx.executeSql('CREATE TABLE IF NOT EXISTS Genre (id integer primary key, name text, username text)'); // // tx.executeSql('CREATE TABLE IF NOT EXISTS KeyWord (id integer primary key, name text, username text)'); // // tx.executeSql('CREATE TABLE IF NOT EXISTS Onomatopoeia (id integer primary Key, name text, joy_status text, anger_status text, sadness_status text, happiness_status text)'); // // }, function(err) { // // console.log('Open database ERROR: ' +JSON.stringify(err) +' ' + err.message); // // }); // } // //ログイン中のユーザ名が含まれるMovieオブジェクトを最新順で取得する // function get_movies_ncmbobject(username, callback){ // var ncmb = get_ncmb(); // var Movie = ncmb.DataStore("Movie"); // Movie.equalTo("UserName", username) // .order("updateDate",true) // .fetchAll() // .then(function(results){ // insert_movie(results); // callback(); // }) // .catch(function(err){ // console.log(err); // }); // } app.initialize();
FiNote/www/js/index.js
var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); setTimeout(function() { navigator.splashscreen.hide();}, 500); }, onDeviceReady: function() { //データベースのテーブルを構築する var db = utility.get_database(); db.transaction(function(tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS movie (id integer primary key, title text unique, tmdb_id integer unique, genre_id text, onomatopoeia_id text, poster blob)'); tx.executeSql('CREATE TABLE IF NOT EXISTS genre (id integer primary key, name text unique)'); tx.executeSql('CREATE TABLE IF NOT EXISTS onomatopoeia (id integer primary Key, name text)'); }, function(err) { console.log('Open database ERROR: ' +JSON.stringify(err) +' ' + err.message); }); }, }; /** * indexで使用する関数をまとめたオブジェクト * @type {Object} */ var index = { formcheck: [false,false], //[0]はユーザ名とパスワード、[1]は生年月日に対応している /** * サインアップしているかを確認する */ check_signup: function(){ var storage = window.localStorage; var signup_flag = storage.getItem('signup_flag'); //ユーザ情報が登録されている場合は自動ログインを行う if (signup_flag == 'true') { movie.draw_movie_content(); //ユーザ情報が登録されていない場合はsignupへ遷移 }else { utility.pushpage('signup.html','fade',1000); //イベント登録 var addevent = function(){ document.getElementById('username').addEventListener('keyup',index.check_usernameAndpassword_form); document.getElementById('password').addEventListener('keyup',index.check_usernameAndpassword_form); }; utility.check_page_init('signup',addevent); } }, /** * ユーザ名とパスワード入力フォームのkeyupイベントが起きるたびに入力文字数を確認する */ check_usernameAndpassword_form: function(){ var username = document.getElementById('username').value; var password = document.getElementById('password').value; if (username.length === 0 || password.length < 6) { index.formcheck[0] = false; }else{ index.formcheck[0] = true; } index.change_abled_signup_button(); }, /** * formcheck配列を確認して全てtrueならボタンをabledに、そうでなければdisabledにする */ change_abled_signup_button: function(){ if (index.formcheck[0] === true && index.formcheck[1] === true) { document.getElementById('signup_button').removeAttribute('disabled'); }else{ document.getElementById('signup_button').setAttribute('disabled'); } }, }; /** * サインアップ画面で使用する関数をまとめたオブジェクト * @type {Object} */ var Signup = { usersignup: function() { //mobile backendアプリとの連携 var ncmb = utility.get_ncmb(); var user = new ncmb.User(); //性別のチェック状態を確認 var sex = Signup.get_sex(); //ユーザー名・パスワードを設定 user.set('userName', document.getElementById('username').value) .set('password', document.getElementById('password').value) .set('birthday', Number(document.getElementById('birthday').value)) .set('sex', sex); // 新規登録 user.signUpByAccount() .then(function(){ /*登録後処理*/ //ローカルにユーザ名とパスワードを保存する。 var username = document.getElementById('username').value; var password = document.getElementById('password').value; var birthday = Number(document.getElementById('birthday').value); var sex = Signup.get_sex(); var storage = window.localStorage; storage.setItem('username', username); storage.setItem('password', password); storage.setItem('birthday', birthday); storage.setItem('sex', sex); //同時にこれらの情報が記録されているかを判断するフラグも保存する storage.setItem('signup_flag', true); document.getElementById('signup-alert-success').show(); }) .catch(function(err){ // エラー処理 document.getElementById('signup-alert-error').show(); var info = document.getElementById('error-message'); var textNode; if (err.name == "NoUserNameError") { textNode = document.createTextNode('ユーザ名を入力してください'); }else if (err.name == "NoPasswordError") { textNode = document.createTextNode('パスワードを入力してください'); }else if (err.message.indexOf('cannot POST') > -1) { textNode = document.createTextNode('入力したユーザ名は既に使用されています'); }else if (err.message.indexOf('Request has been terminated') > -1) { textNode = document.createTextNode('ネットワーク接続がオフラインのため登録ができません'); } info.appendChild(textNode); }); }, alert_hide: function(id) { //成功時にはindex.htmlへ遷移 if (id == 'signup-alert-success') { var pushpage_tabbar = function(){ function autoLink(){ location.href='index.html'; } setTimeout(autoLink(),0); }; document.getElementById(id).hide(pushpage_tabbar()); //追加したエラーメッセージ(子ノード)を削除する }else if (id == 'signup-alert-error') { document.getElementById(id).hide(); var info = document.getElementById('error-message'); var childNode = info.firstChild; info.removeChild(childNode); } }, /** * 生年月日を選択させるフォーム */ birthday_pickerview: function(){ cordova.plugins.Keyboard.close(); //今年から100年前までの年テキストをオブジェクトとして生成する var birthday = document.getElementById('birthday'); var time = new Date(); var year = time.getFullYear(); var items_array = []; //フォーカスした際にpickerviewデフォルド選択の値を決める var fastvalue = ''; if (birthday.value.length === 0) { fastvalue = String(year); }else{ fastvalue = birthday.value; } for (var i = year; i >= year-100; i--) { var obj = {text: String(i), value: String(i)}; items_array.push(obj); } var config = { title: '', items: items_array, selectedValue: fastvalue, doneButtonLabel: 'Done', cancelButtonLabel: 'Cancel' }; window.plugins.listpicker.showPicker(config, function(item) { birthday.value = item; index.formcheck[1] = true; index.change_abled_signup_button(); }, function() { console.log("You have cancelled"); }); }, /** * 性別を選択するチェックボックスの状態から性別の識別子を返す * @return {[string]} [M or F] */ get_sex: function(){ var M = document.getElementById('radio_m').checked; if (M === true) { return 'M'; }else{ return 'F'; } }, }; /** * movieで使用する関数をまとめたオブジェクト * @type {Object} */ var movie = { /** * 自動ログイン後に映画一覧画面の表示を行う */ draw_movie_content: function() { //自動ログイン var ncmb = utility.get_ncmb(); var storage = window.localStorage; var username = storage.getItem('username'); var password = storage.getItem('password'); ncmb.User.login(username, password).then(function(data){ // ログイン後に映画情報をデータベースから取得 var db = utility.get_database(); db.transaction(function(tx) { db.executeSql('SELECT COUNT(*) AS movie_count FROM movie', [], function(res) { utility.pushpage('tab.html','fade',0); var movie_count = res.rows.item(0).movie_count; var draw_content = function(){}; //ローカルに保存されている映画情報の件数で表示内容を変える if (movie_count === 0) { draw_content = function(){ document.getElementById('nodata_message').innerHTML = '登録された映画はありません'; movie.pullhook_setting(); }; }else { draw_content = function(){ var infiniteList = document.getElementById('infinite-list'); var movie_title = 'タイトルがここに入るタイトルがここに入る'; var movie_thumbnail_path = 'http://placekitten.com/g/40/40'; var movie_subtitle = '追加日:yyyy/mm/dd'; infiniteList.delegate = { createItemContent: function(i) { return ons._util.createElement( '<ons-list-item><div class="left"><img class="list__item__thumbnail_movie" src="' + movie_thumbnail_path +'"></div><div class="center"><span class="list__item__title">' + movie_title +'</span><span class="list__item__subtitle">' +movie_subtitle +'</span></div></ons-list-item>' ); }, countItems: function() { return movie_count; }, calculateItemHeight: function() { return ons.platform.isAndroid() ? 48 : 100; } }; infiniteList.refresh(); movie.pullhook_setting(); }; } utility.check_page_init('movies',draw_content); }); }, function(err) { //SELECT文のエラー処理 console.log('SELECT movie ERROR: ' +JSON.stringify(err) +' ' + err.message); }); }).catch(function(err){ // ログインエラー処理 console.log(err); }); }, /** * 映画一覧画面のpullhookにイベントを登録する */ pullhook_setting: function() { var pullHook = document.getElementById('pull-hook'); pullHook.thresholdHeight = 150; pullHook.addEventListener('changestate', function(event) { var pullhook_message = ''; switch (event.state){ case 'initial': pullhook_message = 'Pull to refresh'; break; case 'preaction': pullhook_message = 'Release'; break; case 'action': pullhook_message = 'Loading...'; break; } pullHook.innerHTML = pullhook_message; }); pullHook.onAction = function(done) { setTimeout(done, 1000); }; }, }; var movieadd_search = { /** * Searchボタン(改行)を押した際に動作 */ click_done: function(){ //console.log('click_done'); cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); document.getElementById('search_movie_title').blur(); movieadd_search.get_search_movie_title_val(); }, /** * バツボタンをタップした際に動作 */ tap_reset: function(){ //formのテキストを初期化、バツボタンの削除、検索結果なしメッセージの削除 document.getElementById('search_movie_title').value = ''; document.getElementById('movieadd_search_reset').innerHTML = ''; document.getElementById('movieadd_no_match_message').innerHTML = ''; movieadd_search.not_show_list(); //テキスト未確定入力時にリセットボタンを押した時 if ($(':focus').attr('id') == 'search_movie_title') { document.getElementById('search_movie_title').blur(); document.getElementById('search_movie_title').focus(); //テキスト入力確定後にリセットボタンを押した時 }else { document.getElementById('search_movie_title').focus(); } }, /** * movieadd_searchのsearch-input横にあるキャンセルボタンをタップした際に前のページへ画面遷移する */ tap_cancel: function(){ document.getElementById('myNavigator').popPage(); //console.log("tap_cancel"); }, /** * 検索フォームにフォーカス時、フォーカスが外れた時のアニメーションを設定する * @param {[string]} event_name [focusまたはblurを受け取る] */ set_animation_movieadd_search_input: function(event_name) { //検索フィールドにフォーカスした時のアニメーション if (event_name == 'focus') { //console.log("focus"); //検索窓の入力を監視するイベントを追加する $('#search_movie_title').on('input', movieadd_search.get_search_movie_title_val); $('#movieadd_search_backbutton').fadeTo(100,0); $('#movieadd_search_backbutton').animate({marginLeft: '-40px'},{queue: false , duration: 200}); $('#search_movie_title').animate({width: '150%'},{queue: false, duration: 200}); $('#movieadd_search_cancel_button').html('キャンセル'); $('#movieadd_search_cancel_button').animate({marginLeft: '45px'},{queue: false, duration: 200}); $('#movieadd_search_cancel_button').fadeTo(100,1); $('#movieadd_reset_button').animate({margin: '0px 0px 0px -100px'},{queue: false, duration: 200}); //検索フィールドのフォーカスが外れた時のアニメーション } else if (event_name == 'blur') { //console.log("blur"); movieadd_search.get_search_movie_title_val(); //検索窓の入力を監視するイベントを削除する $('#search_movie_title').off('input', movieadd_search.get_search_movie_title_val); $('#movieadd_search_backbutton').fadeTo(100,1); $('#movieadd_search_backbutton').animate({marginLeft: '0px'},{queue: false , duration: 200}); $('#search_movie_title').animate({width: '170%'},{queue: false, duration: 200}); $('#movieadd_search_cancel_button').animate({marginLeft: '500px'},{queue: false, duration: 200}); $('#movieadd_search_cancel_button').fadeTo(100,0); $('#movieadd_reset_button').animate({margin: '0px 0px 0px -60px'},{queue: false, duration: 200}); } }, show_list_data: [], //listに表示中のデータを格納する /** * 検索窓にテキストを入力するたびに入力したテキストを取得する * 検索窓の文字数が1以上ならリセットボタンを表示させる */ get_search_movie_title_val: function(){ var text = document.getElementById('search_movie_title').value; var resetbutton = document.getElementById('movieadd_search_reset'); var no_match_message = document.getElementById('movieadd_no_match_message'); if (text.length > 0) { //テキストエリアのリセットボタン表示、スピナー表示 resetbutton.innerHTML = '<ons-button id="movieadd_reset_button" onclick="movieadd_search.tap_reset()" style="margin: 0px 0px 0px -100px;" modifier="quiet"><ons-icon icon="ion-close-circled"></ons-icon></ons-button>'; utility.show_spinner('movieadd_no_match_message'); //日本語と英語のリクエストを行う var promises = [movieadd_search.create_request_movie_search(text,'ja'),movieadd_search.create_request_movie_search(text,'en')]; Promise.all(promises).then(function(results) { utility.stop_spinner(); //検索結果として表示するデータを生成する var list_data = movieadd_search.create_list_data(results); movieadd_search.show_list_data = list_data; //データによって表示するコンテンツを動的に変える if (list_data.length === 0) { no_match_message.innerHTML = '検索結果なし'; $('#movieadd_no_match_message').css('height', '100%'); movieadd_search.not_show_list(); }else{ no_match_message.innerHTML = ''; $('#movieadd_no_match_message').css('height', '0%'); var list_data_poster = movieadd_search.get_poster(list_data); //サムネイル取得後にリストを表示する var infiniteList = document.getElementById('movieadd_search_list'); var movie_subtitle = '公開日:'; infiniteList.delegate = { createItemContent: function(i) { var date = list_data[i].release_date; if (date.length === 0) { list_data[i].release_date = '情報なし'; } return ons._util.createElement( '<ons-list-item id="' + i + '" onclick="movieadd_search.tap_list(this)" modifier="chevron" class="list-item-container"><ons-row><ons-col width="95px"><img style="background:url(img/loading.gif) no-repeat center" class="thumbnail" src="' + list_data_poster[i] +'"></ons-col><ons-col><div class="name">' + list_data[i].title +'</div><div class="desc">' +movie_subtitle+list_data[i].release_date +'</div></ons-col><ons-col width="40px"></ons-col></ons-row></ons-list-item>' ); }, countItems: function() { return list_data.length; }, calculateItemHeight: function() { return ons.platform.isAndroid() ? 48 : 100; } }; } }, function(reason) { console.log(reason); }); } else { resetbutton.innerHTML = ''; no_match_message.innerHTML = ''; movieadd_search.not_show_list(); } }, /** * 映画をタイトルで検索するリクエストを生成して実行する * @param {[string]} movie_title [検索したい映画タイトル] * @param {[string]} language [jaで日本語情報、enで英語情報] * @return {[json]} [検索結果をjsonに変換したもの] */ create_request_movie_search: function(movie_title, language){ return new Promise(function(resolve, reject) { var request = new XMLHttpRequest(); var api_key = utility.get_tmdb_apikey(); var request_url = 'http://api.themoviedb.org/3/search/movie?query=' +movie_title +'&api_key=' + api_key + '&language=' +language; request.open('GET', request_url); request.setRequestHeader('Accept', 'application/json'); request.onreadystatechange = function () { if (this.readyState === 4) { var contact = JSON.parse(this.responseText); resolve(contact); } }; request.send(); }); }, /** * jaとenの検索結果を1つの配列にまとめる * @param {[array]} array [[0]にjaリクエストの配列、[1]にenリクエストの配列] * @return {[array]} [jaとen検索結果をまとめた配列] */ create_list_data: function(array){ if (array.length === 0) { return []; }else{ var list_data = []; //overviewが空文字でないオブジェクトを格納する var overview_nodata = []; //overviewが空文字のオブジェクトのidプロパティを格納する var ja_results = array[0].results; var en_results = array[1].results; /*ja_resutlsの中でoverviewが空文字でないオブジェクトをlist_dataに格納する overviewが空文字のオブジェクトidをoverview_nodataに格納する*/ for(var i = 0; i < ja_results.length; i++){ var ja_overview_text = ja_results[i].overview; if (ja_overview_text.length !== 0) { list_data.push(ja_results[i]); }else{ overview_nodata.push(ja_results[i].id); } } //en_resultsの中からoverview_nodataに格納されているidと一致したオブジェクトをlist_dataに格納する for(var j = 0; j < overview_nodata.length; j++){ for(var k = 0; k < en_results.length; k++){ var nodata_id = overview_nodata[j]; var en_id = en_results[k].id; if (nodata_id == en_id) { list_data.push(en_results[k]); } } } return list_data; } }, /** * サムネイルとして表示する画像を取得する * @param {[array]} list_data [映画オブジェクトの配列] * @return {[string]} [画像のパス] */ get_poster: function(list_data){ var image_url_array = []; //画像を配列に格納する for(var i = 0; i < list_data.length; i++){ var poster_path = list_data[i].poster_path; var url = ''; if (poster_path !== null) { url = 'https://image.tmdb.org/t/p/w300_and_h450_bestv2' + poster_path; image_url_array.push(url); }else{ url = 'img/noimage.png'; image_url_array.push(url); } } return image_url_array; }, /** * リストのコンテンツを非表示にする */ not_show_list: function(){ var infiniteList = document.getElementById('movieadd_search_list'); infiniteList.delegate = { createItemContent: function(i) { return ons._util.createElement(); }, countItems: function() { return 0; }, calculateItemHeight: function() { return ons.platform.isAndroid() ? 48 : 100; } }; }, /** * リストをタップした際に動作する * @param {[object]} obj [タップしたオブジェクト] */ tap_list: function(obj){ var list_data = movieadd_search.show_list_data; var tap_id = obj.id; var myNavigator = document.getElementById('myNavigator'); //movieaddの画面初期化後に動作する関数を定義 var callback = function(){ movieadd.show_contents(list_data,tap_id); }; utility.check_page_init('movieadd',callback); movieadd.current_movie = list_data[tap_id]; //映画追加画面へ遷移 myNavigator.pushPage('movieadd.html', {}); }, }; var movieadd = { userdata: {feeling_name_list: [], dvd: false}, current_movie: {}, taped: false, //falseなら映画の情報が表示されていない、trueは表示済み(表示中) /** * [映画追加画面のコンテンツを表示する] * @param {[array]} list_data [検索結果の映画オブジェクトが格納された配列] * @param {[number]} tap_id [映画検索画面のリストのうちタップされたリスト番号] */ show_contents: function(list_data,tap_id){ //映画のユーザデータを初期化する movieadd.userdata.feeling_name_list = []; movieadd.userdata.dvd = false; //card部分に表示する画像を取得して表示 var card = document.getElementById('movieadd_card'); var tap_list_obj = document.getElementById(tap_id); var img_url = tap_list_obj.children[0].children[0].children[0].children[0].getAttribute('src'); $('#movieadd_card').css('backgroundImage' ,'url('+img_url+')'); //noimageとサムネイルでサイズ設定を変える if (img_url.indexOf('noimage.png') != -1) { $('#movieadd_card').css('backgroundSize' ,'contain'); }else { $('#movieadd_card').css('backgroundSize' ,'cover'); } //card部分や吹き出しタップ時に表示する情報の取得と追加 var title = list_data[tap_id].title; var overview = list_data[tap_id].overview; var release_date = list_data[tap_id].release_date; card.innerHTML = '<div class="modal" id="movie_detail_info" style="height: 87%; opacity: 0.0;"><div class="modal__content"><p>'+ title +'</p><p>'+ overview +'</p><p>'+ release_date +'</p></div></div>'; movieadd.show_vote_average(list_data[tap_id].vote_average); }, /** * 映画追加画面上部のツールバーにあるバックボタンをタップした際にpopPageを行う */ tap_backbutton: function(){ document.getElementById('myNavigator').popPage(); }, /** * card部分や吹き出しタップ時にアニメーション表示を行う */ fadeTo_detail_info: function(){ if (movieadd.taped === false) { $('#movie_detail_info').fadeTo(300,1); movieadd.taped = true; }else { $('#movie_detail_info').fadeTo(300,0); movieadd.taped = false; } }, /** * 映画のレーティングを最大評価5に合うように計算して表示する * @param {[number]} vote_average [最大評価10.0の評価値] */ show_vote_average: function(vote_average){ //検索結果のvote_averageはMAX10なので半分にする var ave = vote_average / 2.0; //小数点第2位で四捨五入をする var pow = Math.pow(10,1); ave = Math.round(ave*pow) / pow; //整数部分に0.5を足してx.5という形にする var pivot = Math.floor(ave) + 0.5; //x.5より大きいか小さいかで(x.5〜x.5+0.5)か(x.0〜x.5)の上限と下限を決定する var under_limit = 0.0; var over_limit = 0.0; if (ave < pivot) { under_limit = pivot - 0.5; over_limit = pivot; }else { under_limit = pivot; over_limit = pivot + 0.5; } //上限と下限に近い方の値をvote_averageとする var result = 0.0; if (Math.abs(ave-under_limit) < Math.abs(ave-over_limit)) { result = under_limit; }else { result = over_limit; } //整数部と少数部を取得 var integer = Math.floor(result); var few = String(result).split(".")[1]; //星と数値を書き込む var rating_num = document.getElementById('movieadd_rating'); var innerHTML_string = ''; var few_write = false; for(var i = 0; i < 5; i++){ if (i < integer) { innerHTML_string += '<ons-icon icon="ion-ios-star" fixed-width="false"></ons-icon>'; }else if (few == 5 && few_write === false) { innerHTML_string += '<ons-icon icon="ion-ios-star-half" fixed-width="false"></ons-icon>'; few_write = true; }else{ innerHTML_string += '<ons-icon icon="ion-ios-star-outline" fixed-width="false"></ons-icon>'; } } innerHTML_string += result; rating_num.innerHTML = innerHTML_string; }, //映画追加ボタンを押したら動作 add_movie: function(){ var userdata = movieadd.userdata; if (userdata.feeling_name_list.length === 0) { ons.notification.alert({ title: '映画追加エラー', message: '気分リストに気分が追加されていません', buttonLabel: 'OK'}); }else { //utility.show_spinner('movieadd_card'); //オノマトペをuserdataから取得 var onomatopoeia_list = movieadd.userdata.feeling_name_list; //表示中の映画オブジェクトを取得 var movie = movieadd.current_movie; var promises = [movieadd.genre(movie.genre_ids),movieadd.onomatopoeia(onomatopoeia_list)]; //ジャンル関係とオノマトペ関係の処理を実行 Promise.all(promises).then(function(results) { console.log(results); }) .catch(function(err){ if (err === 'NCMB_Get_Genre_Error') { utility.show_error_alert('NCMB GetGenre Error','再度やり直してください','OK'); }else if (err === 'NCMB_Get_Onomatopoeia_Error') { utility.show_error_alert('NCMB GetOnomatopoeia Error','再度やり直してください','OK'); }else if (err === 'NCMB_Set_Genre_Error') { utility.show_error_alert('NCMB SetGenre Error','再度やり直してください','OK'); }else { utility.show_tmdb_error(err); } }); //ローカルのジャンル内リストを取得する /* ・取得したリスト内になかったらIDとジャンル名を新規追加(Local DB Write) */ //ローカルのオノマトペリストを取得する /* ・取得したリスト内と同じオノマトペが含まれていなかったら新規追加(Local DB Write) */ //NCMBから映画リストを取得する /* ・リストに同じ映画が存在する場合 ・該当レコードを取得 ・オノマトペリストを取得 ・UserNameに自分のユーザを追加 ・取得したオノマトペリストからIDを割り出す ・(新規追加)オノマトペIDに割り出したIDを追加してcountを1にする ・(上書き追加)オノマトペIDと一致したcountを1増やす ・NCMB DB Write /* ・リストに同じ映画が存在しない場合 ・レコードを生成 ・あとは上記と同じかな */ //スピナー非表示 //アラート表示 //OKタップ後、検索画面に遷移 } }, /** * ジャンル関係の処理を行う * @param {[array]} genre_id_list [ユーザが追加しようとしている映画に付与済みのジャンルIDArray] * @return {[promise]} [成功時:LocalDBに記録するジャンルオブジェクト配列,失敗時:エラーステータス] */ genre: function(genre_id_list){ return new Promise(function(resolve,reject) { var genre_id_list_bridge = {}; //ジャンルIDをまたいで使用するために格納する var genre_obj_list = []; //LocalDBに記録する用のジャンルオブジェクト //NCMBからジャンルリストを取得 movieadd.get_ncmb_genres() .then(function(ncmb_genre_list) { //映画オブジェクトのジャンルIDがNCMBに存在していたら削除する for(var i = genre_id_list.length - 1; i >= 0; i--) { for(var j = 0; j < ncmb_genre_list.length; j++) { if (genre_id_list[i] == ncmb_genre_list[j].ID) { genre_id_list.splice(i,1); genre_obj_list.push({id:ncmb_genre_list[j].ID, name: ncmb_genre_list[j].Name}); } } } /*テストコード*/ // genre_id_list.push(99999); // genre_id_list.push(12345); // genre_id_list.push(88888); // genre_id_list.push(77777); return genre_id_list; }) .then(function(genre_id_list){ //NCMBに登録されていないジャンルIDが存在する場合 if (genre_id_list.length !== 0) { genre_id_list_bridge = genre_id_list; return movieadd.get_tmdb_genre_list(); }else { return {genres: []}; } }) .then(function(tmdb_genre_obj){ var tmdb_genre_list = tmdb_genre_obj.genres; //idだけの配列を作成 var tmdb_genre_id_list = []; for(var i = 0; i < tmdb_genre_list.length; i++) { tmdb_genre_id_list.push(tmdb_genre_list[i].id); } /*テストコード*/ // tmdb_genre_id_list.push(99999); // tmdb_genre_id_list.push(88888); // tmdb_genre_id_list.push(77777); // var test_obj1 = {}; // test_obj1.id = 99999; // test_obj1.name = 'hoge1'; // tmdb_genre_list.push(test_obj1); // var test_obj2 = {}; // test_obj2.id = 88888; // test_obj2.name = 'hoge2'; // tmdb_genre_list.push(test_obj2); // var test_obj5 = {}; // test_obj5.id = 12345; // test_obj5.name = 'test_obj5'; // tmdb_genre_list.push(test_obj5); // var test_obj3 = {}; // test_obj3.id = 77777; // test_obj3.name = 'hoge3'; // tmdb_genre_list.push(test_obj3); //tmdbジャンルリスト内にあったらidと名前をncmbへ新規追加する var promises = []; for(var j = 0; j < genre_id_list_bridge.length; j++) { var tmdb_index = tmdb_genre_id_list.indexOf(genre_id_list_bridge[j]); if (tmdb_index != -1) { var id = tmdb_genre_list[tmdb_index].id; var name = tmdb_genre_list[tmdb_index].name; genre_obj_list.push({id:id, name: name}); promises.push(movieadd.set_genre_ncmb(id,name)); } } return promises; }) .then(function(promises){ Promise.all(promises).then(function(results){ resolve(genre_obj_list); }) .catch(function(err){ console.log(err); reject(err); }); }) .catch(function(err){ console.log(err); reject(err); }); }); }, onomatopoeia: function(onomatopoeia_list) { return new Promise(function(resolve,reject) { var onomatopoeia_obj_list = []; //クラウドからオノマトペリストを取得 movieadd.get_ncmb_onomatopoeia() .then(function(ncmb_onomatopoeia_list) { //オノマトペ名だけの配列を作成 var onomatopoeia_name_list = []; for(var i = 0; i < ncmb_onomatopoeia_list.length; i++) { onomatopoeia_name_list.push(ncmb_onomatopoeia_list[i].Name); } var promises = []; var id_count = ncmb_onomatopoeia_list.length; for(var j = 0; j < onomatopoeia_list.length; j++) { var index = onomatopoeia_name_list.indexOf(onomatopoeia_list[j]); //NCMBのオノマトペリスト内になかったらNCMBへ新規追加 if (index == -1) { var new_id = String(id_count); var new_name = onomatopoeia_list[j]; onomatopoeia_obj_list.push({id:new_id, name:new_name}); promises.push(movieadd.set_onomatopoeia_ncmb(new_id,new_name)); id_count += 1; //存在したらNCMBからIDと名前を取得 }else { var old_id = String(ncmb_onomatopoeia_list[index].ID); var old_name = ncmb_onomatopoeia_list[index].Name; onomatopoeia_obj_list.push({id:old_id,name:old_name}); } } return promises; }) .then(function(promises) { Promise.all(promises).then(function(results) { resolve(onomatopoeia_obj_list); }) .catch(function(err){ console.log(err); }); }) .catch(function(err){ console.log(err); }); }); }, /** * NCMBのGenreデータクラス全体を取得する * @return {[object]} [Genreレコードオブジェクトが格納された1次元配列] */ get_ncmb_genres: function(){ return new Promise(function(resolve,reject) { var ncmb = utility.get_ncmb(); var Genre = ncmb.DataStore('Genre'); Genre.fetchAll().then(function(results){ resolve(results); }).catch(function(err){ reject('NCMB_Get_Genre_Error'); }); }); }, /** * NCMBのOnomatopoeiaデータクラス全体を取得する * @return {[object]} [Onomatopoeiaレコードオブジェクトが格納された1次元配列] */ get_ncmb_onomatopoeia: function(){ return new Promise(function(resolve,reject) { var ncmb = utility.get_ncmb(); var Onomatopoeia = ncmb.DataStore('Onomatopoeia'); Onomatopoeia.fetchAll().then(function(results){ resolve(results); }).catch(function(err){ reject('NCMB_Get_Onomatopoeia_Error'); }); }); }, /** * TMDBのジャンルリストを取得する * @return {[array]} [idとnameが格納されたオブジェクトArray] */ get_tmdb_genre_list: function(){ return new Promise(function(resolve, reject) { var request = new XMLHttpRequest(); var api_key = utility.get_tmdb_apikey(); var request_url = 'http://api.themoviedb.org/3/genre/movie/list?api_key=' + api_key + '&language=ja'; request.open('GET', request_url); request.setRequestHeader('Accept', 'application/json'); request.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 0) { reject(0); }else { if (this.status === 200) { var contact = JSON.parse(this.responseText); resolve(contact); }else { reject(this.status); } } } }; request.send(); }); }, /** * NCMBのGenreデータクラスへ指定されたidとnameを新規追加する * @param {[number]} id [ジャンルを識別するid(TMDBと同一)] * @param {[string]} name [日本語で表記されたジャンル名] */ set_genre_ncmb: function(id,name) { return new Promise(function(resolve,reject) { var ncmb = utility.get_ncmb(); var Genre = ncmb.DataStore('Genre'); var genre = new Genre(); genre.set('ID', id) .set('Name', name) .save() .then(function(){ resolve('OK'); }) .catch(function(err){ reject('NCMB_Set_Genre_Error'); }); }); }, set_onomatopoeia_ncmb: function(id,name) { return new Promise(function(resolve,reject) { var ncmb = utility.get_ncmb(); var Onomatopoeia = ncmb.DataStore('Onomatopoeia'); var onomatopoeia = new Onomatopoeia(); onomatopoeia.set('ID', id) .set('Name', name) .save() .then(function(){ resolve('OK'); }) .catch(function(err){ reject('NCMB_Set_Onomatopoeia_Error'); }); }); }, /** * 映画の詳細を表示している画面の気分リストをタップした際に画面遷移する */ pushpage_feeling: function(){ var callback = function(){ movieadd_feeling.show_contents(); }; utility.check_page_init('movieadd_feeling', callback); utility.pushpage('movieadd_feeling.html', 'lift', 0); }, /** * 映画の詳細を表示している画面のDVDをタップした際に画面遷移する */ pushpage_dvd: function(){ var callback = function(){ movieadd_dvd.show_contents(); }; utility.check_page_init('movieadd_dvd', callback); utility.pushpage('movieadd_dvd.html', 'lift', 0); }, /** * 登録されたリストの件数とDVD所持情報をもとにラベルを更新する関数 */ show_feelingAnddvd_label: function(){ var list_length = movieadd.userdata.feeling_name_list.length; var dvd_flag = movieadd.userdata.dvd; var dvd = 'No'; if (dvd_flag) { dvd = 'Yes'; }else { dvd = 'No'; } var list_number = document.getElementById('list_number'); var have_dvd = document.getElementById('have_dvd'); list_number.innerHTML = list_length + '件'; have_dvd.innerHTML = dvd; }, }; var movieadd_feeling = { show_contents: function(){ //アラート表示後に自動フォーカスするためのイベントを登録する movieadd_feeling.feeling_input_name_addEvent(); var nodata_message = document.getElementById('movieadd_feeling_nodata_message'); var length = movieadd.userdata.feeling_name_list.length; if (length === 0) { $('#movieadd_feeling_nodata_message').css('height', '100%'); nodata_message.innerHTML = '感情を1件以上登録してください<br>(1件につき6文字以内)'; }else { $('#movieadd_feeling_nodata_message').css('height', '0%'); nodata_message.innerHTML = ''; //リスト表示 var feeling_list = document.getElementById('feeling_list'); feeling_list.innerHTML = ''; for(var i = 0; i < length; i++) { feeling_list.innerHTML += '<h3 class="feeling_film" style="opacity: 0; margin-top: 40px;">' + movieadd.userdata.feeling_name_list[i] + '</h3>'; } //アニメーション表示 var delaySpeed = 50; var fadeSpeed = 400; $('.feeling_film').each(function(index) { $(this).delay(index*delaySpeed).animate({opacity:'1', marginTop: '20px'},fadeSpeed); }); } }, /** * アラート表示後にフォーカスを当てる処理を行う */ feeling_input_name_addEvent: function(){ document.addEventListener('postshow', function(event) { if (event.target.id == 'feeling_add_dialog') { document.getElementById('feeling_input_name').focus(); } }); }, /** * 気分を入力するアラートを表示してinputのvalueを初期化する */ show_input_alert: function(){ document.getElementById('feeling_add_dialog').show(); var input_form = document.getElementById('feeling_input_name'); input_form.value = ''; input_form.addEventListener('keyup', movieadd_feeling.check_input_form); }, /** * フォームの値を監視して登録ボタンの有効・無効を設定する関数 * @return {[type]} [description] */ check_input_form: function(){ var value = document.getElementById('feeling_input_name').value; var add_button = document.getElementById('feeling_add_button'); if (value !== '') { add_button.removeAttribute('disabled'); }else { add_button.setAttribute('disabled'); } }, /** * アラートを閉じるor閉じてリストへ追加する関数 * @param {[string]} id [cancelかadd] */ hide_input_alert: function(id){ if (id == 'cancel') { document.getElementById('feeling_add_dialog').hide(); }else { //リストへ登録して気分を表示する var feeling_name = document.getElementById('feeling_input_name').value; movieadd_feeling.add_list(feeling_name); document.getElementById('feeling_add_dialog').hide(); } }, /** * 引き数で渡された気分の文字列をリストに表示する * @param {[string]} feeling_name [ユーザが入力した気分] */ add_list: function(feeling_name){ //リスト表示 movieadd.userdata.feeling_name_list.push(feeling_name); movieadd_feeling.show_contents(); //ラベルの更新 movieadd.show_feelingAnddvd_label(); }, }; var movieadd_dvd = { /** * 保存しているラジオボタンの状態をもとにチェックをつける */ show_contents: function(){ var dvd_check = movieadd.userdata.dvd; var radio_dvd_yes = document.getElementById('radio_dvd_yes'); if (dvd_check === true) { radio_dvd_yes.checked = true; }else { radio_dvd_yes.checked = false; } }, /** * movieadd_dvd.html(DVDの所持確認画面)を閉じる時の関数 */ close_movieadd_dvd: function(){ //チェックボタンの状態を保存する var yes = document.getElementById('radio_dvd_yes').checked; if (yes === true) { movieadd.userdata.dvd = true; }else { movieadd.userdata.dvd = false; } //ラベルの更新 movieadd.show_feelingAnddvd_label(); utility.popPage(); }, }; /** * 便利関数をまとめたオブジェクト * @type {Object} */ var utility = { /** * ncmbを生成して返す * @return {[object]} [生成したncmb] */ get_ncmb: function(){ var ncmb = new NCMB('f5f6c2e3aa823eea2c500446a62c5645c04fc2fbfd9833cb173e1d876f464f6c','605298c95c0ba9c654315f11c6817e790f21f83a0e9ff60dc2fdf626b1485899'); return ncmb; }, /** * ローカルストレージの初期化をする */ delete_localstorage: function(){ var storage = window.localStorage; storage.removeItem('username'); storage.removeItem('password'); storage.removeItem('birthday'); storage.removeItem('sex'); storage.removeItem('signup_flag'); }, /** * ローカルストレージの状態を表示する */ show_localstorage: function(){ var storage = window.localStorage; var username = storage.getItem('username'); var password = storage.getItem('password'); var birthday = storage.getItem('birthday'); var sex = storage.getItem('sex'); var signup_flag = storage.getItem('signup_flag'); var obj = {'username':username, 'password':password, 'birthday':birthday, 'sex':sex, 'signup_flag':signup_flag}; console.log(obj); }, /** * 指定したページの読み込み終了後に指定したcallbackを実行する * @param {[string]} pageid [pageのid] * @param {Function} callback [読み込み終了後に実行したいコールバック関数] */ check_page_init: function(pageid,callback){ document.addEventListener('init', function(event) { if (event.target.id == pageid) { console.log(pageid + ' is inited'); callback(); } }); }, /** * データベースのオブジェクトを返す * @return {[type]} [description] */ get_database: function(){ var db = window.sqlitePlugin.openDatabase({name: 'my_db', location: 'default'}); return db; }, /** * TMDBのAPIキーを返す * @return {[string]} [TMDBのAPIキー] */ get_tmdb_apikey: function(){ return 'dcf593b3416b09594c1f13fabd1b9802'; }, /** * htmlファイル、アニメーション、delay時間を指定するとアニメーションを行って画面遷移する * @param {[string]} html_name [画面遷移したいhtmlファイル名] * @param {[string]} animation_name [アニメーション名] * @param {[number]} delaytime [Timeoutの時間] */ pushpage: function(html_name, animation_name, delaytime) { var showpage = function(){ document.getElementById('myNavigator').pushPage(html_name, { animation : animation_name }); }; setTimeout(showpage, delaytime); }, /** * onsen uiのpopPageを実行する関数 */ popPage: function(){ document.getElementById('myNavigator').popPage(); }, /** * 画面のwidth,heightを取得する * @return {[object]} [widthとheightが格納されたオブジェクト] */ getScreenSize: function() { var w = window.parent.screen.width; var h = window.parent.screen.height; var obj = {w:w,h:h}; return obj; }, /** * ブラウザで強制的にログインするための関数 * @return {[type]} [description] */ browser_signup: function(){ var callback = function(){ document.getElementById('username').value = 'ブラウザユーザ'; document.getElementById('password').value = 'password'; document.getElementById('birthday').value = '1994'; index.formcheck[0] = true; index.formcheck[1] = true; var storage = window.localStorage; storage.setItem('username', document.getElementById('username').value); storage.setItem('password', document.getElementById('password').value); storage.setItem('birthday', Number(document.getElementById('birthday').value)); storage.setItem('sex', 'M'); storage.setItem('signup_flag', true); }; utility.check_page_init('signup',callback); }, spinner: {}, //spinnerオブジェクト格納用 /** * 指定した親要素にスピナーを表示する * @param {[string]} parent [親要素のid] */ show_spinner: function(parent){ var opts = { lines: 13, //線の数 length: 8, //線の長さ width: 3, //線の幅 radius: 16, //スピナーの内側の広さ corners: 1, //角の丸み rotate: 74, //向き(あんまり意味が無い・・) direction: 1, //1:時計回り -1:反時計回り color: '#000', // 色 speed: 2.0, // 一秒間に回転する回数 trail: 71, //残像の長さ shadow: true, // 影 hwaccel: true, // ? className: 'spinner', // クラス名 zIndex: 2e9, // Z-index top: '50%', // relative TOP left: '50%', // relative LEFT opacity: 0.25, //透明度 fps: 40 //fps }; //描画先の親要素 var spin_target = document.getElementById(parent); //スピナーオブジェクト var spinner = new Spinner(opts); utility.spinner = spinner; //スピナー描画 spinner.spin(spin_target); }, /** * [スピナーの表示を止める] */ stop_spinner: function(){ utility.spinner.spin(); }, /** * エラーのアラートを表示する * @param {[string]} title [タイトル] * @param {[string]} message [メッセージ] * @param {[string]} buttonLabel [ボタンのラベル] */ show_error_alert: function(title,message,buttonLabel) { ons.notification.alert({ title: title, message: message, buttonLabel: buttonLabel}); }, /** * TMDBに関するエラーアラートを表示する * @param {[number]} err_status [エラーのHTTPstatus] */ show_tmdb_error: function(err_status) { switch(err_status) { case 0: utility.show_error_alert('通信エラー','ネットワーク接続を確認して下さい','OK'); break; case 401: utility.show_error_alert('APIエラー','有効なAPIキーを設定して下さい','OK'); break; case 404: utility.show_error_alert('Not found','リソースが見つかりませんでした','OK'); break; default: utility.show_error_alert('不明なエラー','不明なエラーが発生しました','OK'); break; } }, }; // //ローカルのデータベースにサーバから取得したmovieを記録する // function insert_movie(movies){ // var db = this.get_database(); // for (var i = 0; i < movies.length; i++) { // console.log(movies[i]); // db.executeSql("INSERT INTO movie(title, tmdb_id, genre_id, keyword_id, onomatopoeia_id, thumbnail_path, username) VALUES('title', 'tmdb_id', 'genre_id')"); // //id integer primary key, title text unique, tmdb_id integer unique, genre_id text, keyword_id text, onomatopoeia_id text, thumbnail_path text, username text // } // // db.transaction(function(tx) { // // // console.log('Open database success'); // // for (var i = 0; i >= 0; i--) { // // Things[i] // // } // // tx.executeSql('CREATE TABLE IF NOT EXISTS movie (id integer primary key, title text, tmdb_id text, genre_id text, keyword_id text, onomatopoeia_id text, thumbnail text, username text)'); // // tx.executeSql('CREATE TABLE IF NOT EXISTS Genre (id integer primary key, name text, username text)'); // // tx.executeSql('CREATE TABLE IF NOT EXISTS KeyWord (id integer primary key, name text, username text)'); // // tx.executeSql('CREATE TABLE IF NOT EXISTS Onomatopoeia (id integer primary Key, name text, joy_status text, anger_status text, sadness_status text, happiness_status text)'); // // }, function(err) { // // console.log('Open database ERROR: ' +JSON.stringify(err) +' ' + err.message); // // }); // } // //ログイン中のユーザ名が含まれるMovieオブジェクトを最新順で取得する // function get_movies_ncmbobject(username, callback){ // var ncmb = get_ncmb(); // var Movie = ncmb.DataStore("Movie"); // Movie.equalTo("UserName", username) // .order("updateDate",true) // .fetchAll() // .then(function(results){ // insert_movie(results); // callback(); // }) // .catch(function(err){ // console.log(err); // }); // } app.initialize();
オノマトペ関連のエラー処理を記述
FiNote/www/js/index.js
オノマトペ関連のエラー処理を記述
<ide><path>iNote/www/js/index.js <ide> console.log(results); <ide> }) <ide> .catch(function(err){ <del> if (err === 'NCMB_Get_Genre_Error') { <del> utility.show_error_alert('NCMB GetGenre Error','再度やり直してください','OK'); <del> }else if (err === 'NCMB_Get_Onomatopoeia_Error') { <del> utility.show_error_alert('NCMB GetOnomatopoeia Error','再度やり直してください','OK'); <del> }else if (err === 'NCMB_Set_Genre_Error') { <del> utility.show_error_alert('NCMB SetGenre Error','再度やり直してください','OK'); <del> }else { <del> utility.show_tmdb_error(err); <add> <add> switch(err) { <add> case 'NCMB_Get_Genre_Error': <add> utility.show_error_alert('NCMB GetGenre Error','再度やり直してください','OK'); <add> break; <add> <add> case 'NCMB_Get_Onomatopoeia_Error': <add> utility.show_error_alert('NCMB GetOnomatopoeia Error','再度やり直してください','OK'); <add> break; <add> <add> case 'NCMB_Set_Genre_Error': <add> utility.show_error_alert('NCMB SetGenre Error','再度やり直してください','OK'); <add> break; <add> <add> case 'NCMB_Get_Onomatopoeia_Error': <add> utility.show_error_alert('NCMB GetOnomatopoeia Error','再度やり直して下さい','OK'); <add> break; <add> <add> case 'NCMB_Set_Onomatopoeia_Error': <add> utility.show_error_alert('NCMB SetOnomatopoeia Error','再度やり直して下さい','OK'); <add> break; <add> <add> default: <add> utility.show_tmdb_error(err); <add> break; <ide> } <ide> }); <ide> <ide> }) <ide> .catch(function(err){ <ide> console.log(err); <add> reject(err); <ide> }); <ide> }) <ide> .catch(function(err){ <ide> console.log(err); <add> reject(err); <ide> }); <ide> }); <ide>
Java
apache-2.0
7f585a58eac1a3301eb12f1e9897b28150d9a749
0
nlighten/tomcat_exporter
package nl.nlighten.prometheus.tomcat; import io.prometheus.client.*; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * A servlet filter that can be configured in Tomcat's global web.xml and that provides the following metrics: * * - A Histogram with response time distribution per context * - A Gauge with the number of concurrent request per context * - A Gauge with a the number of responses per context and status code * * <p> * If you are running Tomcat in the conventional non-embedded way you should add the client_tomcat jar and all its * dependencies (see POM.XML) to the $CATALINA_BASE/lib directory or another directory on the common.loader path. * Next, add this filter to the $CATALINA_BASE/lib/web.xml, e.g.: * * <pre> * {@code * <filter> * <filter-name>ServletMetricsFilter</filter-name> * <filter-class>nl.nlighten.prometheus.TomcatServletMetricsFilter</filter-class> * <async-supported>true</async-supported> * <init-param> * <param-name>buckets</param-name> * <param-value>.01, .05, .1, .25, .5, 1, 2.5, 5, 10, 30</param-value> * </init-param> * </filter> * } * </pre> * * If you running Tomcat embedded, please check AbstractTomcatMetricsTest for example configuration. * * Example metrics being exported: * <pre> * servlet_request_seconds_bucket{"/foo", "GET", "0.1",} 1.0 * .... * servlet_request_seconds_bucket{"/foo", "GET", "+Inf",} 1.0 * servlet_request_concurrent_total{"/foo",} 1.0 * servlet_response_status_total{"/foo", "200",} 1.0 * </pre> */ public class TomcatServletMetricsFilter implements Filter { private static final String BUCKET_CONFIG_PARAM = "buckets"; private static Histogram servletLatency; private static Gauge servletConcurrentRequest; private static Gauge servletStatusCodes; private static int UNDEFINED_HTTP_STATUS = 999; @Override public void init(FilterConfig filterConfig) throws ServletException { if (servletLatency == null) { Histogram.Builder servletLatencyBuilder = Histogram.build() .name("servlet_request_seconds") .help("The time taken fulfilling servlet requests") .labelNames("context", "method"); if ((filterConfig.getInitParameter(BUCKET_CONFIG_PARAM) != null) && (!filterConfig.getInitParameter(BUCKET_CONFIG_PARAM).isEmpty())) { String[] bucketParams = filterConfig.getInitParameter(BUCKET_CONFIG_PARAM).split(","); double[] buckets = new double[bucketParams.length]; for (int i = 0; i < bucketParams.length; i++) { buckets[i] = Double.parseDouble(bucketParams[i].trim()); } servletLatencyBuilder.buckets(buckets); } else { servletLatencyBuilder.buckets(.01, .05, .1, .25, .5, 1, 2.5, 5, 10, 30); } servletLatency = servletLatencyBuilder.register(); Gauge.Builder servletConcurrentRequestBuilder = Gauge.build() .name("servlet_request_concurrent_total") .help("Number of concurrent requests for given context.") .labelNames("context"); servletConcurrentRequest = servletConcurrentRequestBuilder.register(); Gauge.Builder servletStatusCodesBuilder = Gauge.build() .name("servlet_response_status_total") .help("Number of requests for given context and status code.") .labelNames("context", "status"); servletStatusCodes = servletStatusCodesBuilder.register(); } } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (!(servletRequest instanceof HttpServletRequest)) { filterChain.doFilter(servletRequest, servletResponse); return; } HttpServletRequest request = (HttpServletRequest) servletRequest; if (!request.isAsyncStarted()) { String context = getContext(request); servletConcurrentRequest.labels(context).inc(); Histogram.Timer timer = servletLatency .labels(context, request.getMethod()) .startTimer(); try { filterChain.doFilter(servletRequest, servletResponse); } finally { timer.observeDuration(); servletConcurrentRequest.labels(context).dec(); servletStatusCodes.labels(context, Integer.toString(getStatus((HttpServletResponse) servletResponse))).inc(); } } else { filterChain.doFilter(servletRequest, servletResponse); } } private int getStatus(HttpServletResponse response) { try { return response.getStatus(); } catch (Exception ex) { return UNDEFINED_HTTP_STATUS; } } private String getContext(HttpServletRequest request) { if (request.getContextPath() != null && !request.getContextPath().isEmpty()) { return request.getContextPath(); } else { return "/"; } } @Override public void destroy() { // NOOP } }
client/src/main/java/nl/nlighten/prometheus/tomcat/TomcatServletMetricsFilter.java
package nl.nlighten.prometheus.tomcat; import io.prometheus.client.*; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * A servlet filter that can be configured in Tomcat's global web.xml and that provides the following metrics: * * - A Histogram with response time distribution per context * - A Gauge with the number of concurrent request per context * - A Gauge with a the number of responses per context and status code * * <p> * If you are running Tomcat in the conventional non-embedded way you should add the client_tomcat jar and all its * dependencies (see POM.XML) to the $CATALINA_BASE/lib directory or another directory on the common.loader path. * Next, add this filter to the $CATALINA_BASE/lib/web.xml, e.g.: * * <pre> * {@code * <filter> * <filter-name>ServletMetricsFilter</filter-name> * <filter-class>nl.nlighten.prometheus.TomcatServletMetricsFilter</filter-class> * <async-supported>true</async-supported> * <init-param> * <param-name>buckets</param-name> * <param-value>.01, .05, .1, .25, .5, 1, 2.5, 5, 10, 30</param-value> * </init-param> * </filter> * } * </pre> * * If you running Tomcat embedded, please check AbstractTomcatMetricsTest for example configuration. * * Example metrics being exported: * <pre> * servlet_request_seconds_bucket{"/foo", "GET", "0.1",} 1.0 * .... * servlet_request_seconds_bucket{"/foo", "GET", "+Inf",} 1.0 * servlet_request_concurrent_total{"/foo",} 1.0 * servlet_response_status_total{"/foo", "200",} 1.0 * </pre> */ public class TomcatServletMetricsFilter implements Filter { private static final String BUCKET_CONFIG_PARAM = "buckets"; private static Histogram servletLatency; private static Gauge servletConcurrentRequest; private static Gauge servletStatusCodes; private static int UNDEFINED_HTTP_STATUS = 999; @Override public void init(FilterConfig filterConfig) throws ServletException { if (servletLatency == null) { Histogram.Builder servletLatencyBuilder = Histogram.build() .name("servlet_request_seconds") .help("The time taken fulfilling servlet requests") .labelNames("context", "method"); if ((filterConfig.getInitParameter(BUCKET_CONFIG_PARAM) != null) && (!filterConfig.getInitParameter(BUCKET_CONFIG_PARAM).isEmpty())) { String[] bucketParams = filterConfig.getInitParameter(BUCKET_CONFIG_PARAM).split(","); double[] buckets = new double[bucketParams.length]; for (int i = 0; i < bucketParams.length; i++) { buckets[i] = Double.parseDouble(bucketParams[i]); } servletLatencyBuilder.buckets(buckets); } else { servletLatencyBuilder.buckets(.01, .05, .1, .25, .5, 1, 2.5, 5, 10, 30); } servletLatency = servletLatencyBuilder.register(); Gauge.Builder servletConcurrentRequestBuilder = Gauge.build() .name("servlet_request_concurrent_total") .help("Number of concurrent requests for given context.") .labelNames("context"); servletConcurrentRequest = servletConcurrentRequestBuilder.register(); Gauge.Builder servletStatusCodesBuilder = Gauge.build() .name("servlet_response_status_total") .help("Number of requests for given context and status code.") .labelNames("context", "status"); servletStatusCodes = servletStatusCodesBuilder.register(); } } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (!(servletRequest instanceof HttpServletRequest)) { filterChain.doFilter(servletRequest, servletResponse); return; } HttpServletRequest request = (HttpServletRequest) servletRequest; if (!request.isAsyncStarted()) { String context = getContext(request); servletConcurrentRequest.labels(context).inc(); Histogram.Timer timer = servletLatency .labels(context, request.getMethod()) .startTimer(); try { filterChain.doFilter(servletRequest, servletResponse); } finally { timer.observeDuration(); servletConcurrentRequest.labels(context).dec(); servletStatusCodes.labels(context, Integer.toString(getStatus((HttpServletResponse) servletResponse))).inc(); } } else { filterChain.doFilter(servletRequest, servletResponse); } } private int getStatus(HttpServletResponse response) { try { return response.getStatus(); } catch (Exception ex) { return UNDEFINED_HTTP_STATUS; } } private String getContext(HttpServletRequest request) { if (request.getContextPath() != null && !request.getContextPath().isEmpty()) { return request.getContextPath(); } else { return "/"; } } @Override public void destroy() { // NOOP } }
trim buckets before parsing as double
client/src/main/java/nl/nlighten/prometheus/tomcat/TomcatServletMetricsFilter.java
trim buckets before parsing as double
<ide><path>lient/src/main/java/nl/nlighten/prometheus/tomcat/TomcatServletMetricsFilter.java <ide> import javax.servlet.ServletException; <ide> import javax.servlet.ServletRequest; <ide> import javax.servlet.ServletResponse; <del>import javax.servlet.annotation.WebFilter; <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> import java.io.IOException; <ide> String[] bucketParams = filterConfig.getInitParameter(BUCKET_CONFIG_PARAM).split(","); <ide> double[] buckets = new double[bucketParams.length]; <ide> for (int i = 0; i < bucketParams.length; i++) { <del> buckets[i] = Double.parseDouble(bucketParams[i]); <add> buckets[i] = Double.parseDouble(bucketParams[i].trim()); <ide> } <ide> servletLatencyBuilder.buckets(buckets); <ide> } else {
Java
apache-2.0
c5b7d7b446cfefc8658b68b113ce84c199ff10f7
0
redlink-gmbh/smarti,redlink-gmbh/smarti,redlink-gmbh/smarti,redlink-gmbh/smarti,redlink-gmbh/smarti
/* * Copyright 2017 Redlink GmbH * * 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 io.redlink.smarti.webservice; import io.redlink.smarti.api.QueryBuilder; import io.redlink.smarti.api.StoreService; import io.redlink.smarti.model.*; import io.redlink.smarti.model.config.ComponentConfiguration; import io.redlink.smarti.model.config.Configuration; import io.redlink.smarti.model.result.Result; import io.redlink.smarti.services.ConfigurationService; import io.redlink.smarti.services.ConversationService; import io.redlink.smarti.services.QueryBuilderService; import io.redlink.smarti.utils.ResponseEntities; import io.redlink.smarti.webservice.pojo.QueryUpdate; import io.redlink.smarti.webservice.pojo.TemplateResponse; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.bson.types.ObjectId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.MimeTypeUtils; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.util.Map.Entry; import java.util.Optional; /** * */ @CrossOrigin @RestController @RequestMapping(value = "conversation", produces = MimeTypeUtils.APPLICATION_JSON_VALUE) @Api("conversation") public class ConversationWebservice { private final Logger log = LoggerFactory.getLogger(getClass()); @SuppressWarnings("unused") private enum Vote { up(1), down(-1); private final int delta; Vote(int delta) { this.delta = delta; } public int getDelta() { return delta; } } @Autowired private StoreService storeService; @Autowired private ConversationService conversationService; @Autowired private QueryBuilderService queryBuilderService; @Autowired private ConfigurationService configService; @ApiOperation(value = "create a conversation") @ApiResponses({ @ApiResponse(code = 201, message = "Created", response = Conversation.class) }) @RequestMapping(method = RequestMethod.POST) public ResponseEntity<?> createConversation(@RequestBody(required = false) Conversation conversation) { conversation = Optional.ofNullable(conversation).orElseGet(Conversation::new); // Create a new Conversation -> id must be null conversation.setId(null); return ResponseEntity.status(HttpStatus.CREATED).body(storeService.store(conversation)); } @ApiOperation(value = "retrieve a conversation", response = Conversation.class) @RequestMapping(value = "{id}", method = RequestMethod.GET) public ResponseEntity<?> getConversation(@PathVariable("id") ObjectId id) { final Conversation conversation = storeService.get(id); if (conversation == null) { return ResponseEntity.notFound().build(); } else { return ResponseEntity.ok(conversation); } } @ApiOperation(value = "update a conversation", response = Conversation.class) @RequestMapping(value = "{id}", method = RequestMethod.PUT, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE) public ResponseEntity<?> updateConversation(@PathVariable("id") ObjectId id, @RequestBody Conversation conversation) { // make sure the id is the right one conversation.setId(id); // todo: some additional checks? return ResponseEntity.ok(storeService.store(conversation)); } @ApiOperation(value = "append a message to the conversation", response = Conversation.class) @RequestMapping(value = "{id}/message", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE) public ResponseEntity<?> addMessage(@PathVariable("id") ObjectId id, @RequestBody Message message) { final Conversation conversation = storeService.get(id); if (conversation == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(conversationService.appendMessage(conversation, message)); } @ApiOperation(value = "up-/down-vote a message within a conversation", response = Conversation.class) @RequestMapping(value = "{id}/message/{messageId}/{vote}", method = RequestMethod.PUT) public ResponseEntity<?> rateMessage(@PathVariable("id") ObjectId conversationId, @PathVariable("messageId") String messageId, @PathVariable("vote") Vote vote) { final Conversation conversation = storeService.get(conversationId); if (conversation == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(conversationService.rateMessage(conversation, messageId, vote.getDelta())); } @ApiOperation(value = "retrieve the analysis result of the conversation", response = Token.class, responseContainer = "List") @RequestMapping(value = "{id}/analysis", method = RequestMethod.GET) public ResponseEntity<?> prepare(@PathVariable("id") ObjectId id) { final Conversation conversation = storeService.get(id); if (conversation == null) { return ResponseEntity.notFound().build(); } else { return ResponseEntity.ok(conversation.getTokens()); } } @ApiOperation(value = "retrieve the intents of the conversation", response = TemplateResponse.class) @RequestMapping(value = "{id}/template", method = RequestMethod.GET) public ResponseEntity<?> query(@PathVariable("id") ObjectId id) { final Conversation conversation = storeService.get(id); if (conversation == null) { return ResponseEntity.notFound().build(); } else { return ResponseEntity.ok(TemplateResponse.from(conversation)); } } @ApiOperation(value = "retrieve the results for a template from a specific creator", response = Result.class, responseContainer = "List") @RequestMapping(value = "{id}/template/{template}/{creator}", method = RequestMethod.GET) public ResponseEntity<?> getResults(@PathVariable("id") ObjectId id, @PathVariable("template") int templateIdx, @PathVariable("creator") String creator) { final Conversation conversation = storeService.get(id); if (conversation == null) { return ResponseEntity.notFound().build(); } try { final Template template = conversation.getTemplates().get(templateIdx); return ResponseEntity.ok(conversationService.getInlineResults(conversation, template, creator)); } catch (IOException e) { return ResponseEntities.serviceUnavailable(e.getMessage(), e); } catch (IndexOutOfBoundsException e) { return ResponseEntity.notFound().build(); } } @ApiOperation(value = "update a query based on new slot-assignments", response = Query.class) @RequestMapping(value = "{id}/query/{template}/{creator}", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE) public ResponseEntity<?> getQuery(@PathVariable("id") ObjectId id, @PathVariable("template") int templateIdx, @PathVariable("creator") String creator, @RequestBody QueryUpdate queryUpdate) { Conversation conversation = storeService.get(id); if (conversation == null) { return ResponseEntity.notFound().build(); } Configuration clientConf = configService.getConfiguration(conversation.getClientId()); if(clientConf == null){ return ResponseEntity.notFound().build(); } Configuration conf = configService.getConfiguration(conversation.getClientId()); if(conf == null){ log.info("Client {} of Conversation {} has no longer a configuration assigned ... returning 404 NOT FOUND", conversation.getChannelId(), conversation.getId()); return ResponseEntity.notFound().build(); } final Template template = conversation.getTemplates().get(templateIdx); if (template == null) return ResponseEntity.notFound().build(); //only update the single requested query final Entry<QueryBuilder<ComponentConfiguration>, ComponentConfiguration> builderContext = queryBuilderService.getQueryBuilder(creator,conf); if (builderContext == null) { return ResponseEntity.notFound().build(); } //now that we have everything perform and store the updates to the conversation conversation.setTokens(queryUpdate.getTokens()); template.setSlots(queryUpdate.getSlots()); conversation = storeService.store(conversation); try { builderContext.getKey().buildQuery(conversation, builderContext.getValue()); storeService.storeIfUnmodifiedSince(conversation, conversation.getLastModified()); return ResponseEntity.ok(template.getQueries()); } catch (IndexOutOfBoundsException e) { return ResponseEntity.notFound().build(); } } @ApiOperation(value = "complete a conversation and add it to indexing", response = Conversation.class) @RequestMapping(value = "{id}/publish", method = RequestMethod.POST) public ResponseEntity<?> complete(@PathVariable("id") ObjectId id) { final Conversation conversation = storeService.get(id); if (conversation == null) { return ResponseEntity.notFound().build(); } else { conversation.getMeta().setStatus(ConversationMeta.Status.Complete); return ResponseEntity.ok(conversationService.completeConversation(conversation)); } } }
application/src/main/java/io/redlink/smarti/webservice/ConversationWebservice.java
/* * Copyright 2017 Redlink GmbH * * 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 io.redlink.smarti.webservice; import io.redlink.smarti.api.QueryBuilder; import io.redlink.smarti.api.StoreService; import io.redlink.smarti.model.*; import io.redlink.smarti.model.config.ComponentConfiguration; import io.redlink.smarti.model.config.Configuration; import io.redlink.smarti.model.result.Result; import io.redlink.smarti.services.ConfigurationService; import io.redlink.smarti.services.ConversationService; import io.redlink.smarti.services.QueryBuilderService; import io.redlink.smarti.utils.ResponseEntities; import io.redlink.smarti.webservice.pojo.QueryUpdate; import io.redlink.smarti.webservice.pojo.TemplateResponse; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.MimeTypeUtils; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.util.Optional; /** * */ @CrossOrigin @RestController @RequestMapping(value = "conversation", produces = MimeTypeUtils.APPLICATION_JSON_VALUE) @Api("conversation") public class ConversationWebservice { @SuppressWarnings("unused") private enum Vote { up(1), down(-1); private final int delta; Vote(int delta) { this.delta = delta; } public int getDelta() { return delta; } } @Autowired private StoreService storeService; @Autowired private ConversationService conversationService; @Autowired private QueryBuilderService queryBuilderService; @Autowired private ConfigurationService configService; @ApiOperation(value = "create a conversation") @ApiResponses({ @ApiResponse(code = 201, message = "Created", response = Conversation.class) }) @RequestMapping(method = RequestMethod.POST) public ResponseEntity<?> createConversation(@RequestBody(required = false) Conversation conversation) { conversation = Optional.ofNullable(conversation).orElseGet(Conversation::new); // Create a new Conversation -> id must be null conversation.setId(null); return ResponseEntity.status(HttpStatus.CREATED).body(storeService.store(conversation)); } @ApiOperation(value = "retrieve a conversation", response = Conversation.class) @RequestMapping(value = "{id}", method = RequestMethod.GET) public ResponseEntity<?> getConversation(@PathVariable("id") ObjectId id) { final Conversation conversation = storeService.get(id); if (conversation == null) { return ResponseEntity.notFound().build(); } else { return ResponseEntity.ok(conversation); } } @ApiOperation(value = "update a conversation", response = Conversation.class) @RequestMapping(value = "{id}", method = RequestMethod.PUT, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE) public ResponseEntity<?> updateConversation(@PathVariable("id") ObjectId id, @RequestBody Conversation conversation) { // make sure the id is the right one conversation.setId(id); // todo: some additional checks? return ResponseEntity.ok(storeService.store(conversation)); } @ApiOperation(value = "append a message to the conversation", response = Conversation.class) @RequestMapping(value = "{id}/message", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE) public ResponseEntity<?> addMessage(@PathVariable("id") ObjectId id, @RequestBody Message message) { final Conversation conversation = storeService.get(id); if (conversation == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(conversationService.appendMessage(conversation, message)); } @ApiOperation(value = "up-/down-vote a message within a conversation", response = Conversation.class) @RequestMapping(value = "{id}/message/{messageId}/{vote}", method = RequestMethod.PUT) public ResponseEntity<?> rateMessage(@PathVariable("id") ObjectId conversationId, @PathVariable("messageId") String messageId, @PathVariable("vote") Vote vote) { final Conversation conversation = storeService.get(conversationId); if (conversation == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(conversationService.rateMessage(conversation, messageId, vote.getDelta())); } @ApiOperation(value = "retrieve the analysis result of the conversation", response = Token.class, responseContainer = "List") @RequestMapping(value = "{id}/analysis", method = RequestMethod.GET) public ResponseEntity<?> prepare(@PathVariable("id") ObjectId id) { final Conversation conversation = storeService.get(id); if (conversation == null) { return ResponseEntity.notFound().build(); } else { return ResponseEntity.ok(conversation.getTokens()); } } @ApiOperation(value = "retrieve the intents of the conversation", response = TemplateResponse.class) @RequestMapping(value = "{id}/template", method = RequestMethod.GET) public ResponseEntity<?> query(@PathVariable("id") ObjectId id) { final Conversation conversation = storeService.get(id); if (conversation == null) { return ResponseEntity.notFound().build(); } else { return ResponseEntity.ok(TemplateResponse.from(conversation)); } } @ApiOperation(value = "retrieve the results for a template from a specific creator", response = Result.class, responseContainer = "List") @RequestMapping(value = "{id}/template/{template}/{creator}", method = RequestMethod.GET) public ResponseEntity<?> getResults(@PathVariable("id") ObjectId id, @PathVariable("template") int templateIdx, @PathVariable("creator") String creator) { final Conversation conversation = storeService.get(id); if (conversation == null) { return ResponseEntity.notFound().build(); } try { final Template template = conversation.getTemplates().get(templateIdx); return ResponseEntity.ok(conversationService.getInlineResults(conversation, template, creator)); } catch (IOException e) { return ResponseEntities.serviceUnavailable(e.getMessage(), e); } catch (IndexOutOfBoundsException e) { return ResponseEntity.notFound().build(); } } @ApiOperation(value = "update a query based on new slot-assignments", response = Query.class) @RequestMapping(value = "{id}/query/{template}/{creator}", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE) public ResponseEntity<?> getQuery(@PathVariable("id") ObjectId id, @PathVariable("template") int templateIdx, @PathVariable("creator") String creator, @RequestBody QueryUpdate queryUpdate) { //FIXME: does this really work as intended? Conversation conversation = storeService.get(id); if (conversation == null) { return ResponseEntity.notFound().build(); } Configuration clientConf = configService.getConfiguration(conversation.getClientId()); if(clientConf == null){ return ResponseEntity.notFound().build(); } final Template template = conversation.getTemplates().get(templateIdx); if (template == null) return ResponseEntity.notFound().build(); final QueryBuilder builder = queryBuilderService.getQueryBuilder(creator); if (builder == null) return ResponseEntity.notFound().build(); //now that we have everything perform and store the updates to the conversation conversation.setTokens(queryUpdate.getTokens()); template.setSlots(queryUpdate.getSlots()); conversation = storeService.store(conversation); try { for(ComponentConfiguration cc : (Iterable<ComponentConfiguration>)clientConf.getConfigurations(builder)){ builder.buildQuery(conversation, cc); } storeService.storeIfUnmodifiedSince(conversation, conversation.getLastModified()); return ResponseEntity.ok(template.getQueries()); } catch (IndexOutOfBoundsException e) { return ResponseEntity.notFound().build(); } } @ApiOperation(value = "complete a conversation and add it to indexing", response = Conversation.class) @RequestMapping(value = "{id}/publish", method = RequestMethod.POST) public ResponseEntity<?> complete(@PathVariable("id") ObjectId id) { final Conversation conversation = storeService.get(id); if (conversation == null) { return ResponseEntity.notFound().build(); } else { conversation.getMeta().setStatus(ConversationMeta.Status.Complete); return ResponseEntity.ok(conversationService.completeConversation(conversation)); } } }
the `getQuery(..)` now supports the new QueryBuilder <-> Query.creator() mapping
application/src/main/java/io/redlink/smarti/webservice/ConversationWebservice.java
the `getQuery(..)` now supports the new QueryBuilder <-> Query.creator() mapping
<ide><path>pplication/src/main/java/io/redlink/smarti/webservice/ConversationWebservice.java <ide> import io.swagger.annotations.ApiResponse; <ide> import io.swagger.annotations.ApiResponses; <ide> import org.bson.types.ObjectId; <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <ide> import org.springframework.beans.factory.annotation.Autowired; <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.http.ResponseEntity; <ide> import org.springframework.web.bind.annotation.*; <ide> <ide> import java.io.IOException; <add>import java.util.Map.Entry; <ide> import java.util.Optional; <ide> <ide> <ide> @Api("conversation") <ide> public class ConversationWebservice { <ide> <add> private final Logger log = LoggerFactory.getLogger(getClass()); <add> <ide> @SuppressWarnings("unused") <ide> private enum Vote { <ide> up(1), <ide> @PathVariable("template") int templateIdx, <ide> @PathVariable("creator") String creator, <ide> @RequestBody QueryUpdate queryUpdate) { <del> //FIXME: does this really work as intended? <ide> Conversation conversation = storeService.get(id); <ide> if (conversation == null) { <ide> return ResponseEntity.notFound().build(); <ide> if(clientConf == null){ <ide> return ResponseEntity.notFound().build(); <ide> } <add> Configuration conf = configService.getConfiguration(conversation.getClientId()); <add> if(conf == null){ <add> log.info("Client {} of Conversation {} has no longer a configuration assigned ... returning 404 NOT FOUND", <add> conversation.getChannelId(), conversation.getId()); <add> return ResponseEntity.notFound().build(); <add> } <ide> final Template template = conversation.getTemplates().get(templateIdx); <ide> if (template == null) return ResponseEntity.notFound().build(); <del> final QueryBuilder builder = queryBuilderService.getQueryBuilder(creator); <del> if (builder == null) return ResponseEntity.notFound().build(); <add> <add> //only update the single requested query <add> final Entry<QueryBuilder<ComponentConfiguration>, ComponentConfiguration> builderContext = queryBuilderService.getQueryBuilder(creator,conf); <add> if (builderContext == null) { <add> return ResponseEntity.notFound().build(); <add> } <ide> <ide> //now that we have everything perform and store the updates to the conversation <ide> conversation.setTokens(queryUpdate.getTokens()); <ide> conversation = storeService.store(conversation); <ide> <ide> try { <del> for(ComponentConfiguration cc : (Iterable<ComponentConfiguration>)clientConf.getConfigurations(builder)){ <del> builder.buildQuery(conversation, cc); <del> } <add> builderContext.getKey().buildQuery(conversation, builderContext.getValue()); <ide> storeService.storeIfUnmodifiedSince(conversation, conversation.getLastModified()); <ide> return ResponseEntity.ok(template.getQueries()); <ide> } catch (IndexOutOfBoundsException e) {
Java
apache-2.0
762eb5e40b255d354446b28d4007b1bd0206d2c3
0
dialob/dialob-api,dialob/dialob-api
/* * Copyright 2018 ReSys 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 io.dialob.api.form; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import io.dialob.api.annotation.Nullable; import org.immutables.gson.Gson; import org.immutables.value.Value; import javax.validation.constraints.NotNull; import java.util.Date; @Value.Immutable @JsonSerialize(as = ImmutableFormTag.class) @JsonDeserialize(as = ImmutableFormTag.class) @Gson.TypeAdapters @JsonInclude(content = JsonInclude.Include.NON_NULL, value = JsonInclude.Include.NON_EMPTY) @Value.Style(validationMethod = Value.Style.ValidationMethod.NONE, jdkOnly = true) public interface FormTag { enum Type { NORMAL, MUTABLE } @NotNull String getFormName(); @NotNull String getName(); @Nullable Date getCreated(); @Nullable String getFormId(); @Nullable String getDescription(); @NotNull @Value.Default default Type getType() { return Type.NORMAL; } }
dialob-api/src/main/java/io/dialob/api/form/FormTag.java
/* * Copyright 2018 ReSys 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 io.dialob.api.form; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import io.dialob.api.annotation.Nullable; import org.immutables.gson.Gson; import org.immutables.value.Value; import javax.validation.constraints.NotNull; import java.util.Date; @Value.Immutable @JsonSerialize(as = ImmutableFormTag.class) @JsonDeserialize(as = ImmutableFormTag.class) @Gson.TypeAdapters @JsonInclude(content = JsonInclude.Include.NON_NULL, value = JsonInclude.Include.NON_EMPTY) @Value.Style(validationMethod = Value.Style.ValidationMethod.NONE, jdkOnly = true) public interface FormTag { @NotNull String getFormName(); @NotNull String getName(); @Nullable Date getCreated(); @Nullable String getFormId(); @Nullable String getDescription(); }
added type attribute on tag
dialob-api/src/main/java/io/dialob/api/form/FormTag.java
added type attribute on tag
<ide><path>ialob-api/src/main/java/io/dialob/api/form/FormTag.java <ide> @Value.Style(validationMethod = Value.Style.ValidationMethod.NONE, jdkOnly = true) <ide> public interface FormTag { <ide> <add> enum Type { <add> NORMAL, <add> MUTABLE <add> } <add> <ide> @NotNull <ide> String getFormName(); <ide> <ide> @Nullable <ide> String getDescription(); <ide> <add> @NotNull <add> @Value.Default <add> default Type getType() { <add> return Type.NORMAL; <add> } <add> <ide> }
Java
apache-2.0
d5e776367fd4e063e64acd7343fb261cc924b05a
0
michaelgallacher/intellij-community,asedunov/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,dslomov/intellij-community,signed/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,da1z/intellij-community,robovm/robovm-studio,supersven/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,signed/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,retomerz/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,holmes/intellij-community,allotria/intellij-community,robovm/robovm-studio,fitermay/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,ernestp/consulo,kdwink/intellij-community,Lekanich/intellij-community,caot/intellij-community,suncycheng/intellij-community,allotria/intellij-community,gnuhub/intellij-community,allotria/intellij-community,signed/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,slisson/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,signed/intellij-community,ahb0327/intellij-community,samthor/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,caot/intellij-community,supersven/intellij-community,samthor/intellij-community,dslomov/intellij-community,allotria/intellij-community,holmes/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,semonte/intellij-community,xfournet/intellij-community,clumsy/intellij-community,ryano144/intellij-community,izonder/intellij-community,ernestp/consulo,akosyakov/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,samthor/intellij-community,adedayo/intellij-community,samthor/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,caot/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,FHannes/intellij-community,holmes/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,blademainer/intellij-community,hurricup/intellij-community,fitermay/intellij-community,apixandru/intellij-community,izonder/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,kdwink/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,diorcety/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,kool79/intellij-community,nicolargo/intellij-community,kool79/intellij-community,consulo/consulo,nicolargo/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,retomerz/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,asedunov/intellij-community,adedayo/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,semonte/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,akosyakov/intellij-community,caot/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,signed/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,ahb0327/intellij-community,signed/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,supersven/intellij-community,da1z/intellij-community,gnuhub/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,gnuhub/intellij-community,da1z/intellij-community,hurricup/intellij-community,da1z/intellij-community,petteyg/intellij-community,vladmm/intellij-community,da1z/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,slisson/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,ernestp/consulo,pwoodworth/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,slisson/intellij-community,vladmm/intellij-community,supersven/intellij-community,tmpgit/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,samthor/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,consulo/consulo,apixandru/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,samthor/intellij-community,da1z/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,caot/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,kdwink/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,xfournet/intellij-community,allotria/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,slisson/intellij-community,dslomov/intellij-community,ibinti/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,ernestp/consulo,ibinti/intellij-community,holmes/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,consulo/consulo,SerCeMan/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,caot/intellij-community,da1z/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,caot/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,ibinti/intellij-community,izonder/intellij-community,orekyuu/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,consulo/consulo,apixandru/intellij-community,xfournet/intellij-community,izonder/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,da1z/intellij-community,jagguli/intellij-community,caot/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,semonte/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,blademainer/intellij-community,hurricup/intellij-community,apixandru/intellij-community,kdwink/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,allotria/intellij-community,fnouama/intellij-community,da1z/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,signed/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,kool79/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,retomerz/intellij-community,ernestp/consulo,vvv1559/intellij-community,kdwink/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,izonder/intellij-community,supersven/intellij-community,ryano144/intellij-community,xfournet/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,jagguli/intellij-community,ernestp/consulo,retomerz/intellij-community,nicolargo/intellij-community,semonte/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,allotria/intellij-community,holmes/intellij-community,hurricup/intellij-community,ibinti/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,izonder/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,samthor/intellij-community,allotria/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,orekyuu/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,adedayo/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,kool79/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,signed/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,FHannes/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,consulo/consulo,caot/intellij-community,slisson/intellij-community,jagguli/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,holmes/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,izonder/intellij-community,apixandru/intellij-community,fitermay/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,adedayo/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,vladmm/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,clumsy/intellij-community,retomerz/intellij-community,fnouama/intellij-community,supersven/intellij-community,ibinti/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,diorcety/intellij-community,blademainer/intellij-community,vladmm/intellij-community,samthor/intellij-community,apixandru/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,xfournet/intellij-community,asedunov/intellij-community,petteyg/intellij-community,allotria/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,allotria/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,consulo/consulo,fitermay/intellij-community,amith01994/intellij-community,ibinti/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,caot/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,slisson/intellij-community,jagguli/intellij-community,ryano144/intellij-community,diorcety/intellij-community,ryano144/intellij-community,xfournet/intellij-community,clumsy/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,vladmm/intellij-community,jagguli/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,apixandru/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,supersven/intellij-community,kool79/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,ryano144/intellij-community,samthor/intellij-community,samthor/intellij-community,Distrotech/intellij-community,izonder/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,semonte/intellij-community,retomerz/intellij-community
/* * Copyright 2000-2009 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 org.jetbrains.plugins.groovy.lang.psi.patterns; import com.intellij.openapi.util.Condition; import com.intellij.patterns.*; import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMethod; import com.intellij.psi.impl.source.tree.LeafPsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.InheritanceUtil; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrLiteralImpl; import static org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes.mGSTRING_LITERAL; import static org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes.mSTRING_LITERAL; public class GroovyPatterns extends PsiJavaPatterns { public static GroovyElementPattern groovyElement() { return new GroovyElementPattern.Capture<GroovyPsiElement>(GroovyPsiElement.class); } public static GroovyBinaryExpressionPattern groovyBinaryExpression() { return new GroovyBinaryExpressionPattern(); } public static GroovyAssignmentExpressionPattern groovyAssignmentExpression() { return new GroovyAssignmentExpressionPattern(); } public static GroovyElementPattern.Capture<GrLiteral> groovyLiteralExpression() { return groovyLiteralExpression(null); } public static GroovyElementPattern.Capture<GrLiteral> groovyLiteralExpression(final ElementPattern value) { return new GroovyElementPattern.Capture<GrLiteral>(new InitialPatternCondition<GrLiteral>(GrLiteral.class) { public boolean accepts(@Nullable final Object o, final ProcessingContext context) { return o instanceof GrLiteral && (value == null || value.accepts(((GrLiteral)o).getValue(), context)); } }); } public static GroovyElementPattern.Capture<GroovyPsiElement> rightOfAssignment(final ElementPattern<? extends GroovyPsiElement> value, final GroovyAssignmentExpressionPattern assignment) { return new GroovyElementPattern.Capture<GroovyPsiElement>(new InitialPatternCondition<GroovyPsiElement>(GroovyPsiElement.class) { @Override public boolean accepts(@Nullable Object o, ProcessingContext context) { if (!(o instanceof GroovyPsiElement)) return false; PsiElement parent = ((GroovyPsiElement)o).getParent(); if (!(parent instanceof GrAssignmentExpression)) return false; if (((GrAssignmentExpression)parent).getRValue() != o) return false; return assignment.getCondition().accepts(parent, context) && value.getCondition().accepts(o, context); } }); } public static GroovyElementPattern.Capture<GrLiteralImpl> stringLiteral() { return new GroovyElementPattern.Capture<GrLiteralImpl>(new InitialPatternCondition<GrLiteralImpl>(GrLiteralImpl.class) { public boolean accepts(@Nullable final Object o, final ProcessingContext context) { if (!(o instanceof GrLiteralImpl)) return false; return ((GrLiteralImpl)o).isStringLiteral(); } }); } public static GroovyElementPattern.Capture<GrLiteralImpl> namedArgumentStringLiteral() { return stringLiteral().withParent(psiElement(GrNamedArgument.class)); } public static GroovyElementPattern.Capture<GrArgumentLabel> namedArgumentLabel(@Nullable final ElementPattern<? extends String> namePattern) { return new GroovyElementPattern.Capture<GrArgumentLabel>(new InitialPatternCondition<GrArgumentLabel>(GrArgumentLabel.class) { public boolean accepts(@Nullable final Object o, final ProcessingContext context) { if (o instanceof GrArgumentLabel) { PsiElement nameElement = ((GrArgumentLabel)o).getNameElement(); if (nameElement instanceof LeafPsiElement) { IElementType elementType = ((LeafPsiElement)nameElement).getElementType(); if (elementType == GroovyElementTypes.mIDENT || CommonClassNames.JAVA_LANG_STRING.equals(TypesUtil.getPsiTypeName(elementType))) { return namePattern == null || namePattern.accepts(((GrArgumentLabel)o).getName()); } } } return false; } }); } public static GroovyElementPattern.Capture<GrNamedArgument> methodNamedParameter(@Nullable final ElementPattern<? extends GrCall> methodCall) { return new GroovyElementPattern.Capture<GrNamedArgument>(new InitialPatternCondition<GrNamedArgument>(GrNamedArgument.class) { public boolean accepts(@Nullable final Object o, final ProcessingContext context) { if (!(o instanceof GrNamedArgument)) return false; PsiElement parent = ((GrNamedArgument)o).getParent(); PsiElement eMethodCall; if (parent instanceof GrArgumentList) { eMethodCall = parent.getParent(); } else { if (!(parent instanceof GrListOrMap)) return false; PsiElement eArgumentList = parent.getParent(); if (!(eArgumentList instanceof GrArgumentList)) return false; GrArgumentList argumentList = (GrArgumentList)eArgumentList; if (argumentList.getNamedArguments().length > 0) return false; if (argumentList.getExpressionArgumentIndex((GrListOrMap)parent) != 0) return false; eMethodCall = eArgumentList.getParent(); } if (!(eMethodCall instanceof GrCall)) return false; return methodCall == null || methodCall.accepts(eMethodCall, context); } }); } public static GroovyMethodCallPattern methodCall(final ElementPattern<? extends String> names, final String className) { return new GroovyMethodCallPattern().withMethodName(names) .withMethod(psiMethod().with(new PatternCondition<PsiMethod>("psiMethodClassNameCondition") { @Override public boolean accepts(@NotNull PsiMethod psiMethod, ProcessingContext context) { PsiClass containingClass = psiMethod.getContainingClass(); if (containingClass != null) { if (InheritanceUtil.isInheritor(containingClass, className)) { return true; } } return false; } })); } public static GroovyMethodCallPattern methodCall() { return new GroovyMethodCallPattern(); } public static PsiFilePattern.Capture<GroovyFile> groovyScript() { return new PsiFilePattern.Capture<GroovyFile>(new InitialPatternCondition<GroovyFile>(GroovyFile.class) { @Override public boolean accepts(@Nullable Object o, ProcessingContext context) { return o instanceof GroovyFileBase && ((GroovyFileBase)o).isScript(); } }); } }
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/patterns/GroovyPatterns.java
/* * Copyright 2000-2009 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 org.jetbrains.plugins.groovy.lang.psi.patterns; import com.intellij.openapi.util.Condition; import com.intellij.patterns.*; import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMethod; import com.intellij.psi.impl.source.tree.LeafPsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.InheritanceUtil; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrLiteralImpl; import static org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes.mGSTRING_LITERAL; import static org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes.mSTRING_LITERAL; public class GroovyPatterns extends PsiJavaPatterns { public static GroovyElementPattern groovyElement() { return new GroovyElementPattern.Capture<GroovyPsiElement>(GroovyPsiElement.class); } public static GroovyBinaryExpressionPattern groovyBinaryExpression() { return new GroovyBinaryExpressionPattern(); } public static GroovyAssignmentExpressionPattern groovyAssignmentExpression() { return new GroovyAssignmentExpressionPattern(); } public static GroovyElementPattern.Capture<GrLiteral> groovyLiteralExpression() { return groovyLiteralExpression(null); } public static GroovyElementPattern.Capture<GrLiteral> groovyLiteralExpression(final ElementPattern value) { return new GroovyElementPattern.Capture<GrLiteral>(new InitialPatternCondition<GrLiteral>(GrLiteral.class) { public boolean accepts(@Nullable final Object o, final ProcessingContext context) { return o instanceof GrLiteral && (value == null || value.accepts(((GrLiteral)o).getValue(), context)); } }); } public static GroovyElementPattern.Capture<GroovyPsiElement> rightOfAssignment(final ElementPattern<? extends GroovyPsiElement> value, final GroovyAssignmentExpressionPattern assignment) { return new GroovyElementPattern.Capture<GroovyPsiElement>(new InitialPatternCondition<GroovyPsiElement>(GroovyPsiElement.class) { @Override public boolean accepts(@Nullable Object o, ProcessingContext context) { if (!(o instanceof GroovyPsiElement)) return false; PsiElement parent = ((GroovyPsiElement)o).getParent(); if (!(parent instanceof GrAssignmentExpression)) return false; if (((GrAssignmentExpression)parent).getRValue() != o) return false; return assignment.getCondition().accepts(parent, context) && value.getCondition().accepts(o, context); } }); } public static GroovyElementPattern.Capture<GrLiteralImpl> stringLiteral() { return new GroovyElementPattern.Capture<GrLiteralImpl>(new InitialPatternCondition<GrLiteralImpl>(GrLiteralImpl.class) { public boolean accepts(@Nullable final Object o, final ProcessingContext context) { if (!(o instanceof GrLiteralImpl)) return false; return ((GrLiteralImpl)o).isStringLiteral(); } }); } public static GroovyElementPattern.Capture<GrLiteralImpl> namedArgumentStringLiteral() { return stringLiteral().withParent(psiElement(GrNamedArgument.class)); } public static GroovyElementPattern.Capture<GrArgumentLabel> namedArgumentLabel() { return new GroovyElementPattern.Capture<GrArgumentLabel>(new InitialPatternCondition<GrArgumentLabel>(GrArgumentLabel.class) { public boolean accepts(@Nullable final Object o, final ProcessingContext context) { if (o instanceof GrArgumentLabel) { PsiElement nameElement = ((GrArgumentLabel)o).getNameElement(); if (nameElement instanceof LeafPsiElement) { IElementType elementType = ((LeafPsiElement)nameElement).getElementType(); if (elementType == GroovyElementTypes.mIDENT || CommonClassNames.JAVA_LANG_STRING.equals(TypesUtil.getPsiTypeName(elementType))) { return true; } } } return false; } }); } public static GroovyElementPattern.Capture<GrNamedArgument> methodNamedParameter(@Nullable final ElementPattern<? extends GrCall> methodCall) { return new GroovyElementPattern.Capture<GrNamedArgument>(new InitialPatternCondition<GrNamedArgument>(GrNamedArgument.class) { public boolean accepts(@Nullable final Object o, final ProcessingContext context) { if (!(o instanceof GrNamedArgument)) return false; PsiElement parent = ((GrNamedArgument)o).getParent(); PsiElement eMethodCall; if (parent instanceof GrArgumentList) { eMethodCall = parent.getParent(); } else { if (!(parent instanceof GrListOrMap)) return false; PsiElement eArgumentList = parent.getParent(); if (!(eArgumentList instanceof GrArgumentList)) return false; GrArgumentList argumentList = (GrArgumentList)eArgumentList; if (argumentList.getNamedArguments().length > 0) return false; if (argumentList.getExpressionArgumentIndex((GrListOrMap)parent) != 0) return false; eMethodCall = eArgumentList.getParent(); } if (!(eMethodCall instanceof GrCall)) return false; return methodCall == null || methodCall.accepts(eMethodCall); } }); } public static GroovyMethodCallPattern methodCall(final ElementPattern<? extends String> names, final String className) { return new GroovyMethodCallPattern().withMethodName(names) .withMethod(psiMethod().with(new PatternCondition<PsiMethod>("psiMethodClassNameCondition") { @Override public boolean accepts(@NotNull PsiMethod psiMethod, ProcessingContext context) { PsiClass containingClass = psiMethod.getContainingClass(); if (containingClass != null) { if (InheritanceUtil.isInheritor(containingClass, className)) { return true; } } return false; } })); } public static GroovyMethodCallPattern methodCall() { return new GroovyMethodCallPattern(); } public static PsiFilePattern.Capture<GroovyFile> groovyScript() { return new PsiFilePattern.Capture<GroovyFile>(new InitialPatternCondition<GroovyFile>(GroovyFile.class) { @Override public boolean accepts(@Nullable Object o, ProcessingContext context) { return o instanceof GroovyFileBase && ((GroovyFileBase)o).isScript(); } }); } }
Fix Grails Tests.
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/patterns/GroovyPatterns.java
Fix Grails Tests.
<ide><path>lugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/patterns/GroovyPatterns.java <ide> return stringLiteral().withParent(psiElement(GrNamedArgument.class)); <ide> } <ide> <del> public static GroovyElementPattern.Capture<GrArgumentLabel> namedArgumentLabel() { <add> public static GroovyElementPattern.Capture<GrArgumentLabel> namedArgumentLabel(@Nullable final ElementPattern<? extends String> namePattern) { <ide> return new GroovyElementPattern.Capture<GrArgumentLabel>(new InitialPatternCondition<GrArgumentLabel>(GrArgumentLabel.class) { <ide> public boolean accepts(@Nullable final Object o, final ProcessingContext context) { <ide> if (o instanceof GrArgumentLabel) { <ide> IElementType elementType = ((LeafPsiElement)nameElement).getElementType(); <ide> if (elementType == GroovyElementTypes.mIDENT || <ide> CommonClassNames.JAVA_LANG_STRING.equals(TypesUtil.getPsiTypeName(elementType))) { <del> return true; <add> return namePattern == null || namePattern.accepts(((GrArgumentLabel)o).getName()); <ide> } <ide> } <ide> } <ide> <ide> if (!(eMethodCall instanceof GrCall)) return false; <ide> <del> return methodCall == null || methodCall.accepts(eMethodCall); <add> return methodCall == null || methodCall.accepts(eMethodCall, context); <ide> } <ide> }); <ide> }
Java
apache-2.0
25f720cfe9516363e44e689fdf1ad19dbcd5d714
0
RSDT/Japp16,RSDT/Japp16,RSDT/Japp
package nl.rsdt.japp.application.fragments; import android.app.Fragment; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.Snackbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.clans.fab.FloatingActionButton; import com.github.clans.fab.FloatingActionMenu; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.PolygonOptions; import org.osmdroid.config.Configuration; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.util.GeoPoint; import java.util.HashMap; import nl.rsdt.japp.R; import nl.rsdt.japp.application.Japp; import nl.rsdt.japp.application.JappPreferences; import nl.rsdt.japp.jotial.availability.StoragePermissionsChecker; import nl.rsdt.japp.jotial.data.bodies.VosPostBody; import nl.rsdt.japp.jotial.maps.deelgebied.Deelgebied; import nl.rsdt.japp.jotial.maps.movement.MovementManager; import nl.rsdt.japp.jotial.maps.pinning.Pin; import nl.rsdt.japp.jotial.maps.pinning.PinningManager; import nl.rsdt.japp.jotial.maps.pinning.PinningSession; import nl.rsdt.japp.jotial.maps.sighting.SightingIcon; import nl.rsdt.japp.jotial.maps.sighting.SightingSession; import nl.rsdt.japp.jotial.maps.wrapper.JotiMap; import nl.rsdt.japp.jotial.maps.wrapper.Polygon; import nl.rsdt.japp.jotial.net.apis.VosApi; import nl.rsdt.japp.service.LocationService; import nl.rsdt.japp.service.ServiceManager; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 8-7-2016 * Description... */ public class JappMapFragment extends Fragment implements OnMapReadyCallback, SharedPreferences.OnSharedPreferenceChangeListener{ public static final String TAG = "JappMapFragment"; private static final String BUNDLE_MAP = "BUNDLE_MAP"; private static final String BUNDLE_OSM_ACTIVE = "BUNDLE_OSM_ACTIVE_B"; private static final String OSM_ZOOM = "OSM_ZOOM"; private static final String OSM_LAT = "OSM_LAT"; private static final java.lang.String OSM_LNG = "OSM_LNG"; private static final String OSM_OR = "OSM_OR"; private static final String OSM_BUNDLE = "OSM_BUNDLE"; private ServiceManager<LocationService, LocationService.LocationBinder> serviceManager = new ServiceManager<>(LocationService.class); private MapView googleMapView; private JotiMap jotiMap; public JotiMap getJotiMap() { return jotiMap; } private nl.rsdt.japp.jotial.maps.wrapper.OnMapReadyCallback callback; private PinningManager pinningManager = new PinningManager(); private MovementManager movementManager = new MovementManager(); private HashMap<String, Polygon> areas = new HashMap<>(); private boolean osmActive = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); JappPreferences.getVisiblePreferences().registerOnSharedPreferenceChangeListener(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { pinningManager.intialize(getActivity()); pinningManager.onCreate(savedInstanceState); // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_map, container, false); boolean useOSM = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).getBoolean("pref_advanced_osm",true); //// TODO: 10/08/17 magic string if (savedInstanceState != null && savedInstanceState.containsKey(BUNDLE_OSM_ACTIVE)) { if (useOSM != savedInstanceState.getBoolean(BUNDLE_OSM_ACTIVE)){ savedInstanceState = null; } } if (useOSM){ return createOSMMap(savedInstanceState, v); }else { return createGoogleMap(savedInstanceState, v); } } private View createOSMMap(Bundle savedInstanceState, View v) { StoragePermissionsChecker.check(getActivity()); osmActive = true; googleMapView = (MapView)v.findViewById(R.id.googleMap); googleMapView.setVisibility(View.GONE); org.osmdroid.views.MapView osmView = (org.osmdroid.views.MapView) v.findViewById(R.id.osmMap); Context ctx = getActivity().getApplicationContext(); Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx)); osmView.setTileSource(TileSourceFactory.MAPNIK); osmView.getController().setCenter(new GeoPoint(51.958852, 5.954517)); osmView.getController().setZoom(11); osmView.setBuiltInZoomControls(true); osmView.setMultiTouchControls(true); osmView.setFlingEnabled(true); jotiMap = JotiMap.getJotiMapInstance(osmView); if (savedInstanceState != null) { Bundle osmbundle = savedInstanceState.getBundle(OSM_BUNDLE); if (osmbundle != null) { osmView.getController().setZoom(osmbundle.getInt(OSM_ZOOM)); osmView.getController().setCenter(new GeoPoint(osmbundle.getDouble(OSM_LAT), osmbundle.getDouble(OSM_LNG))); osmView.setRotation(osmbundle.getFloat(OSM_OR)); } } movementManager.setSnackBarView(osmView); setupHuntButton(v).setEnabled(false); setupSpotButton(v).setEnabled(false); setupPinButton(v).setEnabled(false); setupFollowButton(v); return v; } private View createGoogleMap(Bundle savedInstanceState, View v){ osmActive = false; googleMapView = (MapView)v.findViewById(R.id.googleMap); org.osmdroid.views.MapView osmMapView = (org.osmdroid.views.MapView) v.findViewById(R.id.osmMap); Context ctx = getActivity().getApplicationContext(); Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx)); osmMapView.setVisibility(View.GONE); if(savedInstanceState != null && savedInstanceState.containsKey(BUNDLE_MAP)) { googleMapView.onCreate(savedInstanceState.getBundle(BUNDLE_MAP)); } else { googleMapView.onCreate(savedInstanceState); } movementManager.setSnackBarView(googleMapView); setupHuntButton(v); setupSpotButton(v); setupPinButton(v); setupFollowButton(v); return v; } @Override public void onSaveInstanceState(Bundle savedInstanceState) { pinningManager.onSaveInstanceState(savedInstanceState); savedInstanceState.putBoolean(BUNDLE_OSM_ACTIVE, osmActive); if (!osmActive) { Bundle mapBundle = new Bundle(); googleMapView.onSaveInstanceState(mapBundle); savedInstanceState.putBundle(BUNDLE_MAP, mapBundle); }else{ org.osmdroid.views.MapView osmMap = jotiMap.getOSMMap(); Bundle osmMapBundle = new Bundle(); osmMapBundle.putInt(OSM_ZOOM, osmMap.getZoomLevel()); osmMapBundle.putDouble(OSM_LAT, osmMap.getMapCenter().getLatitude()); osmMapBundle.putDouble(OSM_LNG, osmMap.getMapCenter().getLongitude()); osmMapBundle.putFloat(OSM_OR, osmMap.getMapOrientation()); savedInstanceState.putBundle(OSM_BUNDLE, osmMapBundle); } // Always call the superclass so it can save the view hierarchy state super.onSaveInstanceState(savedInstanceState); } public void getMapAsync(nl.rsdt.japp.jotial.maps.wrapper.OnMapReadyCallback callback) { if (osmActive){ onMapReady(jotiMap); }else { MapView view = (MapView) getView().findViewById(R.id.googleMap); view.getMapAsync(this); } this.callback = callback; } public void onStart() { super.onStart(); if (!osmActive) { googleMapView.onStart(); } } public void onStop() { super.onStop(); if (!osmActive) { googleMapView.onStop(); } } @Override public void onResume() { super.onResume(); if (!osmActive) { googleMapView.onResume(); }else { Configuration.getInstance().load(getActivity(), PreferenceManager.getDefaultSharedPreferences(getActivity())); } serviceManager.add(movementManager); movementManager.onResume(); if(!serviceManager.isBound()) { serviceManager.bind(this.getActivity()); } } @Override public void onPause() { super.onPause(); if (!osmActive) { googleMapView.onPause(); } movementManager.onPause(); } @Override public void onDestroy() { super.onDestroy(); if (!osmActive) { googleMapView.onDestroy(); } if(movementManager != null) { movementManager.onDestroy(); serviceManager.remove(movementManager); movementManager = null; } JappPreferences.getVisiblePreferences().registerOnSharedPreferenceChangeListener(this); serviceManager.unbind(getActivity()); } @Override public void onLowMemory() { super.onLowMemory(); if (!osmActive) { googleMapView.onLowMemory(); } } public void onMapReady(JotiMap jotiMap){ jotiMap.clear(); movementManager.onMapReady(jotiMap); Deelgebied[] all = Deelgebied.all(); Deelgebied current; for(int i = 0; i < all.length; i++) { current = all[i]; PolygonOptions options = new PolygonOptions().addAll(current.getCoordinates()); if(JappPreferences.getAreasColorEnabled()) { int alphaPercent = JappPreferences.getAreasColorAlpha(); float alpha = ((float)(100 - alphaPercent))/100 * 255; options.fillColor(current.alphaled(Math.round(alpha))); } else { options.fillColor(Color.TRANSPARENT); } options.strokeColor(current.getColor()); if(JappPreferences.getAreasEdgesEnabled()) { options.strokeWidth(JappPreferences.getAreasEdgesWidth()); } else { options.strokeWidth(0); } areas.put(current.getName(), jotiMap.addPolygon(options)); } pinningManager.onMapReady(jotiMap); if(callback != null) { callback.onMapReady(jotiMap); } } @Override public void onMapReady(GoogleMap googleMap) { this.jotiMap = JotiMap.getJotiMapInstance(googleMap); onMapReady(jotiMap); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Polygon polygon; switch (key){ case JappPreferences.AREAS_EDGES: boolean edges = JappPreferences.getAreasEdgesEnabled(); for(HashMap.Entry<String, Polygon> pair : areas.entrySet()){ polygon = pair.getValue(); if(edges) { polygon.setStrokeWidth(JappPreferences.getAreasEdgesWidth()); } else { polygon.setStrokeWidth(0); } } break; case JappPreferences.AREAS_EDGES_WIDTH: boolean edgesEnabled = JappPreferences.getAreasEdgesEnabled(); for(HashMap.Entry<String, Polygon> pair : areas.entrySet()){ polygon = pair.getValue(); if(edgesEnabled) { polygon.setStrokeWidth(JappPreferences.getAreasEdgesWidth()); } } break; case JappPreferences.AREAS_COLOR: boolean color = JappPreferences.getAreasColorEnabled(); for(HashMap.Entry<String, Polygon> pair : areas.entrySet()){ polygon = pair.getValue(); if(color) { int alphaPercent = JappPreferences.getAreasColorAlpha(); float alpha = ((float)(100 - alphaPercent))/100 * 255; polygon.setFillColor(Deelgebied.parse(pair.getKey()).alphaled(Math.round(alpha))); } else { polygon.setFillColor(Color.TRANSPARENT); } } break; case JappPreferences.AREAS_COLOR_ALPHA: boolean areasColorEnabled = JappPreferences.getAreasColorEnabled(); for(HashMap.Entry<String, Polygon> pair : areas.entrySet()){ polygon = pair.getValue(); if(areasColorEnabled) { int alphaPercent = JappPreferences.getAreasColorAlpha(); float alpha = ((float)(100 - alphaPercent))/100 * 255; polygon.setFillColor(Deelgebied.parse(pair.getKey()).alphaled(Math.round(alpha))); } } break; } } public FloatingActionButton setupSpotButton(View v) { FloatingActionButton spotButton = (FloatingActionButton)v.findViewById(R.id.fab_spot); spotButton.setOnClickListener(new View.OnClickListener() { SightingSession session; @Override public void onClick(View view) { /*--- Hide the menu ---*/ View v = getView(); FloatingActionMenu menu = (FloatingActionMenu)v.findViewById(R.id.fab_menu); menu.hideMenu(true); /*--- Build a SightingSession and start it ---*/ session = new SightingSession.Builder() .setType(SightingSession.SIGHT_SPOT) .setGoogleMap(jotiMap) .setTargetView(JappMapFragment.this.getActivity().findViewById(R.id.container)) .setDialogContext(JappMapFragment.this.getActivity()) .setOnSightingCompletedCallback(new SightingSession.OnSightingCompletedCallback() { @Override public void onSightingCompleted(LatLng chosen, Deelgebied deelgebied, String optionalInfo) { /*--- Show the menu ---*/ FloatingActionMenu menu = (FloatingActionMenu)getView().findViewById(R.id.fab_menu); menu.showMenu(true); if(chosen != null) { /*--- Construct a JSON string with the data ---*/ VosPostBody builder = VosPostBody.getDefault(); builder.setIcon(SightingIcon.SPOT); builder.setLatLng(chosen); builder.setTeam(deelgebied.getName().substring(0, 1)); builder.setInfo(optionalInfo); VosApi api = Japp.getApi(VosApi.class); api.post(builder).enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container); switch (response.code()) { case 200: Snackbar.make(snackbarView, "Succesvol verzonden", Snackbar.LENGTH_LONG).show(); break; case 404: Snackbar.make(snackbarView, "Verkeerde gegevens", Snackbar.LENGTH_LONG).show(); break; default: Snackbar.make(snackbarView, "Probleem bij verzenden: " + response.code(), Snackbar.LENGTH_LONG).show(); break; } } @Override public void onFailure(Call<Void> call, Throwable t) { View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container); Snackbar.make(snackbarView, "Probleem bij verzenden: " + t.toString() , Snackbar.LENGTH_LONG).show(); } }); /** * TODO: send details? * Log the spot in firebase. * */ Japp.getAnalytics().logEvent("EVENT_SPOT", new Bundle()); } session = null; } }) .create(); session.start(); } }); return spotButton; } public FloatingActionButton setupFollowButton(View v) { FloatingActionButton followButton = (FloatingActionButton) v.findViewById(R.id.fab_follow); followButton.setOnClickListener(new View.OnClickListener() { MovementManager.FollowSession session; @Override public void onClick(View view) { View v = getView(); FloatingActionButton followButton = (FloatingActionButton) v.findViewById(R.id.fab_follow); /*--- Hide the menu ---*/ FloatingActionMenu menu = (FloatingActionMenu) v.findViewById(R.id.fab_menu); /** * TODO: use color to identify follow state? * */ if (session != null) { // followButton.setColorNormal(Color.parseColor("#DA4336")); followButton.setLabelText("Volg mij"); session.end(); session = null; } else { menu.close(true); //followButton.setColorNormal(Color.parseColor("#5cd65c")); followButton.setLabelText("Stop volgen"); session = movementManager.newSession(jotiMap.getCameraPosition(), JappPreferences.getFollowZoom(), JappPreferences.getFollowAngleOfAttack()); } } }); return followButton; } private FloatingActionButton setupPinButton(View v) { FloatingActionButton pinButton = (FloatingActionButton)v.findViewById(R.id.fab_mark); pinButton.setOnClickListener(new View.OnClickListener() { PinningSession session; @Override public void onClick(View view) { View v = getView(); FloatingActionMenu menu = (FloatingActionMenu) v.findViewById(R.id.fab_menu); if(session != null) { /*--- Show the menu ---*/ menu.showMenu(true); session.end(); session = null; } else { /*--- Hide the menu ---*/ menu.hideMenu(true); session = new PinningSession.Builder() .setGoogleMap(jotiMap) .setCallback(new PinningSession.OnPinningCompletedCallback() { @Override public void onPinningCompleted(Pin pin) { if(pin != null) { pinningManager.add(pin); } FloatingActionMenu menu = (FloatingActionMenu)getView().findViewById(R.id.fab_menu); menu.showMenu(true); session.end(); session = null; } }) .setTargetView(JappMapFragment.this.getActivity().findViewById(R.id.container)) .setDialogContext(JappMapFragment.this.getActivity()) .create(); session.start(); } } }); return pinButton; } private FloatingActionButton setupHuntButton(View v){ FloatingActionButton huntButton = (FloatingActionButton)v.findViewById(R.id.fab_hunt); huntButton.setOnClickListener(new View.OnClickListener() { SightingSession session; @Override public void onClick(View view) { /*--- Hide the menu ---*/ View v = getView(); FloatingActionMenu menu = (FloatingActionMenu)v.findViewById(R.id.fab_menu); menu.hideMenu(true); /*--- Build a SightingSession and start it ---*/ session = new SightingSession.Builder() .setType(SightingSession.SIGHT_HUNT) .setGoogleMap(jotiMap) .setTargetView(JappMapFragment.this.getActivity().findViewById(R.id.container)) .setDialogContext(JappMapFragment.this.getActivity()) .setOnSightingCompletedCallback(new SightingSession.OnSightingCompletedCallback() { @Override public void onSightingCompleted(LatLng chosen, Deelgebied deelgebied, String optionalInfo) { /*--- Show the menu ---*/ FloatingActionMenu menu = (FloatingActionMenu)getView().findViewById(R.id.fab_menu); menu.showMenu(true); if(chosen != null) { /*--- Construct a JSON string with the data ---*/ VosPostBody builder = VosPostBody.getDefault(); builder.setIcon(SightingIcon.HUNT); builder.setLatLng(chosen); builder.setTeam(deelgebied.getName().substring(0, 1)); builder.setInfo(optionalInfo); VosApi api = Japp.getApi(VosApi.class); api.post(builder).enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container); switch (response.code()) { case 200: Snackbar.make(snackbarView, "Succesvol verzonden", Snackbar.LENGTH_LONG).show(); //// TODO: 08/08/17 magic string break; case 404: Snackbar.make(snackbarView, "Verkeerde gegevens", Snackbar.LENGTH_LONG).show(); //// TODO: 08/08/17 magic string break; default: Snackbar.make(snackbarView, "Probleem bij verzenden: " + response.code(), Snackbar.LENGTH_LONG).show(); //// TODO: 08/08/17 magic string break; } } @Override public void onFailure(Call<Void> call, Throwable t) { View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container); Snackbar.make(snackbarView, "Probleem bij verzenden: " + t.toString() , Snackbar.LENGTH_LONG).show();//// TODO: 08/08/17 magic string } }); /** * TODO: send details? * Log the hunt in firebase. * */ Japp.getAnalytics().logEvent("EVENT_HUNT", new Bundle()); //// TODO: 08/08/17 magic string } } }) .create(); session.start(); } }); return huntButton; } }
app/src/main/java/nl/rsdt/japp/application/fragments/JappMapFragment.java
package nl.rsdt.japp.application.fragments; import android.app.Fragment; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.Snackbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.clans.fab.FloatingActionButton; import com.github.clans.fab.FloatingActionMenu; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.PolygonOptions; import org.osmdroid.config.Configuration; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.util.GeoPoint; import java.util.HashMap; import nl.rsdt.japp.R; import nl.rsdt.japp.application.Japp; import nl.rsdt.japp.application.JappPreferences; import nl.rsdt.japp.jotial.availability.StoragePermissionsChecker; import nl.rsdt.japp.jotial.data.bodies.VosPostBody; import nl.rsdt.japp.jotial.maps.deelgebied.Deelgebied; import nl.rsdt.japp.jotial.maps.movement.MovementManager; import nl.rsdt.japp.jotial.maps.pinning.Pin; import nl.rsdt.japp.jotial.maps.pinning.PinningManager; import nl.rsdt.japp.jotial.maps.pinning.PinningSession; import nl.rsdt.japp.jotial.maps.sighting.SightingIcon; import nl.rsdt.japp.jotial.maps.sighting.SightingSession; import nl.rsdt.japp.jotial.maps.wrapper.JotiMap; import nl.rsdt.japp.jotial.maps.wrapper.Polygon; import nl.rsdt.japp.jotial.net.apis.VosApi; import nl.rsdt.japp.service.LocationService; import nl.rsdt.japp.service.ServiceManager; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 8-7-2016 * Description... */ public class JappMapFragment extends Fragment implements OnMapReadyCallback, SharedPreferences.OnSharedPreferenceChangeListener{ public static final String TAG = "JappMapFragment"; private static final String BUNDLE_MAP = "BUNDLE_MAP"; private static final String BUNDLE_OSM_ACTIVE = "BUNDLE_OSM_ACTIVE_B"; private static final String OSM_ZOOM = "OSM_ZOOM"; private static final String OSM_LAT = "OSM_LAT"; private static final java.lang.String OSM_LNG = "OSM_LNG"; private static final String OSM_OR = "OSM_OR"; private static final String OSM_BUNDLE = "OSM_BUNDLE"; private ServiceManager<LocationService, LocationService.LocationBinder> serviceManager = new ServiceManager<>(LocationService.class); private MapView googleMapView; private JotiMap jotiMap; public JotiMap getJotiMap() { return jotiMap; } private nl.rsdt.japp.jotial.maps.wrapper.OnMapReadyCallback callback; private PinningManager pinningManager = new PinningManager(); private MovementManager movementManager = new MovementManager(); private HashMap<String, Polygon> areas = new HashMap<>(); private boolean osmActive = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); JappPreferences.getVisiblePreferences().registerOnSharedPreferenceChangeListener(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { pinningManager.intialize(getActivity()); pinningManager.onCreate(savedInstanceState); // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_map, container, false); boolean useOSM = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).getBoolean("pref_advanced_osm",false); //// TODO: 10/08/17 magic string if (savedInstanceState != null && savedInstanceState.containsKey(BUNDLE_OSM_ACTIVE)) { if (useOSM != savedInstanceState.getBoolean(BUNDLE_OSM_ACTIVE)){ savedInstanceState = null; } } if (useOSM){ return createOSMMap(savedInstanceState, v); }else { return createGoogleMap(savedInstanceState, v); } } private View createOSMMap(Bundle savedInstanceState, View v) { StoragePermissionsChecker.check(getActivity()); osmActive = true; googleMapView = (MapView)v.findViewById(R.id.googleMap); googleMapView.setVisibility(View.GONE); org.osmdroid.views.MapView osmView = (org.osmdroid.views.MapView) v.findViewById(R.id.osmMap); Context ctx = getActivity().getApplicationContext(); Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx)); osmView.setTileSource(TileSourceFactory.MAPNIK); osmView.getController().setCenter(new GeoPoint(51.958852, 5.954517)); osmView.getController().setZoom(11); osmView.setBuiltInZoomControls(true); osmView.setMultiTouchControls(true); osmView.setFlingEnabled(true); jotiMap = JotiMap.getJotiMapInstance(osmView); if (savedInstanceState != null) { Bundle osmbundle = savedInstanceState.getBundle(OSM_BUNDLE); if (osmbundle != null) { osmView.getController().setZoom(osmbundle.getInt(OSM_ZOOM)); osmView.getController().setCenter(new GeoPoint(osmbundle.getDouble(OSM_LAT), osmbundle.getDouble(OSM_LNG))); osmView.setRotation(osmbundle.getFloat(OSM_OR)); } } movementManager.setSnackBarView(osmView); setupHuntButton(v).setEnabled(false); setupSpotButton(v).setEnabled(false); setupPinButton(v).setEnabled(false); setupFollowButton(v); return v; } private View createGoogleMap(Bundle savedInstanceState, View v){ osmActive = false; googleMapView = (MapView)v.findViewById(R.id.googleMap); org.osmdroid.views.MapView osmMapView = (org.osmdroid.views.MapView) v.findViewById(R.id.osmMap); Context ctx = getActivity().getApplicationContext(); Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx)); osmMapView.setVisibility(View.GONE); if(savedInstanceState != null && savedInstanceState.containsKey(BUNDLE_MAP)) { googleMapView.onCreate(savedInstanceState.getBundle(BUNDLE_MAP)); } else { googleMapView.onCreate(savedInstanceState); } movementManager.setSnackBarView(googleMapView); setupHuntButton(v); setupSpotButton(v); setupPinButton(v); setupFollowButton(v); return v; } @Override public void onSaveInstanceState(Bundle savedInstanceState) { pinningManager.onSaveInstanceState(savedInstanceState); savedInstanceState.putBoolean(BUNDLE_OSM_ACTIVE, osmActive); if (!osmActive) { Bundle mapBundle = new Bundle(); googleMapView.onSaveInstanceState(mapBundle); savedInstanceState.putBundle(BUNDLE_MAP, mapBundle); }else{ org.osmdroid.views.MapView osmMap = jotiMap.getOSMMap(); Bundle osmMapBundle = new Bundle(); osmMapBundle.putInt(OSM_ZOOM, osmMap.getZoomLevel()); osmMapBundle.putDouble(OSM_LAT, osmMap.getMapCenter().getLatitude()); osmMapBundle.putDouble(OSM_LNG, osmMap.getMapCenter().getLongitude()); osmMapBundle.putFloat(OSM_OR, osmMap.getMapOrientation()); savedInstanceState.putBundle(OSM_BUNDLE, osmMapBundle); } // Always call the superclass so it can save the view hierarchy state super.onSaveInstanceState(savedInstanceState); } public void getMapAsync(nl.rsdt.japp.jotial.maps.wrapper.OnMapReadyCallback callback) { if (osmActive){ onMapReady(jotiMap); }else { MapView view = (MapView) getView().findViewById(R.id.googleMap); view.getMapAsync(this); } this.callback = callback; } public void onStart() { super.onStart(); if (!osmActive) { googleMapView.onStart(); } } public void onStop() { super.onStop(); if (!osmActive) { googleMapView.onStop(); } } @Override public void onResume() { super.onResume(); if (!osmActive) { googleMapView.onResume(); }else { Configuration.getInstance().load(getActivity(), PreferenceManager.getDefaultSharedPreferences(getActivity())); } serviceManager.add(movementManager); movementManager.onResume(); if(!serviceManager.isBound()) { serviceManager.bind(this.getActivity()); } } @Override public void onPause() { super.onPause(); if (!osmActive) { googleMapView.onPause(); } movementManager.onPause(); } @Override public void onDestroy() { super.onDestroy(); if (!osmActive) { googleMapView.onDestroy(); } if(movementManager != null) { movementManager.onDestroy(); serviceManager.remove(movementManager); movementManager = null; } JappPreferences.getVisiblePreferences().registerOnSharedPreferenceChangeListener(this); serviceManager.unbind(getActivity()); } @Override public void onLowMemory() { super.onLowMemory(); if (!osmActive) { googleMapView.onLowMemory(); } } public void onMapReady(JotiMap jotiMap){ jotiMap.clear(); movementManager.onMapReady(jotiMap); Deelgebied[] all = Deelgebied.all(); Deelgebied current; for(int i = 0; i < all.length; i++) { current = all[i]; PolygonOptions options = new PolygonOptions().addAll(current.getCoordinates()); if(JappPreferences.getAreasColorEnabled()) { int alphaPercent = JappPreferences.getAreasColorAlpha(); float alpha = ((float)(100 - alphaPercent))/100 * 255; options.fillColor(current.alphaled(Math.round(alpha))); } else { options.fillColor(Color.TRANSPARENT); } options.strokeColor(current.getColor()); if(JappPreferences.getAreasEdgesEnabled()) { options.strokeWidth(JappPreferences.getAreasEdgesWidth()); } else { options.strokeWidth(0); } areas.put(current.getName(), jotiMap.addPolygon(options)); } pinningManager.onMapReady(jotiMap); if(callback != null) { callback.onMapReady(jotiMap); } } @Override public void onMapReady(GoogleMap googleMap) { this.jotiMap = JotiMap.getJotiMapInstance(googleMap); onMapReady(jotiMap); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Polygon polygon; switch (key){ case JappPreferences.AREAS_EDGES: boolean edges = JappPreferences.getAreasEdgesEnabled(); for(HashMap.Entry<String, Polygon> pair : areas.entrySet()){ polygon = pair.getValue(); if(edges) { polygon.setStrokeWidth(JappPreferences.getAreasEdgesWidth()); } else { polygon.setStrokeWidth(0); } } break; case JappPreferences.AREAS_EDGES_WIDTH: boolean edgesEnabled = JappPreferences.getAreasEdgesEnabled(); for(HashMap.Entry<String, Polygon> pair : areas.entrySet()){ polygon = pair.getValue(); if(edgesEnabled) { polygon.setStrokeWidth(JappPreferences.getAreasEdgesWidth()); } } break; case JappPreferences.AREAS_COLOR: boolean color = JappPreferences.getAreasColorEnabled(); for(HashMap.Entry<String, Polygon> pair : areas.entrySet()){ polygon = pair.getValue(); if(color) { int alphaPercent = JappPreferences.getAreasColorAlpha(); float alpha = ((float)(100 - alphaPercent))/100 * 255; polygon.setFillColor(Deelgebied.parse(pair.getKey()).alphaled(Math.round(alpha))); } else { polygon.setFillColor(Color.TRANSPARENT); } } break; case JappPreferences.AREAS_COLOR_ALPHA: boolean areasColorEnabled = JappPreferences.getAreasColorEnabled(); for(HashMap.Entry<String, Polygon> pair : areas.entrySet()){ polygon = pair.getValue(); if(areasColorEnabled) { int alphaPercent = JappPreferences.getAreasColorAlpha(); float alpha = ((float)(100 - alphaPercent))/100 * 255; polygon.setFillColor(Deelgebied.parse(pair.getKey()).alphaled(Math.round(alpha))); } } break; } } public FloatingActionButton setupSpotButton(View v) { FloatingActionButton spotButton = (FloatingActionButton)v.findViewById(R.id.fab_spot); spotButton.setOnClickListener(new View.OnClickListener() { SightingSession session; @Override public void onClick(View view) { /*--- Hide the menu ---*/ View v = getView(); FloatingActionMenu menu = (FloatingActionMenu)v.findViewById(R.id.fab_menu); menu.hideMenu(true); /*--- Build a SightingSession and start it ---*/ session = new SightingSession.Builder() .setType(SightingSession.SIGHT_SPOT) .setGoogleMap(jotiMap) .setTargetView(JappMapFragment.this.getActivity().findViewById(R.id.container)) .setDialogContext(JappMapFragment.this.getActivity()) .setOnSightingCompletedCallback(new SightingSession.OnSightingCompletedCallback() { @Override public void onSightingCompleted(LatLng chosen, Deelgebied deelgebied, String optionalInfo) { /*--- Show the menu ---*/ FloatingActionMenu menu = (FloatingActionMenu)getView().findViewById(R.id.fab_menu); menu.showMenu(true); if(chosen != null) { /*--- Construct a JSON string with the data ---*/ VosPostBody builder = VosPostBody.getDefault(); builder.setIcon(SightingIcon.SPOT); builder.setLatLng(chosen); builder.setTeam(deelgebied.getName().substring(0, 1)); builder.setInfo(optionalInfo); VosApi api = Japp.getApi(VosApi.class); api.post(builder).enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container); switch (response.code()) { case 200: Snackbar.make(snackbarView, "Succesvol verzonden", Snackbar.LENGTH_LONG).show(); break; case 404: Snackbar.make(snackbarView, "Verkeerde gegevens", Snackbar.LENGTH_LONG).show(); break; default: Snackbar.make(snackbarView, "Probleem bij verzenden: " + response.code(), Snackbar.LENGTH_LONG).show(); break; } } @Override public void onFailure(Call<Void> call, Throwable t) { View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container); Snackbar.make(snackbarView, "Probleem bij verzenden: " + t.toString() , Snackbar.LENGTH_LONG).show(); } }); /** * TODO: send details? * Log the spot in firebase. * */ Japp.getAnalytics().logEvent("EVENT_SPOT", new Bundle()); } session = null; } }) .create(); session.start(); } }); return spotButton; } public FloatingActionButton setupFollowButton(View v) { FloatingActionButton followButton = (FloatingActionButton) v.findViewById(R.id.fab_follow); followButton.setOnClickListener(new View.OnClickListener() { MovementManager.FollowSession session; @Override public void onClick(View view) { View v = getView(); FloatingActionButton followButton = (FloatingActionButton) v.findViewById(R.id.fab_follow); /*--- Hide the menu ---*/ FloatingActionMenu menu = (FloatingActionMenu) v.findViewById(R.id.fab_menu); /** * TODO: use color to identify follow state? * */ if (session != null) { // followButton.setColorNormal(Color.parseColor("#DA4336")); followButton.setLabelText("Volg mij"); session.end(); session = null; } else { menu.close(true); //followButton.setColorNormal(Color.parseColor("#5cd65c")); followButton.setLabelText("Stop volgen"); session = movementManager.newSession(jotiMap.getCameraPosition(), JappPreferences.getFollowZoom(), JappPreferences.getFollowAngleOfAttack()); } } }); return followButton; } private FloatingActionButton setupPinButton(View v) { FloatingActionButton pinButton = (FloatingActionButton)v.findViewById(R.id.fab_mark); pinButton.setOnClickListener(new View.OnClickListener() { PinningSession session; @Override public void onClick(View view) { View v = getView(); FloatingActionMenu menu = (FloatingActionMenu) v.findViewById(R.id.fab_menu); if(session != null) { /*--- Show the menu ---*/ menu.showMenu(true); session.end(); session = null; } else { /*--- Hide the menu ---*/ menu.hideMenu(true); session = new PinningSession.Builder() .setGoogleMap(jotiMap) .setCallback(new PinningSession.OnPinningCompletedCallback() { @Override public void onPinningCompleted(Pin pin) { if(pin != null) { pinningManager.add(pin); } FloatingActionMenu menu = (FloatingActionMenu)getView().findViewById(R.id.fab_menu); menu.showMenu(true); session.end(); session = null; } }) .setTargetView(JappMapFragment.this.getActivity().findViewById(R.id.container)) .setDialogContext(JappMapFragment.this.getActivity()) .create(); session.start(); } } }); return pinButton; } private FloatingActionButton setupHuntButton(View v){ FloatingActionButton huntButton = (FloatingActionButton)v.findViewById(R.id.fab_hunt); huntButton.setOnClickListener(new View.OnClickListener() { SightingSession session; @Override public void onClick(View view) { /*--- Hide the menu ---*/ View v = getView(); FloatingActionMenu menu = (FloatingActionMenu)v.findViewById(R.id.fab_menu); menu.hideMenu(true); /*--- Build a SightingSession and start it ---*/ session = new SightingSession.Builder() .setType(SightingSession.SIGHT_HUNT) .setGoogleMap(jotiMap) .setTargetView(JappMapFragment.this.getActivity().findViewById(R.id.container)) .setDialogContext(JappMapFragment.this.getActivity()) .setOnSightingCompletedCallback(new SightingSession.OnSightingCompletedCallback() { @Override public void onSightingCompleted(LatLng chosen, Deelgebied deelgebied, String optionalInfo) { /*--- Show the menu ---*/ FloatingActionMenu menu = (FloatingActionMenu)getView().findViewById(R.id.fab_menu); menu.showMenu(true); if(chosen != null) { /*--- Construct a JSON string with the data ---*/ VosPostBody builder = VosPostBody.getDefault(); builder.setIcon(SightingIcon.HUNT); builder.setLatLng(chosen); builder.setTeam(deelgebied.getName().substring(0, 1)); builder.setInfo(optionalInfo); VosApi api = Japp.getApi(VosApi.class); api.post(builder).enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container); switch (response.code()) { case 200: Snackbar.make(snackbarView, "Succesvol verzonden", Snackbar.LENGTH_LONG).show(); //// TODO: 08/08/17 magic string break; case 404: Snackbar.make(snackbarView, "Verkeerde gegevens", Snackbar.LENGTH_LONG).show(); //// TODO: 08/08/17 magic string break; default: Snackbar.make(snackbarView, "Probleem bij verzenden: " + response.code(), Snackbar.LENGTH_LONG).show(); //// TODO: 08/08/17 magic string break; } } @Override public void onFailure(Call<Void> call, Throwable t) { View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container); Snackbar.make(snackbarView, "Probleem bij verzenden: " + t.toString() , Snackbar.LENGTH_LONG).show();//// TODO: 08/08/17 magic string } }); /** * TODO: send details? * Log the hunt in firebase. * */ Japp.getAnalytics().logEvent("EVENT_HUNT", new Bundle()); //// TODO: 08/08/17 magic string } } }) .create(); session.start(); } }); return huntButton; } }
nu wordt ook de eerste keer naar osm opgestart
app/src/main/java/nl/rsdt/japp/application/fragments/JappMapFragment.java
nu wordt ook de eerste keer naar osm opgestart
<ide><path>pp/src/main/java/nl/rsdt/japp/application/fragments/JappMapFragment.java <ide> // Inflate the layout for this fragment <ide> View v = inflater.inflate(R.layout.fragment_map, container, false); <ide> <del> boolean useOSM = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).getBoolean("pref_advanced_osm",false); //// TODO: 10/08/17 magic string <add> boolean useOSM = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).getBoolean("pref_advanced_osm",true); //// TODO: 10/08/17 magic string <ide> if (savedInstanceState != null && savedInstanceState.containsKey(BUNDLE_OSM_ACTIVE)) { <ide> if (useOSM != savedInstanceState.getBoolean(BUNDLE_OSM_ACTIVE)){ <ide> savedInstanceState = null;
Java
lgpl-2.1
a4a18e9d1ec5a8efcdfc5acee4350dca28974110
0
jtalks-org/jtalks-common,NCNecros/jtalks-common
/** * Copyright (C) 2011 JTalks.org Team * This library 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 library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jtalks.common.model.entity; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotBlank; import org.joda.time.DateTime; import org.jtalks.common.validation.annotations.Email; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.GrantedAuthorityImpl; import org.springframework.security.core.userdetails.UserDetails; import ru.javatalks.utils.datetime.DateTimeUtilsFactory; import javax.validation.constraints.NotNull; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; /** * Stores information about the forum user. * Used as {@code UserDetails} in spring security for user authentication, authorization. * * @author Pavel Vervenko * @author Kirill Afonin * @author Alexandre Teterin * @author Masich Ivan * @author Ancient_Mariner */ public class User extends Entity implements UserDetails { private static final String USER_EMAIL_ILLEGAL_FORMAT = "{user.email.email_format_constraint_violation}"; private static final String USER_PASSWORD_ILLEGAL_LENGTH = "{user.password.length_constraint_violation}"; private static final String USER_USERNAME_ILLEGAL_LENGTH = "{user.username.length_constraint_violation}"; private static final String USER_CANT_BE_NULL = "{user.username.null_constraint_violation}"; public static final int USER_USERNAME_MIN_LENGTH = 1; public static final int USER_USERNAME_MAX_LENGTH = 25; public static final int USER_PASSWORD_MIN_LENGTH = 1; public static final int USER_PASSWORD_MAX_LENGTH = 25; private String lastName; private String firstName; @NotNull(message = USER_CANT_BE_NULL) @Length(min = USER_USERNAME_MIN_LENGTH, max = USER_USERNAME_MAX_LENGTH, message = USER_USERNAME_ILLEGAL_LENGTH) private String username; @Email(message = USER_EMAIL_ILLEGAL_FORMAT) private String email; @NotBlank @Length(min = USER_PASSWORD_MIN_LENGTH, max = USER_PASSWORD_MAX_LENGTH, message = USER_PASSWORD_ILLEGAL_LENGTH) private String password; private DateTime lastLogin; private String role = "ROLE_USER"; private String encodedUsername; private byte[] avatar = new byte[0]; private String banReason; private String salt; public static final int USERNAME_MIN_LENGTH = 3; /** * Maximum length of the username. */ public static final int USERNAME_MAX_LENGTH = 20; /** * Minimum length of the password. */ public static final int PASSWORD_MIN_LENGTH = 4; /** * Maximum length of the password. */ public static final int PASSWORD_MAX_LENGTH = 20; /** * Maximum avatar width in pixels. */ public static final int AVATAR_MAX_WIDTH = 100; /** * Maximum avatar height in pixels. */ public static final int AVATAR_MAX_HEIGHT = 100; /** * Maximum avatar size in kilobytes. */ public static final int AVATAR_MAX_SIZE = 65; /** * Only for hibernate usage. */ protected User() { } /** * Create instance with requiered fields. * * @param username username * @param email email * @param password password * @deprecated */ public User(String username, String email, String password) { this(); this.setUsername(username); this.email = email; this.password = password; this.salt = ""; } /** * Create instance with requiered fields. * * @param username username * @param email email * @param password password * @param salt salt */ public User(String username, String email, String password, String salt) { this(username, email, password); this.setSalt(salt); } /** * Get the user's Last Name. * * @return the lastName */ public String getLastName() { return lastName; } /** * @param lastName the lastName to set */ public void setLastName(String lastName) { this.lastName = lastName; } /** * @return the firstName */ public String getFirstName() { return firstName; } /** * @param firstName the firstName to set */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * @return the email */ public String getEmail() { return email; } /** * @param email the email to set */ public void setEmail(String email) { this.email = email; } /** * {@inheritDoc} */ @Override public String getUsername() { return username; } /** * Set the username and encoded username (based on username). * * @param username the username to set */ public final void setUsername(String username) { this.username = username; try { setEncodedUsername(URLEncoder.encode(username, "UTF-8").replace("+", "%20")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Could not encode username", e); } } /** * @return user role in security system */ public String getRole() { return role; } /** * @param role role */ public void setRole(String role) { this.role = role; } /** * @return user avatar */ public byte[] getAvatar() { return avatar.clone(); } /** * @param avatar user avatar */ public void setAvatar(byte[] avatar) { this.avatar = (avatar != null) ? avatar.clone() : new byte[0]; } /** * @return collection of user roles */ @Override public Collection<GrantedAuthority> getAuthorities() { Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new GrantedAuthorityImpl(role)); return authorities; } /** * @return password */ @Override public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } // methods from UserDetails inteface, indicating that // user can or can't authenticate. // we don't need this functional now and users always enabled /** * {@inheritDoc} */ @Override public boolean isAccountNonExpired() { return true; } /** * {@inheritDoc} */ @Override public boolean isAccountNonLocked() { return true; } /** * {@inheritDoc} */ @Override public boolean isCredentialsNonExpired() { return true; } /** * {@inheritDoc} */ @Override public boolean isEnabled() { return true; } /** * @return last login time and date */ public DateTime getLastLogin() { return lastLogin; } /** * Set last login time and date. * * @param lastLogin last login time */ protected void setLastLogin(DateTime lastLogin) { this.lastLogin = lastLogin; } private static final long serialVersionUID = 19981017L; /** * Updates last login time to current time. */ public void updateLastLoginTime() { this.lastLogin = DateTimeUtilsFactory.getDateTimeUtils().getNow(); } /** * Sets the encoded version of the username, where all the symbols that might mean something special (like symbols * {@code \;:",.}, etc are replaced with the encoding sequence of symbols. This is required for instance while * constructing a URL that contains a username (let's say a link to the user profile). * * @return encoded version of username that doesn't contain special symbols */ public String getEncodedUsername() { return encodedUsername; } /** * Sets the encoded version of the username, where all the symbols that might mean something special (like symbols * {@code \;:",.}, etc are replaced with the encoding sequence of symbols. This is required for instance while * constructing a URL that contains a username (let's say a link to the user profile). * * @param encodedUsername encoded version of username that doesn't contain special symbols */ protected final void setEncodedUsername(String encodedUsername) { this.encodedUsername = encodedUsername; } /** * This method returns the string ban reason description * * @return ban reason */ public String getBanReason() { return banReason; } /** * This method sets user ban reason description * * @param banReason User ban reason description */ public void setBanReason(String banReason) { this.banReason = banReason; } /** * This method returns the salt for encode password * * @return salt string */ public String getSalt() { return salt; } /** * This method sets salt for encode password * @param salt salt salstring */ public void setSalt(String salt) { this.salt = salt; } }
jtalks-common-model/src/main/java/org/jtalks/common/model/entity/User.java
/** * Copyright (C) 2011 JTalks.org Team * This library 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 library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jtalks.common.model.entity; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotBlank; import org.joda.time.DateTime; import org.jtalks.common.validation.annotations.Email; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.GrantedAuthorityImpl; import org.springframework.security.core.userdetails.UserDetails; import ru.javatalks.utils.datetime.DateTimeUtilsFactory; import javax.validation.constraints.NotNull; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; /** * Stores information about the forum user. * Used as {@code UserDetails} in spring security for user authentication, authorization. * * @author Pavel Vervenko * @author Kirill Afonin * @author Alexandre Teterin * @author Masich Ivan * @author Ancient_Mariner */ public class User extends Entity implements UserDetails { private static final String USER_EMAIL_ILLEGAL_FORMAT = "{user.email.email_format_constraint_violation}"; private static final String USER_PASSWORD_ILLEGAL_LENGTH = "{user.password.length_constraint_violation}"; private static final String USER_USERNAME_ILLEGAL_LENGTH = "{user.username.length_constraint_violation}"; private static final String USER_CANT_BE_NULL = "{user.username.null_constraint_violation}"; public static final int USER_USERNAME_MIN_LENGTH = 1; public static final int USER_USERNAME_MAX_LENGTH = 100; public static final int USER_PASSWORD_MIN_LENGTH = 1; public static final int USER_PASSWORD_MAX_LENGTH = 100; private String lastName; private String firstName; @NotNull(message = USER_CANT_BE_NULL) @Length(min = USER_USERNAME_MIN_LENGTH, max = USER_USERNAME_MAX_LENGTH, message = USER_USERNAME_ILLEGAL_LENGTH) private String username; @Email(message = USER_EMAIL_ILLEGAL_FORMAT) private String email; @NotBlank @Length(min = USER_PASSWORD_MIN_LENGTH, max = USER_PASSWORD_MAX_LENGTH, message = USER_PASSWORD_ILLEGAL_LENGTH) private String password; private DateTime lastLogin; private String role = "ROLE_USER"; private String encodedUsername; private byte[] avatar = new byte[0]; private String banReason; private String salt; public static final int USERNAME_MIN_LENGTH = 3; /** * Maximum length of the username. */ public static final int USERNAME_MAX_LENGTH = 20; /** * Minimum length of the password. */ public static final int PASSWORD_MIN_LENGTH = 4; /** * Maximum length of the password. */ public static final int PASSWORD_MAX_LENGTH = 20; /** * Maximum avatar width in pixels. */ public static final int AVATAR_MAX_WIDTH = 100; /** * Maximum avatar height in pixels. */ public static final int AVATAR_MAX_HEIGHT = 100; /** * Maximum avatar size in kilobytes. */ public static final int AVATAR_MAX_SIZE = 65; /** * Only for hibernate usage. */ protected User() { } /** * Create instance with requiered fields. * * @param username username * @param email email * @param password password * @deprecated */ public User(String username, String email, String password) { this(); this.setUsername(username); this.email = email; this.password = password; this.salt = ""; } /** * Create instance with requiered fields. * * @param username username * @param email email * @param password password * @param salt salt */ public User(String username, String email, String password, String salt) { this(username, email, password); this.setSalt(salt); } /** * Get the user's Last Name. * * @return the lastName */ public String getLastName() { return lastName; } /** * @param lastName the lastName to set */ public void setLastName(String lastName) { this.lastName = lastName; } /** * @return the firstName */ public String getFirstName() { return firstName; } /** * @param firstName the firstName to set */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * @return the email */ public String getEmail() { return email; } /** * @param email the email to set */ public void setEmail(String email) { this.email = email; } /** * {@inheritDoc} */ @Override public String getUsername() { return username; } /** * Set the username and encoded username (based on username). * * @param username the username to set */ public final void setUsername(String username) { this.username = username; try { setEncodedUsername(URLEncoder.encode(username, "UTF-8").replace("+", "%20")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Could not encode username", e); } } /** * @return user role in security system */ public String getRole() { return role; } /** * @param role role */ public void setRole(String role) { this.role = role; } /** * @return user avatar */ public byte[] getAvatar() { return avatar.clone(); } /** * @param avatar user avatar */ public void setAvatar(byte[] avatar) { this.avatar = (avatar != null) ? avatar.clone() : new byte[0]; } /** * @return collection of user roles */ @Override public Collection<GrantedAuthority> getAuthorities() { Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new GrantedAuthorityImpl(role)); return authorities; } /** * @return password */ @Override public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } // methods from UserDetails inteface, indicating that // user can or can't authenticate. // we don't need this functional now and users always enabled /** * {@inheritDoc} */ @Override public boolean isAccountNonExpired() { return true; } /** * {@inheritDoc} */ @Override public boolean isAccountNonLocked() { return true; } /** * {@inheritDoc} */ @Override public boolean isCredentialsNonExpired() { return true; } /** * {@inheritDoc} */ @Override public boolean isEnabled() { return true; } /** * @return last login time and date */ public DateTime getLastLogin() { return lastLogin; } /** * Set last login time and date. * * @param lastLogin last login time */ protected void setLastLogin(DateTime lastLogin) { this.lastLogin = lastLogin; } private static final long serialVersionUID = 19981017L; /** * Updates last login time to current time. */ public void updateLastLoginTime() { this.lastLogin = DateTimeUtilsFactory.getDateTimeUtils().getNow(); } /** * Sets the encoded version of the username, where all the symbols that might mean something special (like symbols * {@code \;:",.}, etc are replaced with the encoding sequence of symbols. This is required for instance while * constructing a URL that contains a username (let's say a link to the user profile). * * @return encoded version of username that doesn't contain special symbols */ public String getEncodedUsername() { return encodedUsername; } /** * Sets the encoded version of the username, where all the symbols that might mean something special (like symbols * {@code \;:",.}, etc are replaced with the encoding sequence of symbols. This is required for instance while * constructing a URL that contains a username (let's say a link to the user profile). * * @param encodedUsername encoded version of username that doesn't contain special symbols */ protected final void setEncodedUsername(String encodedUsername) { this.encodedUsername = encodedUsername; } /** * This method returns the string ban reason description * * @return ban reason */ public String getBanReason() { return banReason; } /** * This method sets user ban reason description * * @param banReason User ban reason description */ public void setBanReason(String banReason) { this.banReason = banReason; } /** * This method returns the salt for encode password * * @return salt string */ public String getSalt() { return salt; } /** * This method sets salt for encode password * @param salt salt salstring */ public void setSalt(String salt) { this.salt = salt; } }
#JTALKSCOMMON69 * Need to change hardcoded entity fields validation values to be declared in constants
jtalks-common-model/src/main/java/org/jtalks/common/model/entity/User.java
#JTALKSCOMMON69 * Need to change hardcoded entity fields validation values to be declared in constants
<ide><path>talks-common-model/src/main/java/org/jtalks/common/model/entity/User.java <ide> private static final String USER_CANT_BE_NULL = "{user.username.null_constraint_violation}"; <ide> <ide> public static final int USER_USERNAME_MIN_LENGTH = 1; <del> public static final int USER_USERNAME_MAX_LENGTH = 100; <add> public static final int USER_USERNAME_MAX_LENGTH = 25; <ide> public static final int USER_PASSWORD_MIN_LENGTH = 1; <del> public static final int USER_PASSWORD_MAX_LENGTH = 100; <add> public static final int USER_PASSWORD_MAX_LENGTH = 25; <ide> <ide> <ide> private String lastName;
Java
agpl-3.0
dc3ca0e180db59575c6cda084ca59f68df7d736c
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
e48bcfa4-2e60-11e5-9284-b827eb9e62be
hello.java
e485fa2a-2e60-11e5-9284-b827eb9e62be
e48bcfa4-2e60-11e5-9284-b827eb9e62be
hello.java
e48bcfa4-2e60-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>e485fa2a-2e60-11e5-9284-b827eb9e62be <add>e48bcfa4-2e60-11e5-9284-b827eb9e62be
Java
apache-2.0
525364cf0ec531d154ce37047198ab9e1ad60795
0
GlenRSmith/elasticsearch,nknize/elasticsearch,HonzaKral/elasticsearch,GlenRSmith/elasticsearch,nknize/elasticsearch,coding0011/elasticsearch,strapdata/elassandra,strapdata/elassandra,gingerwizard/elasticsearch,gingerwizard/elasticsearch,uschindler/elasticsearch,vroyer/elassandra,uschindler/elasticsearch,nknize/elasticsearch,GlenRSmith/elasticsearch,robin13/elasticsearch,gingerwizard/elasticsearch,HonzaKral/elasticsearch,gfyoung/elasticsearch,uschindler/elasticsearch,nknize/elasticsearch,nknize/elasticsearch,HonzaKral/elasticsearch,robin13/elasticsearch,scorpionvicky/elasticsearch,coding0011/elasticsearch,gingerwizard/elasticsearch,GlenRSmith/elasticsearch,robin13/elasticsearch,scorpionvicky/elasticsearch,gingerwizard/elasticsearch,strapdata/elassandra,coding0011/elasticsearch,coding0011/elasticsearch,scorpionvicky/elasticsearch,strapdata/elassandra,GlenRSmith/elasticsearch,vroyer/elassandra,gfyoung/elasticsearch,strapdata/elassandra,coding0011/elasticsearch,scorpionvicky/elasticsearch,gfyoung/elasticsearch,gingerwizard/elasticsearch,gfyoung/elasticsearch,scorpionvicky/elasticsearch,vroyer/elassandra,robin13/elasticsearch,uschindler/elasticsearch,HonzaKral/elasticsearch,uschindler/elasticsearch,gfyoung/elasticsearch,gingerwizard/elasticsearch,robin13/elasticsearch
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.security.authc.ldap.support; import com.unboundid.ldap.sdk.AsyncRequestID; import com.unboundid.ldap.sdk.AsyncSearchResultListener; import com.unboundid.ldap.sdk.DN; import com.unboundid.ldap.sdk.DereferencePolicy; import com.unboundid.ldap.sdk.Filter; import com.unboundid.ldap.sdk.LDAPConnection; import com.unboundid.ldap.sdk.LDAPConnectionPool; import com.unboundid.ldap.sdk.LDAPException; import com.unboundid.ldap.sdk.LDAPInterface; import com.unboundid.ldap.sdk.LDAPURL; import com.unboundid.ldap.sdk.ResultCode; import com.unboundid.ldap.sdk.SearchRequest; import com.unboundid.ldap.sdk.SearchResult; import com.unboundid.ldap.sdk.SearchResultEntry; import com.unboundid.ldap.sdk.SearchResultReference; import com.unboundid.ldap.sdk.SearchScope; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.util.Supplier; import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.SetOnce; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.Strings; import org.elasticsearch.common.logging.ESLoggerFactory; import org.elasticsearch.common.util.concurrent.CountDown; import org.elasticsearch.xpack.security.support.Exceptions; import javax.naming.ldap.Rdn; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.function.BiConsumer; import java.util.stream.Collectors; public final class LdapUtils { public static final Filter OBJECT_CLASS_PRESENCE_FILTER = Filter.createPresenceFilter("objectClass"); private LdapUtils() { } public static DN dn(String dn) { try { return new DN(dn); } catch (LDAPException e) { throw new IllegalArgumentException("invalid DN [" + dn + "]", e); } } public static String relativeName(DN dn) { return dn.getRDNString().split("=")[1].trim(); } public static String escapedRDNValue(String rdn) { // We can't use UnboundID RDN here because it expects attribute=value, not just value return Rdn.escapeValue(rdn); } /** * This method performs an asynchronous ldap search operation that could have multiple results */ public static void searchForEntry(LDAPInterface ldap, String baseDN, SearchScope scope, Filter filter, int timeLimitSeconds, ActionListener<SearchResultEntry> listener, String... attributes) { if (ldap instanceof LDAPConnection) { searchForEntry((LDAPConnection) ldap, baseDN, scope, filter, timeLimitSeconds, listener, attributes); } else if (ldap instanceof LDAPConnectionPool) { searchForEntry((LDAPConnectionPool) ldap, baseDN, scope, filter, timeLimitSeconds, listener, attributes); } else { throw new IllegalArgumentException("unsupported LDAPInterface implementation: " + ldap); } } /** * This method performs an asynchronous ldap search operation that only expects at most one result. If more than one result is found * then this is an error. If no results are found, then {@code null} will be returned. */ public static void searchForEntry(LDAPConnection ldap, String baseDN, SearchScope scope, Filter filter, int timeLimitSeconds, ActionListener<SearchResultEntry> listener, String... attributes) { LdapSearchResultListener searchResultListener = new SingleEntryListener(ldap, listener, filter); try { SearchRequest request = new SearchRequest(searchResultListener, baseDN, scope, DereferencePolicy.NEVER, 0, timeLimitSeconds, false, filter, attributes); searchResultListener.setSearchRequest(request); ldap.asyncSearch(request); } catch (LDAPException e) { listener.onFailure(e); } } /** * This method performs an asynchronous ldap search operation that only expects at most one result. If more than one result is found * then this is an error. If no results are found, then {@code null} will be returned. */ public static void searchForEntry(LDAPConnectionPool ldap, String baseDN, SearchScope scope, Filter filter, int timeLimitSeconds, ActionListener<SearchResultEntry> listener, String... attributes) { boolean searching = false; LDAPConnection ldapConnection = null; try { ldapConnection = ldap.getConnection(); final LDAPConnection finalConnection = ldapConnection; searchForEntry(finalConnection, baseDN, scope, filter, timeLimitSeconds, ActionListener.wrap( (entry) -> { IOUtils.close(() -> ldap.releaseConnection(finalConnection)); listener.onResponse(entry); }, (e) -> { IOUtils.closeWhileHandlingException(() -> ldap.releaseConnection(finalConnection)); listener.onFailure(e); }), attributes); searching = true; } catch (LDAPException e) { listener.onFailure(e); } finally { if (searching == false) { final LDAPConnection finalConnection = ldapConnection; IOUtils.closeWhileHandlingException(() -> ldap.releaseConnection(finalConnection)); } } } /** * This method performs an asynchronous ldap search operation that could have multiple results */ public static void search(LDAPInterface ldap, String baseDN, SearchScope scope, Filter filter, int timeLimitSeconds, ActionListener<List<SearchResultEntry>> listener, String... attributes) { if (ldap instanceof LDAPConnection) { search((LDAPConnection) ldap, baseDN, scope, filter, timeLimitSeconds, listener, attributes); } else if (ldap instanceof LDAPConnectionPool) { search((LDAPConnectionPool) ldap, baseDN, scope, filter, timeLimitSeconds, listener, attributes); } else { throw new IllegalArgumentException("unsupported LDAPInterface implementation: " + ldap); } } /** * This method performs an asynchronous ldap search operation that could have multiple results */ public static void search(LDAPConnection ldap, String baseDN, SearchScope scope, Filter filter, int timeLimitSeconds, ActionListener<List<SearchResultEntry>> listener, String... attributes) { LdapSearchResultListener searchResultListener = new LdapSearchResultListener(ldap, (asyncRequestID, searchResult) -> listener.onResponse(Collections.unmodifiableList(searchResult.getSearchEntries())), 1); try { SearchRequest request = new SearchRequest(searchResultListener, baseDN, scope, DereferencePolicy.NEVER, 0, timeLimitSeconds, false, filter, attributes); searchResultListener.setSearchRequest(request); ldap.asyncSearch(request); } catch (LDAPException e) { listener.onFailure(e); } } /** * This method performs an asynchronous ldap search operation that could have multiple results */ public static void search(LDAPConnectionPool ldap, String baseDN, SearchScope scope, Filter filter, int timeLimitSeconds, ActionListener<List<SearchResultEntry>> listener, String... attributes) { boolean searching = false; LDAPConnection ldapConnection = null; try { ldapConnection = ldap.getConnection(); final LDAPConnection finalConnection = ldapConnection; LdapSearchResultListener ldapSearchResultListener = new LdapSearchResultListener(ldapConnection, (asyncRequestID, searchResult) -> { IOUtils.closeWhileHandlingException(() -> ldap.releaseConnection(finalConnection)); listener.onResponse(Collections.unmodifiableList(searchResult.getSearchEntries())); }, 1); SearchRequest request = new SearchRequest(ldapSearchResultListener, baseDN, scope, DereferencePolicy.NEVER, 0, timeLimitSeconds, false, filter, attributes); ldapSearchResultListener.setSearchRequest(request); finalConnection.asyncSearch(request); searching = true; } catch (LDAPException e) { listener.onFailure(e); } finally { if (searching == false && ldapConnection != null) { final LDAPConnection finalConnection = ldapConnection; IOUtils.closeWhileHandlingException(() -> ldap.releaseConnection(finalConnection)); } } } public static Filter createFilter(String filterTemplate, String... arguments) throws LDAPException { return Filter.create(new MessageFormat(filterTemplate, Locale.ROOT).format((Object[]) encodeFilterValues(arguments), new StringBuffer(), null).toString()); } public static String[] attributesToSearchFor(String[] attributes) { return attributes == null ? new String[] { SearchRequest.NO_ATTRIBUTES } : attributes; } static String[] encodeFilterValues(String... arguments) { for (int i = 0; i < arguments.length; i++) { arguments[i] = Filter.encodeValue(arguments[i]); } return arguments; } private static class SingleEntryListener extends LdapSearchResultListener { SingleEntryListener(LDAPConnection ldapConnection, ActionListener<SearchResultEntry> listener, Filter filter) { super(ldapConnection, ((asyncRequestID, searchResult) -> { final List<SearchResultEntry> entryList = searchResult.getSearchEntries(); if (entryList.size() > 1) { listener.onFailure(Exceptions.authenticationError("multiple search results found for [{}]", filter)); } else if (entryList.size() == 1) { listener.onResponse(entryList.get(0)); } else { listener.onResponse(null); } }), 1); } } private static class LdapSearchResultListener implements AsyncSearchResultListener { private static final Logger LOGGER = ESLoggerFactory.getLogger(LdapUtils.class); private final List<SearchResultEntry> entryList = new ArrayList<>(); private final List<SearchResultReference> referenceList = new ArrayList<>(); protected final SetOnce<SearchRequest> searchRequestRef = new SetOnce<>(); private final BiConsumer<AsyncRequestID, SearchResult> consumer; private final LDAPConnection ldapConnection; private final int depth; LdapSearchResultListener(LDAPConnection ldapConnection, BiConsumer<AsyncRequestID, SearchResult> consumer, int depth) { this.ldapConnection = ldapConnection; this.consumer = consumer; this.depth = depth; } @Override public void searchEntryReturned(SearchResultEntry searchEntry) { entryList.add(searchEntry); } @Override public void searchReferenceReturned(SearchResultReference searchReference) { referenceList.add(searchReference); } @Override public void searchResultReceived(AsyncRequestID requestID, SearchResult searchResult) { // whenever we get a search result we need to check for a referral. A referral is a mechanism for an LDAP server to reference // an object stored in a different LDAP server/partition. There are cases where we need to follow a referral in order to get // the actual object we are searching for final String[] referralUrls = referenceList.stream() .flatMap((ref) -> Arrays.stream(ref.getReferralURLs())) .collect(Collectors.toList()) .toArray(Strings.EMPTY_ARRAY); final SearchRequest searchRequest = searchRequestRef.get(); if (referralUrls.length == 0 || searchRequest.followReferrals(ldapConnection) == false) { // either no referrals to follow or we have explicitly disabled referral following on the connection so we just create // a new search result that has the values we've collected. The search result passed to this method will not have of the // entries as we are using a result listener and the results are not being collected by the LDAP library LOGGER.trace("LDAP Search {} => {} ({})", searchRequest, searchResult, entryList); SearchResult resultWithValues = new SearchResult(searchResult.getMessageID(), searchResult.getResultCode(), searchResult .getDiagnosticMessage(), searchResult.getMatchedDN(), referralUrls, entryList, referenceList, entryList.size(), referenceList.size(), searchResult.getResponseControls()); consumer.accept(requestID, resultWithValues); } else if (depth >= ldapConnection.getConnectionOptions().getReferralHopLimit()) { // we've gone through too many levels of referrals so we terminate with the values collected so far and the proper result // code to indicate the search was terminated early LOGGER.trace("Referral limit exceeded {} => {} ({})", searchRequest, searchResult, entryList); SearchResult resultWithValues = new SearchResult(searchResult.getMessageID(), ResultCode.REFERRAL_LIMIT_EXCEEDED, searchResult.getDiagnosticMessage(), searchResult.getMatchedDN(), referralUrls, entryList, referenceList, entryList.size(), referenceList.size(), searchResult.getResponseControls()); consumer.accept(requestID, resultWithValues); } else { if (LOGGER.isTraceEnabled()) { LOGGER.trace("LDAP referred elsewhere {} => {}", searchRequest, Arrays.toString(referralUrls)); } // there are referrals to follow, so we start the process to follow the referrals final CountDown countDown = new CountDown(referralUrls.length); final List<String> referralUrlsList = new ArrayList<>(Arrays.asList(referralUrls)); BiConsumer<AsyncRequestID, SearchResult> referralConsumer = (reqID, innerResult) -> { // synchronize here since we are possibly sending out a lot of requests and the result lists are not thread safe and // this also provides us with a consistent view synchronized (this) { if (innerResult.getSearchEntries() != null) { entryList.addAll(innerResult.getSearchEntries()); } if (innerResult.getSearchReferences() != null) { referenceList.addAll(innerResult.getSearchReferences()); } } // count down and once all referrals have been traversed then we can create the results if (countDown.countDown()) { SearchResult resultWithValues = new SearchResult(searchResult.getMessageID(), searchResult.getResultCode(), searchResult.getDiagnosticMessage(), searchResult.getMatchedDN(), referralUrlsList.toArray(Strings.EMPTY_ARRAY), entryList, referenceList, entryList.size(), referenceList.size(), searchResult.getResponseControls()); consumer.accept(requestID, resultWithValues); } }; for (String referralUrl : referralUrls) { try { // for each referral follow it and any other referrals returned until we get to a depth that is greater than or // equal to the referral hop limit or all referrals have been followed. Each time referrals are followed from a // search result, the depth increases by 1 followReferral(ldapConnection, referralUrl, searchRequest, referralConsumer, depth + 1, searchResult, requestID); } catch (LDAPException e) { LOGGER.warn((Supplier<?>) () -> new ParameterizedMessage("caught exception while trying to follow referral [{}]", referralUrl), e); referralConsumer.accept(requestID, new SearchResult(searchResult.getMessageID(), e.getResultCode(), e.getDiagnosticMessage(), e.getMatchedDN(), e.getReferralURLs(), 0, 0, e.getResponseControls())); } } } } void setSearchRequest(SearchRequest searchRequest) { this.searchRequestRef.set(searchRequest); } } /** * Performs the actual connection and following of a referral given a URL string. This referral is being followed as it may contain a * result that is relevant to our search */ private static void followReferral(LDAPConnection ldapConnection, String urlString, SearchRequest searchRequest, BiConsumer<AsyncRequestID, SearchResult> consumer, int depth, SearchResult originatingResult, AsyncRequestID asyncRequestID) throws LDAPException { final LDAPURL referralURL = new LDAPURL(urlString); final String host = referralURL.getHost(); // the host must be present in order to follow a referral if (host != null) { // the referral URL often contains information necessary about the LDAP request such as the base DN, scope, and filter. If it // does not, then we reuse the values from the originating search request final String requestBaseDN; if (referralURL.baseDNProvided()) { requestBaseDN = referralURL.getBaseDN().toString(); } else { requestBaseDN = searchRequest.getBaseDN(); } final SearchScope requestScope; if (referralURL.scopeProvided()) { requestScope = referralURL.getScope(); } else { requestScope = searchRequest.getScope(); } final Filter requestFilter; if (referralURL.filterProvided()) { requestFilter = referralURL.getFilter(); } else { requestFilter = searchRequest.getFilter(); } // in order to follow the referral we need to open a new connection and we do so using the referral connector on the ldap // connection final LDAPConnection referralConn = ldapConnection.getReferralConnector().getReferralConnection(referralURL, ldapConnection); final LdapSearchResultListener listener = new LdapSearchResultListener(referralConn, (reqId, searchResult) -> { IOUtils.closeWhileHandlingException(referralConn); consumer.accept(reqId, searchResult); }, depth); boolean success = false; try { final SearchRequest referralSearchRequest = new SearchRequest(listener, searchRequest.getControls(), requestBaseDN, requestScope, searchRequest.getDereferencePolicy(), searchRequest.getSizeLimit(), searchRequest.getTimeLimitSeconds(), searchRequest.typesOnly(), requestFilter, searchRequest.getAttributes()); listener.setSearchRequest(searchRequest); referralConn.asyncSearch(referralSearchRequest); success = true; } finally { if (success == false) { IOUtils.closeWhileHandlingException(referralConn); } } } else { // nothing to really do since a null host cannot really be handled, so we just return with a response that is empty... consumer.accept(asyncRequestID, new SearchResult(originatingResult.getMessageID(), ResultCode.UNAVAILABLE, null, null, null, Collections.emptyList(), Collections.emptyList(), 0, 0, null)); } } }
elasticsearch/src/main/java/org/elasticsearch/xpack/security/authc/ldap/support/LdapUtils.java
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.security.authc.ldap.support; import com.unboundid.ldap.sdk.AsyncRequestID; import com.unboundid.ldap.sdk.AsyncSearchResultListener; import com.unboundid.ldap.sdk.DN; import com.unboundid.ldap.sdk.DereferencePolicy; import com.unboundid.ldap.sdk.Filter; import com.unboundid.ldap.sdk.LDAPConnection; import com.unboundid.ldap.sdk.LDAPConnectionPool; import com.unboundid.ldap.sdk.LDAPException; import com.unboundid.ldap.sdk.LDAPInterface; import com.unboundid.ldap.sdk.LDAPURL; import com.unboundid.ldap.sdk.ResultCode; import com.unboundid.ldap.sdk.SearchRequest; import com.unboundid.ldap.sdk.SearchResult; import com.unboundid.ldap.sdk.SearchResultEntry; import com.unboundid.ldap.sdk.SearchResultReference; import com.unboundid.ldap.sdk.SearchScope; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.util.Supplier; import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.SetOnce; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.Strings; import org.elasticsearch.common.logging.ESLoggerFactory; import org.elasticsearch.common.util.concurrent.CountDown; import org.elasticsearch.xpack.security.support.Exceptions; import javax.naming.ldap.Rdn; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.function.BiConsumer; import java.util.stream.Collectors; public final class LdapUtils { public static final Filter OBJECT_CLASS_PRESENCE_FILTER = Filter.createPresenceFilter("objectClass"); private LdapUtils() { } public static DN dn(String dn) { try { return new DN(dn); } catch (LDAPException e) { throw new IllegalArgumentException("invalid DN [" + dn + "]", e); } } public static String relativeName(DN dn) { return dn.getRDNString().split("=")[1].trim(); } public static String escapedRDNValue(String rdn) { // We can't use UnboundID RDN here because it expects attribute=value, not just value return Rdn.escapeValue(rdn); } /** * This method performs an asynchronous ldap search operation that could have multiple results */ public static void searchForEntry(LDAPInterface ldap, String baseDN, SearchScope scope, Filter filter, int timeLimitSeconds, ActionListener<SearchResultEntry> listener, String... attributes) { if (ldap instanceof LDAPConnection) { searchForEntry((LDAPConnection) ldap, baseDN, scope, filter, timeLimitSeconds, listener, attributes); } else if (ldap instanceof LDAPConnectionPool) { searchForEntry((LDAPConnectionPool) ldap, baseDN, scope, filter, timeLimitSeconds, listener, attributes); } else { throw new IllegalArgumentException("unsupported LDAPInterface implementation: " + ldap); } } /** * This method performs an asynchronous ldap search operation that only expects at most one result. If more than one result is found * then this is an error. If no results are found, then {@code null} will be returned. */ public static void searchForEntry(LDAPConnection ldap, String baseDN, SearchScope scope, Filter filter, int timeLimitSeconds, ActionListener<SearchResultEntry> listener, String... attributes) { LdapSearchResultListener searchResultListener = new SingleEntryListener(ldap, listener, filter); try { SearchRequest request = new SearchRequest(searchResultListener, baseDN, scope, DereferencePolicy.NEVER, 0, timeLimitSeconds, false, filter, attributes); searchResultListener.setSearchRequest(request); ldap.asyncSearch(request); } catch (LDAPException e) { listener.onFailure(e); } } /** * This method performs an asynchronous ldap search operation that only expects at most one result. If more than one result is found * then this is an error. If no results are found, then {@code null} will be returned. */ public static void searchForEntry(LDAPConnectionPool ldap, String baseDN, SearchScope scope, Filter filter, int timeLimitSeconds, ActionListener<SearchResultEntry> listener, String... attributes) { boolean searching = false; LDAPConnection ldapConnection = null; try { ldapConnection = ldap.getConnection(); final LDAPConnection finalConnection = ldapConnection; searchForEntry(finalConnection, baseDN, scope, filter, timeLimitSeconds, ActionListener.wrap( (entry) -> { IOUtils.close(() -> ldap.releaseConnection(finalConnection)); listener.onResponse(entry); }, (e) -> { IOUtils.closeWhileHandlingException(() -> ldap.releaseConnection(finalConnection)); listener.onFailure(e); }), attributes); searching = true; } catch (LDAPException e) { listener.onFailure(e); } finally { if (searching == false) { final LDAPConnection finalConnection = ldapConnection; IOUtils.closeWhileHandlingException(() -> ldap.releaseConnection(finalConnection)); } } } /** * This method performs an asynchronous ldap search operation that could have multiple results */ public static void search(LDAPInterface ldap, String baseDN, SearchScope scope, Filter filter, int timeLimitSeconds, ActionListener<List<SearchResultEntry>> listener, String... attributes) { if (ldap instanceof LDAPConnection) { search((LDAPConnection) ldap, baseDN, scope, filter, timeLimitSeconds, listener, attributes); } else if (ldap instanceof LDAPConnectionPool) { search((LDAPConnectionPool) ldap, baseDN, scope, filter, timeLimitSeconds, listener, attributes); } else { throw new IllegalArgumentException("unsupported LDAPInterface implementation: " + ldap); } } /** * This method performs an asynchronous ldap search operation that could have multiple results */ public static void search(LDAPConnection ldap, String baseDN, SearchScope scope, Filter filter, int timeLimitSeconds, ActionListener<List<SearchResultEntry>> listener, String... attributes) { LdapSearchResultListener searchResultListener = new LdapSearchResultListener(ldap, (asyncRequestID, searchResult) -> listener.onResponse(Collections.unmodifiableList(searchResult.getSearchEntries())), 1); try { SearchRequest request = new SearchRequest(searchResultListener, baseDN, scope, DereferencePolicy.NEVER, 0, timeLimitSeconds, false, filter, attributes); searchResultListener.setSearchRequest(request); ldap.asyncSearch(request); } catch (LDAPException e) { listener.onFailure(e); } } /** * This method performs an asynchronous ldap search operation that could have multiple results */ public static void search(LDAPConnectionPool ldap, String baseDN, SearchScope scope, Filter filter, int timeLimitSeconds, ActionListener<List<SearchResultEntry>> listener, String... attributes) { boolean searching = false; LDAPConnection ldapConnection = null; try { ldapConnection = ldap.getConnection(); final LDAPConnection finalConnection = ldapConnection; LdapSearchResultListener ldapSearchResultListener = new LdapSearchResultListener(ldapConnection, (asyncRequestID, searchResult) -> { IOUtils.closeWhileHandlingException(() -> ldap.releaseConnection(finalConnection)); listener.onResponse(Collections.unmodifiableList(searchResult.getSearchEntries())); }, 1); SearchRequest request = new SearchRequest(ldapSearchResultListener, baseDN, scope, DereferencePolicy.NEVER, 0, timeLimitSeconds, false, filter, attributes); ldapSearchResultListener.setSearchRequest(request); finalConnection.asyncSearch(request); searching = true; } catch (LDAPException e) { listener.onFailure(e); } finally { if (searching == false && ldapConnection != null) { final LDAPConnection finalConnection = ldapConnection; IOUtils.closeWhileHandlingException(() -> ldap.releaseConnection(finalConnection)); } } } public static Filter createFilter(String filterTemplate, String... arguments) throws LDAPException { return Filter.create(new MessageFormat(filterTemplate, Locale.ROOT).format((Object[]) encodeFilterValues(arguments), new StringBuffer(), null).toString()); } public static String[] attributesToSearchFor(String[] attributes) { return attributes == null ? new String[] { SearchRequest.NO_ATTRIBUTES } : attributes; } static String[] encodeFilterValues(String... arguments) { for (int i = 0; i < arguments.length; i++) { arguments[i] = Filter.encodeValue(arguments[i]); } return arguments; } private static class SingleEntryListener extends LdapSearchResultListener { SingleEntryListener(LDAPConnection ldapConnection, ActionListener<SearchResultEntry> listener, Filter filter) { super(ldapConnection, ((asyncRequestID, searchResult) -> { final List<SearchResultEntry> entryList = searchResult.getSearchEntries(); if (entryList.size() > 1) { listener.onFailure(Exceptions.authenticationError("multiple search results found for [{}]", filter)); } else if (entryList.size() == 1) { listener.onResponse(entryList.get(0)); } else { listener.onResponse(null); } }), 1); } } private static class LdapSearchResultListener implements AsyncSearchResultListener { private static final Logger LOGGER = ESLoggerFactory.getLogger(LdapUtils.class); private final List<SearchResultEntry> entryList = new ArrayList<>(); private final List<SearchResultReference> referenceList = new ArrayList<>(); protected final SetOnce<SearchRequest> searchRequestRef = new SetOnce<>(); private final BiConsumer<AsyncRequestID, SearchResult> consumer; private final LDAPConnection ldapConnection; private final int depth; LdapSearchResultListener(LDAPConnection ldapConnection, BiConsumer<AsyncRequestID, SearchResult> consumer, int depth) { this.ldapConnection = ldapConnection; this.consumer = consumer; this.depth = depth; } @Override public void searchEntryReturned(SearchResultEntry searchEntry) { entryList.add(searchEntry); } @Override public void searchReferenceReturned(SearchResultReference searchReference) { referenceList.add(searchReference); } @Override public void searchResultReceived(AsyncRequestID requestID, SearchResult searchResult) { // whenever we get a search result we need to check for a referral. A referral is a mechanism for an LDAP server to reference // an object stored in a different LDAP server/partition. There are cases where we need to follow a referral in order to get // the actual object we are searching for final String[] referralUrls = referenceList.stream() .flatMap((ref) -> Arrays.stream(ref.getReferralURLs())) .collect(Collectors.toList()) .toArray(Strings.EMPTY_ARRAY); final SearchRequest searchRequest = searchRequestRef.get(); if (referralUrls.length == 0 || searchRequest.followReferrals(ldapConnection) == false) { // either no referrals to follow or we have explicitly disabled referral following on the connection so we just create // a new search result that has the values we've collected. The search result passed to this method will not have of the // entries as we are using a result listener and the results are not being collected by the LDAP library SearchResult resultWithValues = new SearchResult(searchResult.getMessageID(), searchResult.getResultCode(), searchResult .getDiagnosticMessage(), searchResult.getMatchedDN(), referralUrls, entryList, referenceList, entryList.size(), referenceList.size(), searchResult.getResponseControls()); consumer.accept(requestID, resultWithValues); } else if (depth >= ldapConnection.getConnectionOptions().getReferralHopLimit()) { // we've gone through too many levels of referrals so we terminate with the values collected so far and the proper result // code to indicate the search was terminated early SearchResult resultWithValues = new SearchResult(searchResult.getMessageID(), ResultCode.REFERRAL_LIMIT_EXCEEDED, searchResult.getDiagnosticMessage(), searchResult.getMatchedDN(), referralUrls, entryList, referenceList, entryList.size(), referenceList.size(), searchResult.getResponseControls()); consumer.accept(requestID, resultWithValues); } else { // there are referrals to follow, so we start the process to follow the referrals final CountDown countDown = new CountDown(referralUrls.length); final List<String> referralUrlsList = new ArrayList<>(Arrays.asList(referralUrls)); BiConsumer<AsyncRequestID, SearchResult> referralConsumer = (reqID, innerResult) -> { // synchronize here since we are possibly sending out a lot of requests and the result lists are not thread safe and // this also provides us with a consistent view synchronized (this) { if (innerResult.getSearchEntries() != null) { entryList.addAll(innerResult.getSearchEntries()); } if (innerResult.getSearchReferences() != null) { referenceList.addAll(innerResult.getSearchReferences()); } } // count down and once all referrals have been traversed then we can create the results if (countDown.countDown()) { SearchResult resultWithValues = new SearchResult(searchResult.getMessageID(), searchResult.getResultCode(), searchResult.getDiagnosticMessage(), searchResult.getMatchedDN(), referralUrlsList.toArray(Strings.EMPTY_ARRAY), entryList, referenceList, entryList.size(), referenceList.size(), searchResult.getResponseControls()); consumer.accept(requestID, resultWithValues); } }; for (String referralUrl : referralUrls) { try { // for each referral follow it and any other referrals returned until we get to a depth that is greater than or // equal to the referral hop limit or all referrals have been followed. Each time referrals are followed from a // search result, the depth increases by 1 followReferral(ldapConnection, referralUrl, searchRequest, referralConsumer, depth + 1, searchResult, requestID); } catch (LDAPException e) { LOGGER.warn((Supplier<?>) () -> new ParameterizedMessage("caught exception while trying to follow referral [{}]", referralUrl), e); referralConsumer.accept(requestID, new SearchResult(searchResult.getMessageID(), e.getResultCode(), e.getDiagnosticMessage(), e.getMatchedDN(), e.getReferralURLs(), 0, 0, e.getResponseControls())); } } } } void setSearchRequest(SearchRequest searchRequest) { this.searchRequestRef.set(searchRequest); } } /** * Performs the actual connection and following of a referral given a URL string. This referral is being followed as it may contain a * result that is relevant to our search */ private static void followReferral(LDAPConnection ldapConnection, String urlString, SearchRequest searchRequest, BiConsumer<AsyncRequestID, SearchResult> consumer, int depth, SearchResult originatingResult, AsyncRequestID asyncRequestID) throws LDAPException { final LDAPURL referralURL = new LDAPURL(urlString); final String host = referralURL.getHost(); // the host must be present in order to follow a referral if (host != null) { // the referral URL often contains information necessary about the LDAP request such as the base DN, scope, and filter. If it // does not, then we reuse the values from the originating search request final String requestBaseDN; if (referralURL.baseDNProvided()) { requestBaseDN = referralURL.getBaseDN().toString(); } else { requestBaseDN = searchRequest.getBaseDN(); } final SearchScope requestScope; if (referralURL.scopeProvided()) { requestScope = referralURL.getScope(); } else { requestScope = searchRequest.getScope(); } final Filter requestFilter; if (referralURL.filterProvided()) { requestFilter = referralURL.getFilter(); } else { requestFilter = searchRequest.getFilter(); } // in order to follow the referral we need to open a new connection and we do so using the referral connector on the ldap // connection final LDAPConnection referralConn = ldapConnection.getReferralConnector().getReferralConnection(referralURL, ldapConnection); final LdapSearchResultListener listener = new LdapSearchResultListener(referralConn, (reqId, searchResult) -> { IOUtils.closeWhileHandlingException(referralConn); consumer.accept(reqId, searchResult); }, depth); boolean success = false; try { final SearchRequest referralSearchRequest = new SearchRequest(listener, searchRequest.getControls(), requestBaseDN, requestScope, searchRequest.getDereferencePolicy(), searchRequest.getSizeLimit(), searchRequest.getTimeLimitSeconds(), searchRequest.typesOnly(), requestFilter, searchRequest.getAttributes()); listener.setSearchRequest(searchRequest); referralConn.asyncSearch(referralSearchRequest); success = true; } finally { if (success == false) { IOUtils.closeWhileHandlingException(referralConn); } } } else { // nothing to really do since a null host cannot really be handled, so we just return with a response that is empty... consumer.accept(asyncRequestID, new SearchResult(originatingResult.getMessageID(), ResultCode.UNAVAILABLE, null, null, null, Collections.emptyList(), Collections.emptyList(), 0, 0, null)); } } }
Add TRACE logging for LDAP traffic (elastic/elasticsearch#4551) We frequently have support requests to diagnose LDAP realm problems. One of the tools that would be useful in those cases is to be able to turn on trace logging and be able to see the LDAP searches and their results Original commit: elastic/x-pack-elasticsearch@632d8e4f1996edb2b6ae9a3ce359242e92528f74
elasticsearch/src/main/java/org/elasticsearch/xpack/security/authc/ldap/support/LdapUtils.java
Add TRACE logging for LDAP traffic (elastic/elasticsearch#4551)
<ide><path>lasticsearch/src/main/java/org/elasticsearch/xpack/security/authc/ldap/support/LdapUtils.java <ide> // either no referrals to follow or we have explicitly disabled referral following on the connection so we just create <ide> // a new search result that has the values we've collected. The search result passed to this method will not have of the <ide> // entries as we are using a result listener and the results are not being collected by the LDAP library <add> LOGGER.trace("LDAP Search {} => {} ({})", searchRequest, searchResult, entryList); <ide> SearchResult resultWithValues = new SearchResult(searchResult.getMessageID(), searchResult.getResultCode(), searchResult <ide> .getDiagnosticMessage(), searchResult.getMatchedDN(), referralUrls, entryList, referenceList, entryList.size(), <ide> referenceList.size(), searchResult.getResponseControls()); <ide> } else if (depth >= ldapConnection.getConnectionOptions().getReferralHopLimit()) { <ide> // we've gone through too many levels of referrals so we terminate with the values collected so far and the proper result <ide> // code to indicate the search was terminated early <add> LOGGER.trace("Referral limit exceeded {} => {} ({})", searchRequest, searchResult, entryList); <ide> SearchResult resultWithValues = new SearchResult(searchResult.getMessageID(), ResultCode.REFERRAL_LIMIT_EXCEEDED, <ide> searchResult.getDiagnosticMessage(), searchResult.getMatchedDN(), referralUrls, entryList, referenceList, <ide> entryList.size(), referenceList.size(), searchResult.getResponseControls()); <ide> consumer.accept(requestID, resultWithValues); <ide> } else { <add> if (LOGGER.isTraceEnabled()) { <add> LOGGER.trace("LDAP referred elsewhere {} => {}", searchRequest, Arrays.toString(referralUrls)); <add> } <ide> // there are referrals to follow, so we start the process to follow the referrals <ide> final CountDown countDown = new CountDown(referralUrls.length); <ide> final List<String> referralUrlsList = new ArrayList<>(Arrays.asList(referralUrls));
Java
lgpl-2.1
c7ff868402ea16a863d11ee5454e44a29a056955
0
CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine
/* * jETeL/Clover - Java based ETL application framework. * Copyright (C) 2005-06 Javlin Consulting <[email protected]> * * This library 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 library 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 library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package org.jetel.data.parser; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.jetel.data.DataRecord; import org.jetel.exception.BadDataFormatException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.IParserExceptionHandler; import org.jetel.exception.JetelException; import org.jetel.exception.PolicyType; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.StringUtils; /** * Parsing data from xls file. * * @author avackova * */ public class XLSDataParser implements Parser { private final static int CELL_NUMBER_IN_SHEET = 25;//number of "Z" cell in excel sheet private final static int NO_METADATA_INFO = 0; private final static int ONLY_CLOVER_FIELDS = 1; private final static int CLOVER_FIELDS_AND_XLS_NUMBERS = 2; private final static int MAP_NAMES = 3; private final static int CLOVER_FIELDS_AND_XLS_NAMES = 4; static Log logger = LogFactory.getLog(XLSDataParser.class); private DataRecordMetadata metadata; private IParserExceptionHandler exceptionHandler; private String sheetName = null; private int recordCounter; private int firstRow = 0; private int currentRow; private HSSFWorkbook wb; private HSSFSheet sheet; private HSSFRow row; private HSSFCell cell; private HSSFDataFormat format; private int metadataRow = -1; private String[] cloverFields = null; private String[] xlsFields = null; private int[] fieldNumber ; /** * Constructor */ public XLSDataParser() { } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#getNext() */ public DataRecord getNext() throws JetelException { // create a new data record DataRecord record = new DataRecord(metadata); record.init(); record = parseNext(record); if(exceptionHandler != null ) { //use handler only if configured while(exceptionHandler.isExceptionThrowed()) { exceptionHandler.handleException(); record = parseNext(record); } } return record; } /** * This method gets string representation of cell value * * @param cell * @return */ private String getStringFromCell(HSSFCell cell) { short formatNumber = cell.getCellStyle().getDataFormat(); String pattern = format.getFormat(formatNumber); String cellValue = ""; switch (cell.getCellType()){ case HSSFCell.CELL_TYPE_BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_STRING: cellValue = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_FORMULA: cellValue = cell.getCellFormula(); break; case HSSFCell.CELL_TYPE_ERROR: cellValue = String.valueOf(cell.getErrorCellValue()); break; case HSSFCell.CELL_TYPE_NUMERIC: //in numeric cell can be date ... if (pattern.contains("M")||pattern.contains("D")||pattern.contains("Y")){ cellValue = cell.getDateCellValue().toString(); }else{//... or number cellValue = String.valueOf(cell.getNumericCellValue()); } break; } return cellValue; } /** * This method gets the next record from the sheet * * @param record * @return * @throws JetelException */ private DataRecord parseNext(DataRecord record) throws JetelException { row = sheet.getRow(currentRow); if (row==null) return null; //afterlast row char type; for (short i=0;i<fieldNumber.length;i++){ if (fieldNumber[i] == -1) continue; //in metdata there is not any field corresponding to this column cell = row.getCell(i); type = metadata.getField(fieldNumber[i]).getType(); try{ switch (type) { case DataFieldMetadata.DATE_FIELD: record.getField(fieldNumber[i]).setValue(cell.getDateCellValue()); break; case DataFieldMetadata.BYTE_FIELD: case DataFieldMetadata.STRING_FIELD: record.getField(fieldNumber[i]).fromString(getStringFromCell(cell)); break; case DataFieldMetadata.DECIMAL_FIELD: case DataFieldMetadata.INTEGER_FIELD: case DataFieldMetadata.LONG_FIELD: case DataFieldMetadata.NUMERIC_FIELD: record.getField(fieldNumber[i]).setValue(cell.getNumericCellValue()); break; } } catch (NumberFormatException bdne) {//exception when trying get date or number from not numeric cell BadDataFormatException bdfe = new BadDataFormatException(bdne.getMessage()); bdfe.setRecordNumber(currentRow+1); bdfe.setFieldNumber(fieldNumber[i]); String cellValue = getStringFromCell(cell); try { record.getField(fieldNumber[i]).fromString(cellValue); } catch (Exception e) { if (exceptionHandler != null) { // use handler only if configured exceptionHandler.populateHandler(getErrorMessage(bdfe .getMessage(), currentRow + 1, fieldNumber[i]), record, currentRow + 1, fieldNumber[i], cellValue, bdfe); } else { throw new RuntimeException(getErrorMessage(bdfe .getMessage(), currentRow + 1, fieldNumber[i])); } } }catch (NullPointerException np){// empty cell try { record.getField(fieldNumber[i]).setNull(true); }catch (BadDataFormatException ex){ BadDataFormatException bdfe = new BadDataFormatException(np.getMessage()); bdfe.setRecordNumber(currentRow+1); bdfe.setFieldNumber(fieldNumber[i]); if(exceptionHandler != null ) { //use handler only if configured exceptionHandler.populateHandler( getErrorMessage(bdfe.getMessage(), currentRow+1, fieldNumber[i]), record, currentRow + 1, fieldNumber[i], "null", bdfe); } else { throw new RuntimeException(getErrorMessage(bdfe.getMessage(), currentRow + 1, fieldNumber[i])); } } } } currentRow++; recordCounter++; return record; } /** * Assembles error message when exception occures during parsing * * @param exceptionMessage * message from exception getMessage() call * @param recNo * recordNumber * @param fieldNo * fieldNumber * @return error message */ private String getErrorMessage(String exceptionMessage, int recNo, int fieldNo) { StringBuffer message = new StringBuffer(); message.append(exceptionMessage); message.append(" when parsing record #"); message.append(recordCounter); message.append(" field "); message.append(metadata.getField(fieldNo).getName()); return message.toString(); } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#skip(int) */ public int skip(int nRec) throws JetelException { currentRow+=nRec; return nRec; } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#open(java.lang.Object, org.jetel.metadata.DataRecordMetadata) */ public void open(Object in, DataRecordMetadata _metadata)throws ComponentNotReadyException{ this.metadata = _metadata; recordCounter = 1; //creating workbook from input stream try { wb = new HSSFWorkbook((InputStream)in); }catch(IOException ex){ throw new ComponentNotReadyException(ex); } if (sheetName!=null){ sheet = wb.getSheet(sheetName); }else{ sheet = wb.getSheetAt(0); } format = wb.createDataFormat(); currentRow = firstRow; fieldNumber = new int[metadata.getNumFields()]; Arrays.fill(fieldNumber,-1); Map fieldNames = metadata.getFieldNames(); switch (getMappingType(metadataRow,cloverFields!=null,xlsFields!=null)) { case NO_METADATA_INFO: for (short i=0;i<fieldNumber.length;i++){ fieldNumber[i] = i; } break; case ONLY_CLOVER_FIELDS: for (int i = 0; i < cloverFields.length; i++) { try { fieldNumber[i] = ((Integer) fieldNames.get(cloverFields[i])); } catch (NullPointerException ex) { throw new ComponentNotReadyException("Clover field \"" + cloverFields[i] + "\" not found"); } } break; case CLOVER_FIELDS_AND_XLS_NUMBERS: if (cloverFields.length!=xlsFields.length){ throw new ComponentNotReadyException("Number of clover fields and xls fields must be the same"); } for (short i=0;i<cloverFields.length;i++){ String cellCode = xlsFields[i].toUpperCase(); int cellNumber = 0; for (int j=0;j<cellCode.length();j++){ cellNumber+=cellCode.charAt(j); } cellNumber+=CELL_NUMBER_IN_SHEET*(cellCode.length()-1) - 'A'*cellCode.length(); try { fieldNumber[cellNumber] = ((Integer)fieldNames.get(cloverFields[i])).shortValue(); }catch (NullPointerException ex) { throw new ComponentNotReadyException("Clover field \"" + cloverFields[i] + "\" not found"); } } break; case MAP_NAMES: row = sheet.getRow(metadataRow); int count = 0; for (Iterator i=row.cellIterator();i.hasNext();){ cell = (HSSFCell)i.next(); String cellValue = cell.getStringCellValue(); if (fieldNames.containsKey(cellValue)){ fieldNumber[cell.getCellNum()] = ((Integer)fieldNames.get(cellValue)).shortValue(); fieldNames.remove(cellValue); }else{ logger.warn("There is no field \"" + cellValue + "\" in output metadata"); } count++; } if (count<metadata.getNumFields()){ short lastCell = row.getLastCellNum(); for (short i=0;i<fieldNumber.length;i++){ if (fieldNumber[i] == -1) { fieldNumber[i] = lastCell++; } } } break; case CLOVER_FIELDS_AND_XLS_NAMES: if (cloverFields.length!=xlsFields.length){ throw new ComponentNotReadyException("Number of clover fields and xls fields must be the same"); } row = sheet.getRow(metadataRow); count = 0; for (Iterator i=row.cellIterator();i.hasNext();){ cell = (HSSFCell)i.next(); String cellValue = cell.getStringCellValue(); int xlsNumber = StringUtils.findString(cellValue,xlsFields); if (xlsNumber > -1){ try { fieldNumber[cell.getCellNum()] = ((Integer)fieldNames.get(cloverFields[xlsNumber])).shortValue(); }catch (NullPointerException ex) { throw new ComponentNotReadyException("Clover field \"" + cloverFields[xlsNumber] + "\" not found"); } count++; }else{ logger.warn("There is no field corresponding to \"" + cellValue + "\" in output metadata"); } } if (count<cloverFields.length){ logger.warn("Not all fields found"); } break; } } private int getMappingType(int metadataRow,boolean cloverFields,boolean xlsFields){ if (metadataRow == -1 && !cloverFields && !xlsFields){ return NO_METADATA_INFO; } if (metadataRow == -1 && !xlsFields){ return ONLY_CLOVER_FIELDS; } if (metadataRow == -1){ return CLOVER_FIELDS_AND_XLS_NUMBERS; } if (!cloverFields && !xlsFields){ return MAP_NAMES; } if (cloverFields && xlsFields){ return CLOVER_FIELDS_AND_XLS_NAMES; } return -1; } public void close() { // TODO Auto-generated method stub } public DataRecord getNext(DataRecord record) throws JetelException { record = parseNext(record); if(exceptionHandler != null ) { //use handler only if configured while(exceptionHandler.isExceptionThrowed()) { exceptionHandler.handleException(); record = parseNext(record); } } return record; } public void setExceptionHandler(IParserExceptionHandler handler) { this.exceptionHandler = handler; } public IParserExceptionHandler getExceptionHandler() { return exceptionHandler; } public PolicyType getPolicyType() { if(exceptionHandler != null) { return exceptionHandler.getType(); } return null; } public void setSheetName(String sheetName) { this.sheetName = sheetName; } public void setFirstRow(int firstRecord) { this.firstRow = firstRecord-1; } public int getRecordCount() { return recordCounter; } public void setCloverFields(String[] cloverFields) { this.metadataRow = 0; this.cloverFields = cloverFields; } public void setMetadataRow(int metadataRow) { this.metadataRow = metadataRow - 1; if (firstRow == 0) { firstRow = this.metadataRow +1; } } public void setXlsFields(String[] xlsFields, boolean names) { this.xlsFields = xlsFields; this.metadataRow = 0; } }
cloveretl.engine/src/org/jetel/data/parser/XLSDataParser.java
package org.jetel.data.parser; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.exception.BadDataFormatException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.IParserExceptionHandler; import org.jetel.exception.JetelException; import org.jetel.exception.PolicyType; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.StringUtils; public class XLSDataParser implements Parser { private static int CELL_NUMBER_IN_SHEET = 25; static Log logger = LogFactory.getLog(XLSDataParser.class); private DataRecordMetadata metadata; private IParserExceptionHandler exceptionHandler; private String sheetName = null; private int recordCounter; private int firstRow = 0; private int currentRow; private HSSFWorkbook wb; private HSSFSheet sheet; private HSSFRow row; private HSSFCell cell; private HSSFDataFormat format; private int metadataRow = -1; private String[] cloverFields = null; private String[] xlsFields = null; private boolean names; private short[] fieldNumber ; public XLSDataParser() { } public DataRecord getNext() throws JetelException { // create a new data record DataRecord record = new DataRecord(metadata); record.init(); record = parseNext(record); if(exceptionHandler != null ) { //use handler only if configured while(exceptionHandler.isExceptionThrowed()) { exceptionHandler.handleException(); record = parseNext(record); } } return record; } private String getStringFromCell(HSSFCell cell) { short formatNumber = cell.getCellStyle().getDataFormat(); String pattern = format.getFormat(formatNumber); String cellValue = ""; switch (cell.getCellType()){ case HSSFCell.CELL_TYPE_BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_STRING: cellValue = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_FORMULA: cellValue = cell.getCellFormula(); break; case HSSFCell.CELL_TYPE_ERROR: cellValue = String.valueOf(cell.getErrorCellValue()); break; case HSSFCell.CELL_TYPE_NUMERIC: if (pattern.contains("M")||pattern.contains("D")||pattern.contains("Y")){ cellValue = cell.getDateCellValue().toString(); }else{ cellValue = String.valueOf(cell.getNumericCellValue()); } break; } return cellValue; } private DataRecord parseNext(DataRecord record) throws JetelException { row = sheet.getRow(currentRow); if (row==null) return null; char type; for (short i=0;i<fieldNumber.length;i++){ if (fieldNumber[i] == -1) continue; //in metdata there is not any field corresponding to this column cell = row.getCell(i); type = metadata.getField(fieldNumber[i]).getType(); try{ switch (type) { case DataFieldMetadata.DATE_FIELD: record.getField(fieldNumber[i]).setValue(cell.getDateCellValue()); break; case DataFieldMetadata.BYTE_FIELD: case DataFieldMetadata.STRING_FIELD: record.getField(fieldNumber[i]).fromString(getStringFromCell(cell)); break; case DataFieldMetadata.DECIMAL_FIELD: case DataFieldMetadata.INTEGER_FIELD: case DataFieldMetadata.LONG_FIELD: case DataFieldMetadata.NUMERIC_FIELD: record.getField(fieldNumber[i]).setValue(cell.getNumericCellValue()); break; } } catch (NumberFormatException bdne) { BadDataFormatException bdfe = new BadDataFormatException(bdne.getMessage()); bdfe.setRecordNumber(currentRow+1); bdfe.setFieldNumber(fieldNumber[i]); if(exceptionHandler != null ) { //use handler only if configured String cellValue = getStringFromCell(cell); try{ record.getField(fieldNumber[i]).fromString(cellValue); }catch (Exception e) { exceptionHandler.populateHandler( getErrorMessage(bdfe.getMessage(), currentRow+1, fieldNumber[i]), record, currentRow + 1, fieldNumber[i], cellValue, bdfe); } } else { throw new RuntimeException(getErrorMessage(bdfe.getMessage(), recordCounter, fieldNumber[i])); } }catch (NullPointerException np){ try { record.getField(fieldNumber[i]).setNull(true); }catch (BadDataFormatException ex){ BadDataFormatException bdfe = new BadDataFormatException(np.getMessage()); bdfe.setRecordNumber(currentRow+1); bdfe.setFieldNumber(fieldNumber[i]); if(exceptionHandler != null ) { //use handler only if configured exceptionHandler.populateHandler( getErrorMessage(bdfe.getMessage(), currentRow+1, fieldNumber[i]), record, currentRow + 1, fieldNumber[i], "null", bdfe); } else { throw new RuntimeException(getErrorMessage(bdfe.getMessage(), recordCounter, fieldNumber[i])); } } } } currentRow++; recordCounter++; return record; } private String getErrorMessage(String exceptionMessage, int recNo, int fieldNo) { StringBuffer message = new StringBuffer(); message.append(exceptionMessage); message.append(" when parsing record #"); message.append(recordCounter); message.append(" field "); message.append(metadata.getField(fieldNo).getName()); return message.toString(); } public int skip(int nRec) throws JetelException { currentRow+=nRec; return nRec; } public void open(Object in, DataRecordMetadata _metadata)throws ComponentNotReadyException{ this.metadata = _metadata; recordCounter = 1; try { wb = new HSSFWorkbook((InputStream)in); }catch(IOException ex){ throw new ComponentNotReadyException(ex); } if (sheetName!=null){ sheet = wb.getSheet(sheetName); }else{ sheet = wb.getSheetAt(0); } format = wb.createDataFormat(); currentRow = firstRow; fieldNumber = new short[metadata.getNumFields()]; if (metadataRow == -1){ for (short i=0;i<fieldNumber.length;i++){ fieldNumber[i] = i; } }else{ Arrays.fill(fieldNumber,(short)-1); Map fieldNames = metadata.getFieldNames(); if (cloverFields == null){ row = sheet.getRow(metadataRow); int count = 0; for (Iterator i=row.cellIterator();i.hasNext();){ cell = (HSSFCell)i.next(); String cellValue = cell.getStringCellValue(); if (fieldNames.containsKey(cellValue)){ fieldNumber[cell.getCellNum()] = ((Integer)fieldNames.get(cellValue)).shortValue(); fieldNames.remove(cellValue); }else{ logger.warn("There is no field \"" + cellValue + "\" in output metadata"); } count++; } if (count<metadata.getNumFields()){ short lastCell = row.getLastCellNum(); for (short i=0;i<fieldNumber.length;i++){ if (fieldNumber[i] == -1) { fieldNumber[i] = lastCell++; } } } }else if (xlsFields == null){ for (short i = 0; i < cloverFields.length; i++) { try { fieldNumber[i] = ((Integer) fieldNames .get(cloverFields[i])).shortValue(); } catch (NullPointerException ex) { throw new ComponentNotReadyException("Clover field \"" + cloverFields[i] + "\" not found"); } } }else{ if (cloverFields.length!=xlsFields.length){ throw new ComponentNotReadyException("Number of clover fields and xls fields must be the same"); } if (!names){ for (short i=0;i<cloverFields.length;i++){ String cellCode = xlsFields[i].toUpperCase(); int cellNumber = 0; for (int j=0;j<cellCode.length();j++){ cellNumber+=cellCode.charAt(j); } cellNumber+=CELL_NUMBER_IN_SHEET*(cellCode.length()-1) - 'A'*cellCode.length(); try { fieldNumber[cellNumber] = ((Integer)fieldNames.get(cloverFields[i])).shortValue(); }catch (NullPointerException ex) { throw new ComponentNotReadyException("Clover field \"" + cloverFields[i] + "\" not found"); } } }else{ row = sheet.getRow(metadataRow); int count = 0; for (Iterator i=row.cellIterator();i.hasNext();){ cell = (HSSFCell)i.next(); String cellValue = cell.getStringCellValue(); int xlsNumber = StringUtils.findString(cellValue,xlsFields); if (xlsNumber > -1){ try { fieldNumber[cell.getCellNum()] = ((Integer)fieldNames.get(cloverFields[xlsNumber])).shortValue(); }catch (NullPointerException ex) { throw new ComponentNotReadyException("Clover field \"" + cloverFields[xlsNumber] + "\" not found"); } count++; }else{ logger.warn("There is no field corresponding to \"" + cellValue + "\" in output metadata"); } } if (count<cloverFields.length){ logger.warn("Not all fields found"); } } } } } public void close() { // TODO Auto-generated method stub } public DataRecord getNext(DataRecord record) throws JetelException { record = parseNext(record); if(exceptionHandler != null ) { //use handler only if configured while(exceptionHandler.isExceptionThrowed()) { exceptionHandler.handleException(); record = parseNext(record); } } return record; } public void setExceptionHandler(IParserExceptionHandler handler) { this.exceptionHandler = handler; } public IParserExceptionHandler getExceptionHandler() { return exceptionHandler; } public PolicyType getPolicyType() { if(exceptionHandler != null) { return exceptionHandler.getType(); } return null; } public void setSheetName(String sheetName) { this.sheetName = sheetName; } public void setFirstRow(int firstRecord) { this.firstRow = firstRecord-1; } public int getRecordCount() { return recordCounter; } public void setCloverFields(String[] cloverFields) { this.metadataRow = 0; this.cloverFields = cloverFields; } public void setMetadataRow(int metadataRow) { this.metadataRow = metadataRow - 1; if (firstRow == 0) { firstRow = this.metadataRow +1; } } public void setXlsFields(String[] xlsFields, boolean names) { this.xlsFields = xlsFields; this.names = names; this.metadataRow = 0; } }
changed open method git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@1506 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
cloveretl.engine/src/org/jetel/data/parser/XLSDataParser.java
changed open method
<ide><path>loveretl.engine/src/org/jetel/data/parser/XLSDataParser.java <add> <add>/* <add>* jETeL/Clover - Java based ETL application framework. <add>* Copyright (C) 2005-06 Javlin Consulting <[email protected]> <add>* <add>* This library is free software; you can redistribute it and/or <add>* modify it under the terms of the GNU Lesser General Public <add>* License as published by the Free Software Foundation; either <add>* version 2.1 of the License, or (at your option) any later version. <add>* <add>* This library is distributed in the hope that it will be useful, <add>* but WITHOUT ANY WARRANTY; without even the implied warranty of <add>* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU <add>* Lesser General Public License for more details. <add>* <add>* You should have received a copy of the GNU Lesser General Public <add>* License along with this library; if not, write to the Free Software <add>* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA <add>* <add>*/ <ide> <ide> package org.jetel.data.parser; <ide> <ide> import java.io.IOException; <ide> import java.io.InputStream; <del>import java.nio.charset.Charset; <del>import java.nio.charset.CharsetDecoder; <ide> import java.util.Arrays; <ide> import java.util.Iterator; <ide> import java.util.Map; <ide> import org.apache.poi.hssf.usermodel.HSSFSheet; <ide> import org.apache.poi.hssf.usermodel.HSSFWorkbook; <ide> import org.jetel.data.DataRecord; <del>import org.jetel.data.Defaults; <ide> import org.jetel.exception.BadDataFormatException; <ide> import org.jetel.exception.ComponentNotReadyException; <ide> import org.jetel.exception.IParserExceptionHandler; <ide> import org.jetel.metadata.DataRecordMetadata; <ide> import org.jetel.util.StringUtils; <ide> <add>/** <add> * Parsing data from xls file. <add> * <add> * @author avackova <add> * <add> */ <ide> public class XLSDataParser implements Parser { <ide> <del> private static int CELL_NUMBER_IN_SHEET = 25; <del> <add> private final static int CELL_NUMBER_IN_SHEET = 25;//number of "Z" cell in excel sheet <add> <add> private final static int NO_METADATA_INFO = 0; <add> private final static int ONLY_CLOVER_FIELDS = 1; <add> private final static int CLOVER_FIELDS_AND_XLS_NUMBERS = 2; <add> private final static int MAP_NAMES = 3; <add> private final static int CLOVER_FIELDS_AND_XLS_NAMES = 4; <add> <ide> static Log logger = LogFactory.getLog(XLSDataParser.class); <ide> <ide> private DataRecordMetadata metadata; <ide> private int metadataRow = -1; <ide> private String[] cloverFields = null; <ide> private String[] xlsFields = null; <del> private boolean names; <del> private short[] fieldNumber ; <del> <add> private int[] fieldNumber ; <add> <add> /** <add> * Constructor <add> */ <ide> public XLSDataParser() { <ide> } <ide> <add> /* (non-Javadoc) <add> * @see org.jetel.data.parser.Parser#getNext() <add> */ <ide> public DataRecord getNext() throws JetelException { <ide> // create a new data record <ide> DataRecord record = new DataRecord(metadata); <ide> return record; <ide> } <ide> <add> /** <add> * This method gets string representation of cell value <add> * <add> * @param cell <add> * @return <add> */ <ide> private String getStringFromCell(HSSFCell cell) { <ide> short formatNumber = cell.getCellStyle().getDataFormat(); <ide> String pattern = format.getFormat(formatNumber); <ide> break; <ide> case HSSFCell.CELL_TYPE_ERROR: cellValue = String.valueOf(cell.getErrorCellValue()); <ide> break; <del> case HSSFCell.CELL_TYPE_NUMERIC: <add> case HSSFCell.CELL_TYPE_NUMERIC: //in numeric cell can be date ... <ide> if (pattern.contains("M")||pattern.contains("D")||pattern.contains("Y")){ <ide> cellValue = cell.getDateCellValue().toString(); <del> }else{ <add> }else{//... or number <ide> cellValue = String.valueOf(cell.getNumericCellValue()); <ide> } <ide> break; <ide> return cellValue; <ide> } <ide> <add> /** <add> * This method gets the next record from the sheet <add> * <add> * @param record <add> * @return <add> * @throws JetelException <add> */ <ide> private DataRecord parseNext(DataRecord record) throws JetelException { <ide> row = sheet.getRow(currentRow); <del> if (row==null) return null; <add> if (row==null) return null; //afterlast row <ide> char type; <ide> for (short i=0;i<fieldNumber.length;i++){ <ide> if (fieldNumber[i] == -1) continue; //in metdata there is not any field corresponding to this column <ide> record.getField(fieldNumber[i]).setValue(cell.getNumericCellValue()); <ide> break; <ide> } <del> } catch (NumberFormatException bdne) { <add> } catch (NumberFormatException bdne) {//exception when trying get date or number from not numeric cell <ide> BadDataFormatException bdfe = new BadDataFormatException(bdne.getMessage()); <ide> bdfe.setRecordNumber(currentRow+1); <ide> bdfe.setFieldNumber(fieldNumber[i]); <del> if(exceptionHandler != null ) { //use handler only if configured <del> String cellValue = getStringFromCell(cell); <del> try{ <del> record.getField(fieldNumber[i]).fromString(cellValue); <del> }catch (Exception e) { <del> exceptionHandler.populateHandler( <del> getErrorMessage(bdfe.getMessage(), currentRow+1, fieldNumber[i]), <del> record, currentRow + 1, fieldNumber[i], cellValue, bdfe); <add> String cellValue = getStringFromCell(cell); <add> try { <add> record.getField(fieldNumber[i]).fromString(cellValue); <add> } catch (Exception e) { <add> if (exceptionHandler != null) { // use handler only if configured <add> exceptionHandler.populateHandler(getErrorMessage(bdfe <add> .getMessage(), currentRow + 1, fieldNumber[i]), <add> record, currentRow + 1, fieldNumber[i], <add> cellValue, bdfe); <add> } else { <add> throw new RuntimeException(getErrorMessage(bdfe <add> .getMessage(), currentRow + 1, fieldNumber[i])); <ide> } <del> } else { <del> throw new RuntimeException(getErrorMessage(bdfe.getMessage(), <del> recordCounter, fieldNumber[i])); <del> } <del> }catch (NullPointerException np){ <add> } <add> }catch (NullPointerException np){// empty cell <ide> try { <ide> record.getField(fieldNumber[i]).setNull(true); <ide> }catch (BadDataFormatException ex){ <ide> record, currentRow + 1, fieldNumber[i], "null", bdfe); <ide> } else { <ide> throw new RuntimeException(getErrorMessage(bdfe.getMessage(), <del> recordCounter, fieldNumber[i])); <add> currentRow + 1, fieldNumber[i])); <ide> } <ide> } <ide> } <ide> return record; <ide> } <ide> <add> /** <add> * Assembles error message when exception occures during parsing <add> * <add> * @param exceptionMessage <add> * message from exception getMessage() call <add> * @param recNo <add> * recordNumber <add> * @param fieldNo <add> * fieldNumber <add> * @return error message <add> */ <ide> private String getErrorMessage(String exceptionMessage, int recNo, int fieldNo) { <ide> StringBuffer message = new StringBuffer(); <ide> message.append(exceptionMessage); <ide> return message.toString(); <ide> } <ide> <add> /* (non-Javadoc) <add> * @see org.jetel.data.parser.Parser#skip(int) <add> */ <ide> public int skip(int nRec) throws JetelException { <ide> currentRow+=nRec; <ide> return nRec; <ide> } <ide> <add> /* (non-Javadoc) <add> * @see org.jetel.data.parser.Parser#open(java.lang.Object, org.jetel.metadata.DataRecordMetadata) <add> */ <ide> public void open(Object in, DataRecordMetadata _metadata)throws ComponentNotReadyException{ <ide> this.metadata = _metadata; <ide> recordCounter = 1; <add> //creating workbook from input stream <ide> try { <ide> wb = new HSSFWorkbook((InputStream)in); <ide> }catch(IOException ex){ <ide> } <ide> format = wb.createDataFormat(); <ide> currentRow = firstRow; <del> fieldNumber = new short[metadata.getNumFields()]; <del> if (metadataRow == -1){ <add> fieldNumber = new int[metadata.getNumFields()]; <add> Arrays.fill(fieldNumber,-1); <add> Map fieldNames = metadata.getFieldNames(); <add> switch (getMappingType(metadataRow,cloverFields!=null,xlsFields!=null)) { <add> case NO_METADATA_INFO: <ide> for (short i=0;i<fieldNumber.length;i++){ <ide> fieldNumber[i] = i; <ide> } <del> }else{ <del> Arrays.fill(fieldNumber,(short)-1); <del> Map fieldNames = metadata.getFieldNames(); <del> if (cloverFields == null){ <del> row = sheet.getRow(metadataRow); <del> int count = 0; <del> for (Iterator i=row.cellIterator();i.hasNext();){ <del> cell = (HSSFCell)i.next(); <del> String cellValue = cell.getStringCellValue(); <del> if (fieldNames.containsKey(cellValue)){ <del> fieldNumber[cell.getCellNum()] = ((Integer)fieldNames.get(cellValue)).shortValue(); <del> fieldNames.remove(cellValue); <del> }else{ <del> logger.warn("There is no field \"" + cellValue + "\" in output metadata"); <add> break; <add> case ONLY_CLOVER_FIELDS: <add> for (int i = 0; i < cloverFields.length; i++) { <add> try { <add> fieldNumber[i] = ((Integer) fieldNames.get(cloverFields[i])); <add> } catch (NullPointerException ex) { <add> throw new ComponentNotReadyException("Clover field \"" <add> + cloverFields[i] + "\" not found"); <add> } <add> } <add> break; <add> case CLOVER_FIELDS_AND_XLS_NUMBERS: <add> if (cloverFields.length!=xlsFields.length){ <add> throw new ComponentNotReadyException("Number of clover fields and xls fields must be the same"); <add> } <add> for (short i=0;i<cloverFields.length;i++){ <add> String cellCode = xlsFields[i].toUpperCase(); <add> int cellNumber = 0; <add> for (int j=0;j<cellCode.length();j++){ <add> cellNumber+=cellCode.charAt(j); <add> } <add> cellNumber+=CELL_NUMBER_IN_SHEET*(cellCode.length()-1) - 'A'*cellCode.length(); <add> try { <add> fieldNumber[cellNumber] = <add> ((Integer)fieldNames.get(cloverFields[i])).shortValue(); <add> }catch (NullPointerException ex) { <add> throw new ComponentNotReadyException("Clover field \"" <add> + cloverFields[i] + "\" not found"); <add> } <add> } <add> break; <add> case MAP_NAMES: <add> row = sheet.getRow(metadataRow); <add> int count = 0; <add> for (Iterator i=row.cellIterator();i.hasNext();){ <add> cell = (HSSFCell)i.next(); <add> String cellValue = cell.getStringCellValue(); <add> if (fieldNames.containsKey(cellValue)){ <add> fieldNumber[cell.getCellNum()] = ((Integer)fieldNames.get(cellValue)).shortValue(); <add> fieldNames.remove(cellValue); <add> }else{ <add> logger.warn("There is no field \"" + cellValue + "\" in output metadata"); <add> } <add> count++; <add> } <add> if (count<metadata.getNumFields()){ <add> short lastCell = row.getLastCellNum(); <add> for (short i=0;i<fieldNumber.length;i++){ <add> if (fieldNumber[i] == -1) { <add> fieldNumber[i] = lastCell++; <add> } <add> } <add> } <add> break; <add> case CLOVER_FIELDS_AND_XLS_NAMES: <add> if (cloverFields.length!=xlsFields.length){ <add> throw new ComponentNotReadyException("Number of clover fields and xls fields must be the same"); <add> } <add> row = sheet.getRow(metadataRow); <add> count = 0; <add> for (Iterator i=row.cellIterator();i.hasNext();){ <add> cell = (HSSFCell)i.next(); <add> String cellValue = cell.getStringCellValue(); <add> int xlsNumber = StringUtils.findString(cellValue,xlsFields); <add> if (xlsNumber > -1){ <add> try { <add> fieldNumber[cell.getCellNum()] = ((Integer)fieldNames.get(cloverFields[xlsNumber])).shortValue(); <add> }catch (NullPointerException ex) { <add> throw new ComponentNotReadyException("Clover field \"" <add> + cloverFields[xlsNumber] + "\" not found"); <ide> } <ide> count++; <del> } <del> if (count<metadata.getNumFields()){ <del> short lastCell = row.getLastCellNum(); <del> for (short i=0;i<fieldNumber.length;i++){ <del> if (fieldNumber[i] == -1) { <del> fieldNumber[i] = lastCell++; <del> } <del> } <del> } <del> }else if (xlsFields == null){ <del> for (short i = 0; i < cloverFields.length; i++) { <del> try { <del> fieldNumber[i] = ((Integer) fieldNames <del> .get(cloverFields[i])).shortValue(); <del> } catch (NullPointerException ex) { <del> throw new ComponentNotReadyException("Clover field \"" <del> + cloverFields[i] + "\" not found"); <del> } <del> } <del> }else{ <del> if (cloverFields.length!=xlsFields.length){ <del> throw new ComponentNotReadyException("Number of clover fields and xls fields must be the same"); <del> } <del> if (!names){ <del> for (short i=0;i<cloverFields.length;i++){ <del> String cellCode = xlsFields[i].toUpperCase(); <del> int cellNumber = 0; <del> for (int j=0;j<cellCode.length();j++){ <del> cellNumber+=cellCode.charAt(j); <del> } <del> cellNumber+=CELL_NUMBER_IN_SHEET*(cellCode.length()-1) - 'A'*cellCode.length(); <del> try { <del> fieldNumber[cellNumber] = <del> ((Integer)fieldNames.get(cloverFields[i])).shortValue(); <del> }catch (NullPointerException ex) { <del> throw new ComponentNotReadyException("Clover field \"" <del> + cloverFields[i] + "\" not found"); <del> } <del> } <ide> }else{ <del> row = sheet.getRow(metadataRow); <del> int count = 0; <del> for (Iterator i=row.cellIterator();i.hasNext();){ <del> cell = (HSSFCell)i.next(); <del> String cellValue = cell.getStringCellValue(); <del> int xlsNumber = StringUtils.findString(cellValue,xlsFields); <del> if (xlsNumber > -1){ <del> try { <del> fieldNumber[cell.getCellNum()] = ((Integer)fieldNames.get(cloverFields[xlsNumber])).shortValue(); <del> }catch (NullPointerException ex) { <del> throw new ComponentNotReadyException("Clover field \"" <del> + cloverFields[xlsNumber] + "\" not found"); <del> } <del> count++; <del> }else{ <del> logger.warn("There is no field corresponding to \"" + cellValue + "\" in output metadata"); <del> } <del> } <del> if (count<cloverFields.length){ <del> logger.warn("Not all fields found"); <del> } <del> } <del> } <del> } <add> logger.warn("There is no field corresponding to \"" + cellValue + "\" in output metadata"); <add> } <add> } <add> if (count<cloverFields.length){ <add> logger.warn("Not all fields found"); <add> } <add> break; <add> } <add> } <add> <add> private int getMappingType(int metadataRow,boolean cloverFields,boolean xlsFields){ <add> if (metadataRow == -1 && !cloverFields && !xlsFields){ <add> return NO_METADATA_INFO; <add> } <add> if (metadataRow == -1 && !xlsFields){ <add> return ONLY_CLOVER_FIELDS; <add> } <add> if (metadataRow == -1){ <add> return CLOVER_FIELDS_AND_XLS_NUMBERS; <add> } <add> if (!cloverFields && !xlsFields){ <add> return MAP_NAMES; <add> } <add> if (cloverFields && xlsFields){ <add> return CLOVER_FIELDS_AND_XLS_NAMES; <add> } <add> return -1; <ide> } <ide> <ide> public void close() { <ide> <ide> public void setXlsFields(String[] xlsFields, boolean names) { <ide> this.xlsFields = xlsFields; <del> this.names = names; <ide> this.metadataRow = 0; <ide> } <ide>
Java
mit
0a1d90e3611f65830551ddac2f0ead646a66b2b3
0
coffeine-009/storage
/** * Copyright (c) 2014-2017 by Coffeine Inc * * @author <a href = "mailto:[email protected]>Vitaliy Tsutsman</a> * * @date 1/21/17 3:48 PM */ package com.thecoffeine.storage.utils; import org.junit.Test; /** * Tests of {@link FileUtil} * * @version 1.0 * @see FileUtil */ public class FileUtilTests { /** * Check if util class is abstract. */ @Test( expected = InstantiationException.class) public void testNoInstances() throws IllegalAccessException, InstantiationException { FileUtil.class.newInstance(); } }
src/test/java/com/thecoffeine/storage/utils/FileUtilTests.java
/** * Copyright (c) 2014-2017 by Coffeine Inc * * @author <a href = "mailto:[email protected]>Vitaliy Tsutsman</a> * * @date 1/21/17 3:48 PM */ package com.thecoffeine.storage.utils; import org.junit.Test; import java.lang.reflect.Modifier; import static org.junit.Assert.assertTrue; /** * Tests of {@link FileUtil} * * @version 1.0 * @see FileUtil */ public class FileUtilTests { /** * Check if util class is abstract. */ @Test public void testNoInstances() { //- Trick for cobertura -// new FileUtil() {};//FIXME: remove if cobertura can handle this. //- Real check -// assertTrue( "Util class has to be abstract", Modifier.isAbstract( FileUtil.class.getModifiers() ) ); } }
Findbugs fixes.
src/test/java/com/thecoffeine/storage/utils/FileUtilTests.java
Findbugs fixes.
<ide><path>rc/test/java/com/thecoffeine/storage/utils/FileUtilTests.java <ide> <ide> import org.junit.Test; <ide> <del>import java.lang.reflect.Modifier; <del> <del>import static org.junit.Assert.assertTrue; <del> <ide> /** <ide> * Tests of {@link FileUtil} <ide> * <ide> /** <ide> * Check if util class is abstract. <ide> */ <del> @Test <del> public void testNoInstances() { <del> //- Trick for cobertura -// <del> new FileUtil() {};//FIXME: remove if cobertura can handle this. <del> <del> //- Real check -// <del> assertTrue( <del> "Util class has to be abstract", <del> Modifier.isAbstract( FileUtil.class.getModifiers() ) <del> ); <add> @Test( expected = InstantiationException.class) <add> public void testNoInstances() throws IllegalAccessException, InstantiationException { <add> FileUtil.class.newInstance(); <ide> } <ide> }
JavaScript
mit
5ed1835c5324a7b7b1f661dd189044113eb467c5
0
mrogach2350/rpgLoot,mrogach2350/rpgLoot
Meteor.subscribe('items'); Template.GroupItems.helpers({ items: ()=> { return Items.find({inGroupStash: true}); } }); Template.GroupItems.events({ 'click .toggle-group'() { Meteor.call('toggleGroupItem', this._id, this.inGroupStash); var current = FlowRouter.current(); if (current.params.characterName){ newOwner = current.params.characterName; } else { newOwner = "DM"; } Meteor.call('togglePlayerItem', this._id, newOwner ); }, 'click .delete'() { Items.remove(this._id); } });
client/items/GroupItems.js
Meteor.subscribe('items'); Template.GroupItems.helpers({ items: ()=> { return Items.find({inGroupStash: true}); } }); Template.GroupItems.events({ 'click .toggle-group'() { Meteor.call('toggleGroupItem', this._id, this.inGroupStash); }, 'click .delete'() { Items.remove(this._id); } });
added change owner method
client/items/GroupItems.js
added change owner method
<ide><path>lient/items/GroupItems.js <ide> Template.GroupItems.events({ <ide> 'click .toggle-group'() { <ide> Meteor.call('toggleGroupItem', this._id, this.inGroupStash); <add> <add> var current = FlowRouter.current(); <add> if (current.params.characterName){ <add> newOwner = current.params.characterName; <add> } else { <add> newOwner = "DM"; <add> } <add> Meteor.call('togglePlayerItem', this._id, newOwner ); <ide> }, <ide> 'click .delete'() { <ide> Items.remove(this._id);
Java
epl-1.0
f8451c8e8c571e164352d27989556226db33bf78
0
Netcentric/accesscontroltool,mtstv/accesscontroltool
package biz.netcentric.cq.tools.actool.authorizableutils; import org.apache.commons.lang.StringUtils; public class AuthorizableConfigBean { private String principalID; private String principalName; private String[] memberOf; private String description; private String path; private String password; private boolean isGroup = true; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isGroup() { return isGroup; } public void setIsGroup(boolean isGroup) { this.isGroup = isGroup; } public void memberOf(boolean isGroup) { this.isGroup = isGroup; } public String getPrincipalName() { return principalName; } public void setAuthorizableName(String principalName) { this.principalName = principalName; } public String getPrincipalID() { return principalID; } public void setPrincipalID(final String principalID) { this.principalID = principalID; } public String[] getMemberOf() { return memberOf; } public boolean isMemberOfOtherGroups(){ return memberOf != null; } public String getMemberOfString() { if(memberOf == null){ return ""; } StringBuilder memberOfString = new StringBuilder(); for(String group : memberOf){ memberOfString.append(group).append(","); } return StringUtils.chop(memberOfString.toString()); } public void setMemberOf(final String[] memberOf) { this.memberOf = memberOf; } public String getDescription() { return description; } public void setDescription(final String description) { this.description = description; } public String getPath() { return path; } public void setPath(final String path) { this.path = path; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("\n" +"id: " + this.principalID + "\n"); sb.append("name: " + this.principalName + "\n"); sb.append("description: " + this.description + "\n"); sb.append("path: " + this.path + "\n"); sb.append("memberOf: " + this.getMemberOfString() + "\n"); return sb.toString(); } }
accesscontroltool-bundle/src/main/java/biz/netcentric/cq/tools/actool/authorizableutils/AuthorizableConfigBean.java
package biz.netcentric.cq.tools.actool.authorizableutils; import org.apache.commons.lang.StringUtils; public class AuthorizableConfigBean { private String principalID; private String principalName; private String[] memberOf; private String description; private String path; private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } private boolean isGroup; public boolean isGroup() { return isGroup; } public void setIsGroup(boolean isGroup) { this.isGroup = isGroup; } public void memberOf(boolean isGroup) { this.isGroup = isGroup; } public String getPrincipalName() { return principalName; } public void setAuthorizableName(String principalName) { this.principalName = principalName; } public String getPrincipalID() { return principalID; } public void setPrincipalID(final String principalID) { this.principalID = principalID; } public String[] getMemberOf() { return memberOf; } public boolean isMemberOfOtherGroups(){ return memberOf != null; } public String getMemberOfString() { if(memberOf == null){ return ""; } StringBuilder memberOfString = new StringBuilder(); for(String group : memberOf){ memberOfString.append(group).append(","); } return StringUtils.chop(memberOfString.toString()); } public void setMemberOf(final String[] memberOf) { this.memberOf = memberOf; } public String getDescription() { return description; } public void setDescription(final String description) { this.description = description; } public String getPath() { return path; } public void setPath(final String path) { this.path = path; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("\n" +"id: " + this.principalID + "\n"); sb.append("name: " + this.principalName + "\n"); sb.append("description: " + this.description + "\n"); sb.append("path: " + this.path + "\n"); sb.append("memberOf: " + this.getMemberOfString() + "\n"); return sb.toString(); } }
CQ-76 git-svn-id: 1fe78034f366cabe9e91c66cdd7653c9e6c31dfe@383 698b1b75-dbda-4fde-87e6-ec25ab2619bc
accesscontroltool-bundle/src/main/java/biz/netcentric/cq/tools/actool/authorizableutils/AuthorizableConfigBean.java
CQ-76
<ide><path>ccesscontroltool-bundle/src/main/java/biz/netcentric/cq/tools/actool/authorizableutils/AuthorizableConfigBean.java <ide> private String description; <ide> private String path; <ide> private String password; <add> private boolean isGroup = true; <ide> <ide> public String getPassword() { <ide> return password; <ide> this.password = password; <ide> } <ide> <del> private boolean isGroup; <add> <ide> <ide> public boolean isGroup() { <ide> return isGroup;
Java
apache-2.0
87acd239cc1c8dfd33bff58fc446a6f1b0806823
0
treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag
package io.digdag.core.schedule; import com.google.inject.Inject; import com.google.inject.Module; import com.google.inject.Binder; import com.google.inject.Scopes; import com.google.inject.multibindings.Multibinder; import io.digdag.spi.SchedulerFactory; public class ScheduleModule implements Module { @Override public void configure(Binder binder) { binder.bind(SchedulerManager.class).in(Scopes.SINGLETON); Multibinder.newSetBinder(binder, SchedulerFactory.class); } }
digdag-core/src/main/java/io/digdag/core/schedule/ScheduleModule.java
package io.digdag.core.schedule; import com.google.inject.Inject; import com.google.inject.Module; import com.google.inject.Binder; import com.google.inject.Scopes; public class ScheduleModule implements Module { @Override public void configure(Binder binder) { binder.bind(SchedulerManager.class).in(Scopes.SINGLETON); } }
Set<SchedulerFactory> should be bound explicitly in case there're no classes bound
digdag-core/src/main/java/io/digdag/core/schedule/ScheduleModule.java
Set<SchedulerFactory> should be bound explicitly in case there're no classes bound
<ide><path>igdag-core/src/main/java/io/digdag/core/schedule/ScheduleModule.java <ide> import com.google.inject.Module; <ide> import com.google.inject.Binder; <ide> import com.google.inject.Scopes; <add>import com.google.inject.multibindings.Multibinder; <add> <add>import io.digdag.spi.SchedulerFactory; <ide> <ide> public class ScheduleModule <ide> implements Module <ide> public void configure(Binder binder) <ide> { <ide> binder.bind(SchedulerManager.class).in(Scopes.SINGLETON); <add> Multibinder.newSetBinder(binder, SchedulerFactory.class); <ide> } <ide> }
Java
apache-2.0
95cb307092a0acb625a9f45a8e0323c671c7e1d3
0
codahale/shamir
/* * 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.codahale.shamir; import java.security.SecureRandom; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * Two static methods which use Shamir's Secret Sharing over {@code GF(256)} to * securely split secrets into {@code N} shares, of which {@code K} can be * combined to recover the original secret. * * @see <a href="https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing">Shamir's Secret * Sharing</a> */ public final class SecretSharing { private SecretSharing() { throw new AssertionError("No SecretSharing instances for you!"); } /** * Splits the given secret into {@code n} shares, of which any {@code k} or * more can be combined to recover the original secret. * * @param n the number of shares to produce (must be {@code >1}) * @param k the threshold of combinable shares (must be {@code <= n}) * @param secret the secret to split * @return a set of {@code n} {@link Share} instances */ public static Set<Share> split(int n, int k, byte[] secret) { Objects.requireNonNull(secret, "secret must not be null"); if (k <= 1) { throw new IllegalArgumentException("K must be > 1"); } if (n < k) { throw new IllegalArgumentException("N must be >= K"); } // generate shares final SecureRandom random = new SecureRandom(); final byte[][] shares = new byte[n][secret.length]; for (int i = 0; i < secret.length; i++) { // for each byte, generate a random polynomial, p final byte[] p = GF256.generate(random, k - 1, secret[i]); for (byte x = 1; x <= n; x++) { // each share's byte is p(shareId) shares[x - 1][i] = GF256.eval(p, x); } } // return as a set of objects return IntStream.range(0, n) .mapToObj(i -> new Share(i + 1, shares[i])) .collect(Collectors.toSet()); } /** * Combines the given shares into the original secret. * <p> * <b>N.B.:</b> There is no way to determine whether or not the returned * value is actually the original secret. If the shares are incorrect, or * are under the threshold value used to split the secret, a random value * will be returned. * * @param shares a set of {@link Share} instances * @return the original secret * @throws IllegalArgumentException if {@code shares} is empty or contains values of varying * lengths */ public static byte[] combine(Set<Share> shares) { final byte[] secret = new byte[secretLength(shares)]; for (int i = 0; i < secret.length; i++) { final byte[][] points = new byte[shares.size()][2]; int p = 0; for (Share share : shares) { points[p][0] = (byte) share.id; points[p][1] = share.value[i]; p++; } secret[i] = GF256.interpolate(points); } return secret; } private static int secretLength(Set<Share> shares) { Objects.requireNonNull(shares, "Shares must not be null"); final int[] l = shares.stream().mapToInt(s -> s.value.length).distinct().toArray(); if (l.length == 0) { throw new IllegalArgumentException("No shares provided"); } if (l.length != 1) { throw new IllegalArgumentException("Varying lengths of share values"); } return l[0]; } }
src/main/java/com/codahale/shamir/SecretSharing.java
/* * 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.codahale.shamir; import java.security.SecureRandom; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * Two static methods which use Shamir's Secret Sharing over {@code GF(256)} to * securely split secrets into {@code N} shares, of which {@code K} can be * combined to recover the original secret. * * @see <a href="https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing">Shamir's Secret * Sharing</a> */ public final class SecretSharing { private SecretSharing() { throw new AssertionError("No SecretSharing instances for you!"); } /** * Splits the given secret into {@code n} shares, of which any {@code k} or * more can be combined to recover the original secret. * * @param n the number of shares to produce (must be {@code >1}) * @param k the threshold of combinable shares (must be {@code <= n}) * @param secret the secret to split * @return a set of {@code n} {@link Share} instances */ public static Set<Share> split(int n, int k, byte[] secret) { Objects.requireNonNull(secret, "secret must not be null"); if (k <= 1) { throw new IllegalArgumentException("K must be > 1"); } if (n < k) { throw new IllegalArgumentException("N must be >= K"); } // generate shares final SecureRandom random = new SecureRandom(); final byte[][] shares = new byte[n][secret.length]; for (int i = 0; i < secret.length; i++) { // for each byte, generate a random polynomial, p final byte[] p = GF256.generate(random, k - 1, secret[i]); for (byte x = 1; x <= n; x++) { // each share's byte is p(shareId) shares[x - 1][i] = GF256.eval(p, x); } } // return as a set of objects return IntStream.range(0, n) .mapToObj(i -> new Share(i + 1, shares[i])) .collect(Collectors.toSet()); } /** * Combines the given shares into the original secret. * <p> * <b>N.B.:</b> There is no way to determine whether or not the returned * value is actually the original secret. If the shares are incorrect, or * are under the threshold value used to split the secret, a random value * will be returned. * * @param shares a set of {@link Share} instances * @return the original secret * @throws IllegalArgumentException if {@code shares} is empty or contains values of varying * lengths */ public static byte[] combine(Set<Share> shares) { Objects.requireNonNull(shares, "shares must not be null"); final int[] l = shares.stream().mapToInt(s -> s.value.length).distinct().toArray(); if (l.length == 0) { throw new IllegalArgumentException("No shares provided"); } if (l.length != 1) { throw new IllegalArgumentException("Varying lengths of share values"); } final byte[] secret = new byte[l[0]]; for (int i = 0; i < secret.length; i++) { final byte[][] points = new byte[shares.size()][2]; int p = 0; for (Share share : shares) { points[p][0] = (byte) share.id; points[p][1] = share.value[i]; p++; } secret[i] = GF256.interpolate(points); } return secret; } }
Extract method for checking share value lengths.
src/main/java/com/codahale/shamir/SecretSharing.java
Extract method for checking share value lengths.
<ide><path>rc/main/java/com/codahale/shamir/SecretSharing.java <ide> * lengths <ide> */ <ide> public static byte[] combine(Set<Share> shares) { <del> Objects.requireNonNull(shares, "shares must not be null"); <del> final int[] l = shares.stream().mapToInt(s -> s.value.length).distinct().toArray(); <del> if (l.length == 0) { <del> throw new IllegalArgumentException("No shares provided"); <del> } <del> if (l.length != 1) { <del> throw new IllegalArgumentException("Varying lengths of share values"); <del> } <del> <del> final byte[] secret = new byte[l[0]]; <add> final byte[] secret = new byte[secretLength(shares)]; <ide> for (int i = 0; i < secret.length; i++) { <ide> final byte[][] points = new byte[shares.size()][2]; <ide> int p = 0; <ide> } <ide> return secret; <ide> } <add> <add> private static int secretLength(Set<Share> shares) { <add> Objects.requireNonNull(shares, "Shares must not be null"); <add> final int[] l = shares.stream().mapToInt(s -> s.value.length).distinct().toArray(); <add> if (l.length == 0) { <add> throw new IllegalArgumentException("No shares provided"); <add> } <add> if (l.length != 1) { <add> throw new IllegalArgumentException("Varying lengths of share values"); <add> } <add> return l[0]; <add> } <ide> }
Java
apache-2.0
7387baa4a3e01854a8f0bf36bc167f68c981ba88
0
springrichclient/springrcp,springrichclient/springrcp,springrichclient/springrcp
/* * Copyright 2002-2004 the original author or authors. * * 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.springframework.richclient.dialog; import org.springframework.binding.value.PropertyChangePublisher; import org.springframework.richclient.core.Message; /** * An interface to be implemented by objects that are capable of receiving messages to be * provided to the user. * * @author Keith Donald */ public interface Messagable extends PropertyChangePublisher { /** The name of the message property, to be used for publishing update events. */ public static final String MESSAGE_PROPERTY = "message"; /** * Set the message. * @param The message. */ public void setMessage(Message message); }
support/src/main/java/org/springframework/richclient/dialog/Messagable.java
/* * Copyright 2002-2004 the original author or authors. * * 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.springframework.richclient.dialog; import org.springframework.binding.value.PropertyChangePublisher; import org.springframework.richclient.core.Message; /** * Interface to be implemented by object capable of receiving messages to the * user. * * @author Keith Donald */ public interface Messagable extends PropertyChangePublisher { public static final String MESSAGE_PROPERTY = "message"; /** * Set the message. */ public void setMessage(Message message); }
Added javadoc, no functional changes
support/src/main/java/org/springframework/richclient/dialog/Messagable.java
Added javadoc, no functional changes
<ide><path>upport/src/main/java/org/springframework/richclient/dialog/Messagable.java <ide> import org.springframework.richclient.core.Message; <ide> <ide> /** <del> * Interface to be implemented by object capable of receiving messages to the <del> * user. <add> * An interface to be implemented by objects that are capable of receiving messages to be <add> * provided to the user. <ide> * <ide> * @author Keith Donald <ide> */ <ide> public interface Messagable extends PropertyChangePublisher { <del> public static final String MESSAGE_PROPERTY = "message"; <add> <add> /** The name of the message property, to be used for publishing update events. */ <add> public static final String MESSAGE_PROPERTY = "message"; <ide> <ide> /** <ide> * Set the message. <add> * @param The message. <ide> */ <ide> public void setMessage(Message message); <ide>
Java
apache-2.0
98f66223144be20153e2a087aa11357e2130663b
0
sakaiproject/turnitin,sakaiproject/turnitin
/********************************************************************************** * $URL: https://source.sakaiproject.org/contrib/turnitin/trunk/contentreview-impl/impl/src/java/org/sakaiproject/contentreview/impl/turnitin/TurnitinReviewServiceImpl.java $ * $Id: TurnitinReviewServiceImpl.java 69345 2010-07-22 08:11:44Z [email protected] $ *********************************************************************************** * * Copyright (c) 2006 Sakai Foundation * * Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.contentreview.impl.turnitin; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.contentreview.service.ContentReviewService; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.exception.ServerOverloadException; /** * This class contains the implementation of * {@link ContentReviewService.isAcceptableContent}. This includes other * utility logic for checking the length and correctness of Word Documents and * other things. * * @author sgithens * */ public class TurnitinContentValidator { private static final Log log = LogFactory.getLog(TurnitinContentValidator.class); private int TII_MAX_FILE_SIZE; private ServerConfigurationService serverConfigurationService; public void setServerConfigurationService (ServerConfigurationService serverConfigurationService) { this.serverConfigurationService = serverConfigurationService; } public void init() { TII_MAX_FILE_SIZE = serverConfigurationService.getInt("turnitin.maxFileSize",10995116); } private boolean isMsWordDoc(ContentResource resource) { String mime = resource.getContentType(); log.debug("Got a content type of " + mime); if (mime.equals("application/msword")) { log.debug("FileType matches a known mime"); return true; } ResourceProperties resourceProperties = resource.getProperties(); String fileName = resourceProperties.getProperty(resourceProperties.getNamePropDisplayName()); if (fileName.contains(".")) { String extension = fileName.substring(fileName.lastIndexOf(".")); log.debug("file has an extension of " + extension); if (extension.equals(".doc") || extension.equals(".docx") || ".rtf".equals(extension)) { return true; } } else { //if the file has no extension we assume its a doc return true; } return false; } private int wordDocLength(ContentResource resource) { if (!serverConfigurationService.getBoolean("tii.checkWordLength", false)) return 100; try { POIFSFileSystem pfs = new POIFSFileSystem(resource.streamContent()); HWPFDocument doc = new HWPFDocument(pfs); SummaryInformation dsi = doc.getSummaryInformation(); int count = dsi.getWordCount(); log.debug("got a count of " + count); //if this == 0 then its likely that something went wrong -poi couldn't read it if (count == 0) return 100; return count; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServerOverloadException e) { // TODO Auto-generated catch block e.printStackTrace(); } //in case we can't read this lets err on the side of caution return 100; } public boolean isAcceptableContent(ContentResource resource) { //for now we accept all content // TODO: Check against content types accepted by Turnitin /* * Turnitin currently accepts the following file types for submission: MS Word (.doc), WordPerfect (.wpd), PostScript (.eps), Portable Document Format (.pdf), HTML (.htm), Rich Text (.rtf) and Plain Text (.txt) * text/plain * text/html * application/msword * application/msword * application/postscript */ String mime = resource.getContentType(); log.debug("Got a content type of " + mime); Boolean fileTypeOk = false; if ((mime.equals("text/plain") || mime.equals("text/html") || mime.equals("application/msword") || mime.equals("application/postscript") || mime.equals("application/pdf") || mime.equals("text/rtf")) ) { fileTypeOk = true; log.debug("FileType matches a known mime"); } //as mime's can be tricky check the extensions if (!fileTypeOk) { ResourceProperties resourceProperties = resource.getProperties(); String fileName = resourceProperties.getProperty(resourceProperties.getNamePropDisplayName()); if (fileName.indexOf(".")>0) { String extension = fileName.substring(fileName.lastIndexOf(".")); log.debug("file has an extension of " + extension); if (extension.equals(".doc") || extension.equals(".wpd") || extension.equals(".eps") || extension.equals(".txt") || extension.equals(".htm") || extension.equals(".html") || extension.equals(".pdf") || extension.equals(".docx") || ".rtf".equals(extension)) fileTypeOk = true; } else { //we don't know what this is so lets submit it anyway fileTypeOk = true; } } if (!fileTypeOk) { return false; } //TODO: if file is too big reject here 10.48576 MB if (resource.getContentLength() > TII_MAX_FILE_SIZE) { log.debug("File is too big: " + resource.getContentLength()); return false; } //TII-93 content length must be > o if (resource.getContentLength() == 0) { log.debug("File is Ob"); return false; } //if this is a msword type file we can check the legth if (isMsWordDoc(resource)) { if (wordDocLength(resource) < 20) { return false; } } return true; } }
contentreview-impl/impl/src/java/org/sakaiproject/contentreview/impl/turnitin/TurnitinContentValidator.java
/********************************************************************************** * $URL: https://source.sakaiproject.org/contrib/turnitin/trunk/contentreview-impl/impl/src/java/org/sakaiproject/contentreview/impl/turnitin/TurnitinReviewServiceImpl.java $ * $Id: TurnitinReviewServiceImpl.java 69345 2010-07-22 08:11:44Z [email protected] $ *********************************************************************************** * * Copyright (c) 2006 Sakai Foundation * * Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.contentreview.impl.turnitin; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.contentreview.service.ContentReviewService; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.exception.ServerOverloadException; /** * This class contains the implementation of * {@link ContentReviewService.isAcceptableContent}. This includes other * utility logic for checking the length and correctness of Word Documents and * other things. * * @author sgithens * */ public class TurnitinContentValidator { private static final Log log = LogFactory.getLog(TurnitinContentValidator.class); private int TII_MAX_FILE_SIZE; private ServerConfigurationService serverConfigurationService; public void setServerConfigurationService (ServerConfigurationService serverConfigurationService) { this.serverConfigurationService = serverConfigurationService; } public void init() { TII_MAX_FILE_SIZE = serverConfigurationService.getInt("turnitin.maxFileSize",10995116); } private boolean isMsWordDoc(ContentResource resource) { String mime = resource.getContentType(); log.debug("Got a content type of " + mime); if (mime.equals("application/msword")) { log.debug("FileType matches a known mime"); return true; } ResourceProperties resourceProperties = resource.getProperties(); String fileName = resourceProperties.getProperty(resourceProperties.getNamePropDisplayName()); if (fileName.contains(".")) { String extension = fileName.substring(fileName.lastIndexOf(".")); log.debug("file has an extension of " + extension); if (extension.equals(".doc") || extension.equals(".docx") || ".rtf".equals(extension)) { return true; } } else { //if the file has no extension we assume its a doc return true; } return false; } private int wordDocLength(ContentResource resource) { if (!serverConfigurationService.getBoolean("tii.checkWordLength", false)) return 100; try { POIFSFileSystem pfs = new POIFSFileSystem(resource.streamContent()); HWPFDocument doc = new HWPFDocument(pfs); SummaryInformation dsi = doc.getSummaryInformation(); int count = dsi.getWordCount(); log.debug("got a count of " + count); //if this == 0 then its likely that something went wrong -poi couldn't read it if (count == 0) return 100; return count; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServerOverloadException e) { // TODO Auto-generated catch block e.printStackTrace(); } //in case we can't read this lets err on the side of caution return 100; } public boolean isAcceptableContent(ContentResource resource) { //for now we accept all content // TODO: Check against content types accepted by Turnitin /* * Turnitin currently accepts the following file types for submission: MS Word (.doc), WordPerfect (.wpd), PostScript (.eps), Portable Document Format (.pdf), HTML (.htm), Rich Text (.rtf) and Plain Text (.txt) * text/plain * text/html * application/msword * application/msword * application/postscript */ String mime = resource.getContentType(); log.debug("Got a content type of " + mime); Boolean fileTypeOk = false; if ((mime.equals("text/plain") || mime.equals("text/html") || mime.equals("application/msword") || mime.equals("application/postscript") || mime.equals("application/pdf") || mime.equals("text/rtf")) ) { fileTypeOk = true; log.debug("FileType matches a known mime"); } //as mime's can be tricky check the extensions if (!fileTypeOk) { ResourceProperties resourceProperties = resource.getProperties(); String fileName = resourceProperties.getProperty(resourceProperties.getNamePropDisplayName()); if (fileName.indexOf(".")>0) { String extension = fileName.substring(fileName.lastIndexOf(".")); log.debug("file has an extension of " + extension); if (extension.equals(".doc") || extension.equals(".wpd") || extension.equals(".eps") || extension.equals(".txt") || extension.equals(".htm") || extension.equals(".html") || extension.equals(".pdf") || extension.equals(".docx") || ".rtf".equals(extension)) fileTypeOk = true; } else { //we don't know what this is so lets submit it anyway fileTypeOk = true; } } if (!fileTypeOk) { return false; } //TODO: if file is too big reject here 10.48576 MB if (resource.getContentLength() > TII_MAX_FILE_SIZE) { log.debug("File is too big: " + resource.getContentLength()); return false; } //if this is a msword type file we can check the legth if (isMsWordDoc(resource)) { if (wordDocLength(resource) < 20) { return false; } } return true; } }
TII-93 don't accept 0 lenght files git-svn-id: 4e8da3c7dac66920e663ced6f23cd9ae43b37078@69792 fdecad78-55fc-0310-b1b2-d7d25cf747c9
contentreview-impl/impl/src/java/org/sakaiproject/contentreview/impl/turnitin/TurnitinContentValidator.java
TII-93 don't accept 0 lenght files
<ide><path>ontentreview-impl/impl/src/java/org/sakaiproject/contentreview/impl/turnitin/TurnitinContentValidator.java <ide> return false; <ide> } <ide> <add> //TII-93 content length must be > o <add> if (resource.getContentLength() == 0) { <add> log.debug("File is Ob"); <add> return false; <add> } <add> <ide> //if this is a msword type file we can check the legth <ide> if (isMsWordDoc(resource)) { <ide> if (wordDocLength(resource) < 20) {
Java
apache-2.0
de7689bd5724d5c9f567925f377afa48c43a62da
0
bentrm/camunda-bpm-platform,camunda/camunda-bpm-platform,tcrossland/camunda-bpm-platform,xasx/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,langfr/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,tcrossland/camunda-bpm-platform,xasx/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,Sumitdahiya/camunda,holisticon/camunda-bpm-platform,Sumitdahiya/camunda,fouasnon/camunda-bpm-platform,fouasnon/camunda-bpm-platform,langfr/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,tcrossland/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,joansmith/camunda-bpm-platform,falko/camunda-bpm-platform,jangalinski/camunda-bpm-platform,filiphr/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,subhrajyotim/camunda-bpm-platform,camunda/camunda-bpm-platform,Sumitdahiya/camunda,xasx/camunda-bpm-platform,camunda/camunda-bpm-platform,filiphr/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,langfr/camunda-bpm-platform,nibin/camunda-bpm-platform,nibin/camunda-bpm-platform,camunda/camunda-bpm-platform,xasx/camunda-bpm-platform,camunda/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,bentrm/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,tcrossland/camunda-bpm-platform,filiphr/camunda-bpm-platform,skjolber/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,bentrm/camunda-bpm-platform,tcrossland/camunda-bpm-platform,jangalinski/camunda-bpm-platform,jangalinski/camunda-bpm-platform,rainerh/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,rainerh/camunda-bpm-platform,filiphr/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,LuisePufahl/camunda-bpm-platform_batchProcessing,bentrm/camunda-bpm-platform,joansmith/camunda-bpm-platform,plexiti/camunda-bpm-platform,nibin/camunda-bpm-platform,falko/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,subhrajyotim/camunda-bpm-platform,rainerh/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,falko/camunda-bpm-platform,langfr/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,langfr/camunda-bpm-platform,hupda-edpe/c,joansmith/camunda-bpm-platform,xasx/camunda-bpm-platform,Sumitdahiya/camunda,nibin/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,Sumitdahiya/camunda,langfr/camunda-bpm-platform,fouasnon/camunda-bpm-platform,holisticon/camunda-bpm-platform,skjolber/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,camunda/camunda-bpm-platform,rainerh/camunda-bpm-platform,hupda-edpe/c,AlexMinsk/camunda-bpm-platform,nibin/camunda-bpm-platform,falko/camunda-bpm-platform,joansmith/camunda-bpm-platform,filiphr/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,jangalinski/camunda-bpm-platform,bentrm/camunda-bpm-platform,plexiti/camunda-bpm-platform,skjolber/camunda-bpm-platform,holisticon/camunda-bpm-platform,plexiti/camunda-bpm-platform,filiphr/camunda-bpm-platform,Sumitdahiya/camunda,hawky-4s-/camunda-bpm-platform,fouasnon/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,hupda-edpe/c,joansmith/camunda-bpm-platform,plexiti/camunda-bpm-platform,rainerh/camunda-bpm-platform,rainerh/camunda-bpm-platform,jangalinski/camunda-bpm-platform,holisticon/camunda-bpm-platform,tcrossland/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,hupda-edpe/c,falko/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,plexiti/camunda-bpm-platform,fouasnon/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,plexiti/camunda-bpm-platform,jangalinski/camunda-bpm-platform,xasx/camunda-bpm-platform,hupda-edpe/c,AlexMinsk/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,joansmith/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,nibin/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,skjolber/camunda-bpm-platform,holisticon/camunda-bpm-platform,bentrm/camunda-bpm-platform,skjolber/camunda-bpm-platform,fouasnon/camunda-bpm-platform,hupda-edpe/c,skjolber/camunda-bpm-platform,falko/camunda-bpm-platform,holisticon/camunda-bpm-platform,nagyistoce/camunda-bpm-platform
/* 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.camunda.bpm.engine.test.bpmn.iomapping; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.delegate.BpmnError; import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; import org.camunda.bpm.engine.runtime.Execution; import org.camunda.bpm.engine.runtime.Job; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.runtime.VariableInstance; import org.camunda.bpm.engine.task.Task; import org.camunda.bpm.engine.test.Deployment; /** * Testcase for camunda input / output in BPMN * * @author Daniel Meyer * */ public class InputOutputTest extends PluggableProcessEngineTestCase { // Input parameters ///////////////////////////////////////// @Deployment public void testInputNullValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals("null", variable.getTypeName()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputStringConstantValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals("stringValue", variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputElValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2l, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputScriptValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptSource", "return 1 + 1"); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputExternalScriptValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputExternalScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptPath", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy"); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputExternalScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputExternalClasspathScriptValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputExternalClasspathScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptPath", "classpath://org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy"); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputExternalClasspathScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment(resources = { "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testInputExternalDeploymentScriptValue.bpmn", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy" }) public void testInputExternalDeploymentScriptValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment(resources = { "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testInputExternalDeploymentScriptValueAsVariable.bpmn", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy" }) public void testInputExternalDeploymentScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptPath", "deployment://org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy"); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment(resources = { "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testInputExternalDeploymentScriptValueAsBean.bpmn", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy" }) public void testInputExternalDeploymentScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment @SuppressWarnings("unchecked") public void testInputListElValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); List<Object> value = (List<Object>) variable.getValue(); assertEquals(2l, value.get(0)); assertEquals(3l, value.get(1)); assertEquals(4l, value.get(2)); } @Deployment @SuppressWarnings("unchecked") public void testInputListMixedValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); List<Object> value = (List<Object>) variable.getValue(); assertEquals("constantStringValue", value.get(0)); assertEquals("elValue", value.get(1)); assertEquals("scriptValue", value.get(2)); } @Deployment @SuppressWarnings("unchecked") public void testInputMapElValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); TreeMap<String, Object> value = (TreeMap) variable.getValue(); assertEquals(2l, value.get("a")); assertEquals(3l, value.get("b")); assertEquals(4l, value.get("c")); } @Deployment public void testInputMultipleElValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance var1 = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(var1); assertEquals(2l, var1.getValue()); assertEquals(execution.getId(), var1.getExecutionId()); VariableInstance var2 = runtimeService.createVariableInstanceQuery().variableName("var2").singleResult(); assertNotNull(var2); assertEquals(3l, var2.getValue()); assertEquals(execution.getId(), var2.getExecutionId()); } @Deployment public void testInputMultipleMixedValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance var1 = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(var1); assertEquals(2l, var1.getValue()); assertEquals(execution.getId(), var1.getExecutionId()); VariableInstance var2 = runtimeService.createVariableInstanceQuery().variableName("var2").singleResult(); assertNotNull(var2); assertEquals("stringConstantValue", var2.getValue()); assertEquals(execution.getId(), var2.getExecutionId()); } @Deployment @SuppressWarnings("unchecked") public void testInputNested() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance var1 = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); TreeMap<String, Object> value = (TreeMap) var1.getValue(); List<Object> nestedList = (List<Object>) value.get("a"); assertEquals("stringInListNestedInMap", nestedList.get(0)); assertEquals("b", nestedList.get(1)); VariableInstance var2 = runtimeService.createVariableInstanceQuery().variableName("var2").singleResult(); assertNotNull(var2); assertEquals("stringConstantValue", var2.getValue()); assertEquals(execution.getId(), var2.getExecutionId()); } @Deployment @SuppressWarnings("unchecked") public void testInputNestedListValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); List<Object> value = (List<Object>) variable.getValue(); assertEquals("constantStringValue", value.get(0)); assertEquals("elValue", value.get(1)); assertEquals("scriptValue", value.get(2)); List<Object> nestedList = (List<Object>) value.get(3); List<Object> nestedNestedList = (List<Object>) nestedList.get(0); assertEquals("a", nestedNestedList.get(0)); assertEquals("b", nestedNestedList.get(1)); assertEquals("c", nestedNestedList.get(2)); assertEquals("d", nestedList.get(1)); TreeMap<String, Object> nestedMap = (TreeMap<String, Object>) value.get(4); assertEquals("bar", nestedMap.get("foo")); assertEquals("world", nestedMap.get("hello")); } // output parameter /////////////////////////////////////////////////////// @Deployment public void testOutputNullValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals("null", variable.getTypeName()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputStringConstantValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals("stringValue", variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputElValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2l, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputScriptValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptSource", "return 1 + 1"); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputExternalScriptValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputExternalScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptPath", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy"); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputExternalScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputExternalClasspathScriptValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputExternalClasspathScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptPath", "classpath://org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy"); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputExternalClasspathScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment(resources = { "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testOutputExternalDeploymentScriptValue.bpmn", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy" }) public void testOutputExternalDeploymentScriptValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment(resources = { "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testOutputExternalDeploymentScriptValueAsVariable.bpmn", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy" }) public void testOutputExternalDeploymentScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptPath", "deployment://org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy"); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment(resources = { "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testOutputExternalDeploymentScriptValueAsBean.bpmn", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy" }) public void testOutputExternalDeploymentScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment @SuppressWarnings("unchecked") public void testOutputListElValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); List<Object> value = (List<Object>) variable.getValue(); assertEquals(2l, value.get(0)); assertEquals(3l, value.get(1)); assertEquals(4l, value.get(2)); } @Deployment @SuppressWarnings("unchecked") public void testOutputListMixedValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); List<Object> value = (List<Object>) variable.getValue(); assertEquals("constantStringValue", value.get(0)); assertEquals("elValue", value.get(1)); assertEquals("scriptValue", value.get(2)); } @Deployment @SuppressWarnings("unchecked") public void testOutputMapElValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); TreeMap<String, Object> value = (TreeMap) variable.getValue(); assertEquals(2l, value.get("a")); assertEquals(3l, value.get("b")); assertEquals(4l, value.get("c")); } @Deployment public void testOutputMultipleElValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance var1 = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(var1); assertEquals(2l, var1.getValue()); assertEquals(pi.getId(), var1.getExecutionId()); VariableInstance var2 = runtimeService.createVariableInstanceQuery().variableName("var2").singleResult(); assertNotNull(var2); assertEquals(3l, var2.getValue()); assertEquals(pi.getId(), var2.getExecutionId()); } @Deployment public void testOutputMultipleMixedValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance var1 = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(var1); assertEquals(2l, var1.getValue()); assertEquals(pi.getId(), var1.getExecutionId()); VariableInstance var2 = runtimeService.createVariableInstanceQuery().variableName("var2").singleResult(); assertNotNull(var2); assertEquals("stringConstantValue", var2.getValue()); assertEquals(pi.getId(), var2.getExecutionId()); } @Deployment @SuppressWarnings("unchecked") public void testOutputNested() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance var1 = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); TreeMap<String, Object> value = (TreeMap) var1.getValue(); List<Object> nestedList = (List<Object>) value.get("a"); assertEquals("stringInListNestedInMap", nestedList.get(0)); assertEquals("b", nestedList.get(1)); assertEquals(pi.getId(), var1.getExecutionId()); VariableInstance var2 = runtimeService.createVariableInstanceQuery().variableName("var2").singleResult(); assertNotNull(var2); assertEquals("stringConstantValue", var2.getValue()); assertEquals(pi.getId(), var2.getExecutionId()); } @Deployment @SuppressWarnings("unchecked") public void testOutputListNestedValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); List<Object> value = (List<Object>) variable.getValue(); assertEquals("constantStringValue", value.get(0)); assertEquals("elValue", value.get(1)); assertEquals("scriptValue", value.get(2)); List<Object> nestedList = (List<Object>) value.get(3); List<Object> nestedNestedList = (List<Object>) nestedList.get(0); assertEquals("a", nestedNestedList.get(0)); assertEquals("b", nestedNestedList.get(1)); assertEquals("c", nestedNestedList.get(2)); assertEquals("d", nestedList.get(1)); TreeMap<String, Object> nestedMap = (TreeMap<String, Object>) value.get(4); assertEquals("bar", nestedMap.get("foo")); assertEquals("world", nestedMap.get("hello")); } // ensure Io supported on event subprocess ///////////////////////////////// public void testInterruptingEventSubprocessIoSupport() { try { repositoryService .createDeployment() .addClasspathResource("org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testInterruptingEventSubprocessIoSupport.bpmn") .deploy(); fail("exception expected"); } catch (ProcessEngineException e) { // happy path assertTextPresent("camunda:inputOutput mapping unsupported for element type 'subProcess' with attribute 'triggeredByEvent = true'", e.getMessage()); } } @Deployment public void testSubprocessIoSupport() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("processVar", "value"); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testProcess", variables); Execution subprocessExecution = runtimeService.createExecutionQuery().activityId("subprocessTask").singleResult(); Map<String, Object> variablesLocal = runtimeService.getVariablesLocal(subprocessExecution.getId()); assertEquals(1, variablesLocal.size()); assertEquals("value", variablesLocal.get("innerVar")); Task task = taskService.createTaskQuery().singleResult(); taskService.complete(task.getId()); String outerVariable = (String) runtimeService.getVariableLocal(processInstance.getId(), "outerVar"); assertNotNull(outerVariable); assertEquals("value", outerVariable); } @Deployment public void testSequentialMIActivityIoSupport() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("counter", new AtomicInteger()); variables.put("nrOfLoops", 2); ProcessInstance instance = runtimeService.startProcessInstanceByKey("miSequentialActivity", variables); // first sequential mi execution Execution miExecution = runtimeService.createExecutionQuery().activityId("miTask").singleResult(); assertNotNull(miExecution); assertFalse(instance.getId().equals(miExecution.getId())); assertEquals(0, runtimeService.getVariable(miExecution.getId(), "loopCounter")); // input mapping assertEquals(1, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); assertEquals(1, runtimeService.getVariableLocal(miExecution.getId(), "miCounterValue")); Task task = taskService.createTaskQuery().singleResult(); taskService.complete(task.getId()); // second sequential mi execution miExecution = runtimeService.createExecutionQuery().activityId("miTask").singleResult(); assertNotNull(miExecution); assertFalse(instance.getId().equals(miExecution.getId())); assertEquals(1, runtimeService.getVariable(miExecution.getId(), "loopCounter")); // input mapping assertEquals(1, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); assertEquals(2, runtimeService.getVariableLocal(miExecution.getId(), "miCounterValue")); task = taskService.createTaskQuery().singleResult(); taskService.complete(task.getId()); // variable does not exist outside of scope assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); } @Deployment public void testSequentialMISubprocessIoSupport() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("counter", new AtomicInteger()); variables.put("nrOfLoops", 2); ProcessInstance instance = runtimeService.startProcessInstanceByKey("miSequentialSubprocess", variables); // first sequential mi execution Execution miScopeExecution = runtimeService.createExecutionQuery().activityId("task").singleResult(); assertNotNull(miScopeExecution); assertEquals(0, runtimeService.getVariable(miScopeExecution.getId(), "loopCounter")); // input mapping assertEquals(1, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); assertEquals(1, runtimeService.getVariableLocal(miScopeExecution.getId(), "miCounterValue")); Task task = taskService.createTaskQuery().singleResult(); taskService.complete(task.getId()); // second sequential mi execution miScopeExecution = runtimeService.createExecutionQuery().activityId("task").singleResult(); assertNotNull(miScopeExecution); assertFalse(instance.getId().equals(miScopeExecution.getId())); assertEquals(1, runtimeService.getVariable(miScopeExecution.getId(), "loopCounter")); // input mapping assertEquals(1, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); assertEquals(2, runtimeService.getVariableLocal(miScopeExecution.getId(), "miCounterValue")); task = taskService.createTaskQuery().singleResult(); taskService.complete(task.getId()); // variable does not exist outside of scope assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); } @Deployment public void testParallelMIActivityIoSupport() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("counter", new AtomicInteger()); variables.put("nrOfLoops", 2); ProcessInstance instance = runtimeService.startProcessInstanceByKey("miParallelActivity", variables); // first mi execution Execution miExecution1 = runtimeService.createExecutionQuery().activityId("miTask") .variableValueEquals("loopCounter", 0).singleResult(); assertNotNull(miExecution1); assertFalse(instance.getId().equals(miExecution1.getId())); assertEquals(1, runtimeService.getVariableLocal(miExecution1.getId(), "miCounterValue")); // second mi execution Execution miExecution2 = runtimeService.createExecutionQuery().activityId("miTask") .variableValueEquals("loopCounter", 1).singleResult(); assertNotNull(miExecution2); assertFalse(instance.getId().equals(miExecution2.getId())); assertEquals(2, runtimeService.getVariableLocal(miExecution2.getId(), "miCounterValue")); assertEquals(2, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); for (Task task : taskService.createTaskQuery().list()) { taskService.complete(task.getId()); } // variable does not exist outside of scope assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); } @Deployment public void testParallelMISubprocessIoSupport() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("counter", new AtomicInteger()); variables.put("nrOfLoops", 2); ProcessInstance instance = runtimeService.startProcessInstanceByKey("miParallelSubprocess", variables); // first parallel mi execution Execution miScopeExecution1 = runtimeService.createExecutionQuery().activityId("task") .variableValueEquals("loopCounter", 0).singleResult(); assertNotNull(miScopeExecution1); assertEquals(1, runtimeService.getVariableLocal(miScopeExecution1.getId(), "miCounterValue")); // second parallel mi execution Execution miScopeExecution2 = runtimeService.createExecutionQuery().activityId("task") .variableValueEquals("loopCounter", 1).singleResult(); assertNotNull(miScopeExecution2); assertFalse(instance.getId().equals(miScopeExecution2.getId())); assertEquals(2, runtimeService.getVariableLocal(miScopeExecution2.getId(), "miCounterValue")); assertEquals(2, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); for (Task task : taskService.createTaskQuery().list()) { taskService.complete(task.getId()); } // variable does not exist outside of scope assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); } public void testMIOutputMappingDisallowed() { try { repositoryService.createDeployment() .addClasspathResource("org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testMIOutputMappingDisallowed.bpmn20.xml") .deploy(); fail("Exception expected"); } catch (ProcessEngineException e) { assertTextPresent("camunda:outputParameter not allowed for multi-instance constructs", e.getMessage()); } } @Deployment(resources = "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testThrowErrorInScriptInputOutputMapping.bpmn") public void FAILING_testBpmnErrorInScriptInputMapping() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("throwInMapping", "in"); variables.put("exception", new BpmnError("error")); runtimeService.startProcessInstanceByKey("testProcess", variables); //we will only reach the user task if the BPMNError from the script was handled by the boundary event Task task = taskService.createTaskQuery().singleResult(); assertThat(task.getName(), is("User Task")); } @Deployment(resources = "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testThrowErrorInScriptInputOutputMapping.bpmn") public void testExceptionInScriptInputMapping() { String exceptionMessage = "myException"; Map<String, Object> variables = new HashMap<String, Object>(); variables.put("throwInMapping", "in"); variables.put("exception", new RuntimeException(exceptionMessage)); try { runtimeService.startProcessInstanceByKey("testProcess", variables); } catch(RuntimeException re){ assertThat(re.getMessage(), containsString(exceptionMessage)); } } @Deployment(resources = "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testThrowErrorInScriptInputOutputMapping.bpmn") public void FAILING_testBpmnErrorInScriptOutputMapping() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("throwInMapping", "out"); variables.put("exception", new BpmnError("error")); runtimeService.startProcessInstanceByKey("testProcess", variables); //we will only reach the user task if the BPMNError from the script was handled by the boundary event Task task = taskService.createTaskQuery().singleResult(); assertThat(task.getName(), is("User Task")); } @Deployment(resources = "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testThrowErrorInScriptInputOutputMapping.bpmn") public void testExceptionInScriptOutputMapping() { String exceptionMessage = "myException"; Map<String, Object> variables = new HashMap<String, Object>(); variables.put("throwInMapping", "out"); variables.put("exception", new RuntimeException(exceptionMessage)); try { runtimeService.startProcessInstanceByKey("testProcess", variables); } catch(RuntimeException re){ assertThat(re.getMessage(), containsString(exceptionMessage)); } } @Deployment public void FAILING_testOutputMappingOnErrorBoundaryEvent() { // case 1: no error occurs runtimeService.startProcessInstanceByKey("testProcess"); Task task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("taskOk", task.getTaskDefinitionKey()); // then: variable mapped exists assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("localNotMapped").count()); assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("localMapped").count()); assertEquals(1, runtimeService.createVariableInstanceQuery().variableName("mapped").count()); taskService.complete(task.getId()); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); // case 2: error occurs runtimeService.startProcessInstanceByKey("testProcess", Collections.<String, Object>singletonMap("throwError", true)); task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("taskError", task.getTaskDefinitionKey()); assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("localNotMapped").count()); assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("localMapped").count()); assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("mapped").count()); taskService.complete(task.getId()); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); } @Deployment public void FAILING_testOutputMappingOnMessageBoundaryEvent() { // case 1: no error occurs runtimeService.startProcessInstanceByKey("testProcess"); Task task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("wait", task.getTaskDefinitionKey()); taskService.complete(task.getId()); task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("taskOk", task.getTaskDefinitionKey()); // then: variable mapped exists assertEquals(1, runtimeService.createVariableInstanceQuery().variableName("mapped").count()); taskService.complete(task.getId()); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); // case 2: error occurs runtimeService.startProcessInstanceByKey("testProcess", Collections.<String, Object>singletonMap("throwError", true)); task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("wait", task.getTaskDefinitionKey()); runtimeService.correlateMessage("message"); task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("taskError", task.getTaskDefinitionKey()); assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("mapped").count()); taskService.complete(task.getId()); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); } @Deployment public void FAILING_testOutputMappingOnTimerBoundaryEvent() { // case 1: no error occurs runtimeService.startProcessInstanceByKey("testProcess"); Task task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("wait", task.getTaskDefinitionKey()); taskService.complete(task.getId()); task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("taskOk", task.getTaskDefinitionKey()); // then: variable mapped exists assertEquals(1, runtimeService.createVariableInstanceQuery().variableName("mapped").count()); taskService.complete(task.getId()); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); // case 2: error occurs runtimeService.startProcessInstanceByKey("testProcess", Collections.<String, Object>singletonMap("throwError", true)); task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("wait", task.getTaskDefinitionKey()); Job job = managementService.createJobQuery().singleResult(); assertNotNull(job); managementService.executeJob(job.getId()); task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("taskError", task.getTaskDefinitionKey()); assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("mapped").count()); taskService.complete(task.getId()); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); } }
engine/src/test/java/org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.java
/* 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.camunda.bpm.engine.test.bpmn.iomapping; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.delegate.BpmnError; import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; import org.camunda.bpm.engine.runtime.Execution; import org.camunda.bpm.engine.runtime.Job; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.runtime.VariableInstance; import org.camunda.bpm.engine.task.Task; import org.camunda.bpm.engine.test.Deployment; /** * Testcase for camunda input / output in BPMN * * @author Daniel Meyer * */ public class InputOutputTest extends PluggableProcessEngineTestCase { // Input parameters ///////////////////////////////////////// @Deployment public void testInputNullValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals("null", variable.getTypeName()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputStringConstantValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals("stringValue", variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputElValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2l, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputScriptValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptSource", "return 1 + 1"); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputExternalScriptValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputExternalScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptPath", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy"); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputExternalScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputExternalClasspathScriptValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputExternalClasspathScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptPath", "classpath://org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy"); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment public void testInputExternalClasspathScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment(resources = { "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testInputExternalDeploymentScriptValue.bpmn", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy" }) public void testInputExternalDeploymentScriptValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment(resources = { "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testInputExternalDeploymentScriptValueAsVariable.bpmn", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy" }) public void testInputExternalDeploymentScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptPath", "deployment://org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy"); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment(resources = { "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testInputExternalDeploymentScriptValueAsBean.bpmn", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy" }) public void testInputExternalDeploymentScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); runtimeService.startProcessInstanceByKey("testProcess", variables); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(execution.getId(), variable.getExecutionId()); } @Deployment @SuppressWarnings("unchecked") public void testInputListElValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); List<Object> value = (List<Object>) variable.getValue(); assertEquals(2l, value.get(0)); assertEquals(3l, value.get(1)); assertEquals(4l, value.get(2)); } @Deployment @SuppressWarnings("unchecked") public void testInputListMixedValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); List<Object> value = (List<Object>) variable.getValue(); assertEquals("constantStringValue", value.get(0)); assertEquals("elValue", value.get(1)); assertEquals("scriptValue", value.get(2)); } @Deployment @SuppressWarnings("unchecked") public void testInputMapElValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); TreeMap<String, Object> value = (TreeMap) variable.getValue(); assertEquals(2l, value.get("a")); assertEquals(3l, value.get("b")); assertEquals(4l, value.get("c")); } @Deployment public void testInputMultipleElValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance var1 = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(var1); assertEquals(2l, var1.getValue()); assertEquals(execution.getId(), var1.getExecutionId()); VariableInstance var2 = runtimeService.createVariableInstanceQuery().variableName("var2").singleResult(); assertNotNull(var2); assertEquals(3l, var2.getValue()); assertEquals(execution.getId(), var2.getExecutionId()); } @Deployment public void testInputMultipleMixedValue() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance var1 = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(var1); assertEquals(2l, var1.getValue()); assertEquals(execution.getId(), var1.getExecutionId()); VariableInstance var2 = runtimeService.createVariableInstanceQuery().variableName("var2").singleResult(); assertNotNull(var2); assertEquals("stringConstantValue", var2.getValue()); assertEquals(execution.getId(), var2.getExecutionId()); } @Deployment @SuppressWarnings("unchecked") public void testInputNested() { runtimeService.startProcessInstanceByKey("testProcess"); Execution execution = runtimeService.createExecutionQuery().activityId("wait").singleResult(); VariableInstance var1 = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); TreeMap<String, Object> value = (TreeMap) var1.getValue(); List<Object> nestedList = (List<Object>) value.get("a"); assertEquals("stringInListNestedInMap", nestedList.get(0)); assertEquals("b", nestedList.get(1)); VariableInstance var2 = runtimeService.createVariableInstanceQuery().variableName("var2").singleResult(); assertNotNull(var2); assertEquals("stringConstantValue", var2.getValue()); assertEquals(execution.getId(), var2.getExecutionId()); } @Deployment @SuppressWarnings("unchecked") public void testInputNestedListValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); List<Object> value = (List<Object>) variable.getValue(); assertEquals("constantStringValue", value.get(0)); assertEquals("elValue", value.get(1)); assertEquals("scriptValue", value.get(2)); List<Object> nestedList = (List<Object>) value.get(3); List<Object> nestedNestedList = (List<Object>) nestedList.get(0); assertEquals("a", nestedNestedList.get(0)); assertEquals("b", nestedNestedList.get(1)); assertEquals("c", nestedNestedList.get(2)); assertEquals("d", nestedList.get(1)); TreeMap<String, Object> nestedMap = (TreeMap<String, Object>) value.get(4); assertEquals("bar", nestedMap.get("foo")); assertEquals("world", nestedMap.get("hello")); } // output parameter /////////////////////////////////////////////////////// @Deployment public void testOutputNullValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals("null", variable.getTypeName()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputStringConstantValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals("stringValue", variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputElValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2l, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputScriptValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptSource", "return 1 + 1"); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputExternalScriptValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputExternalScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptPath", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy"); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputExternalScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputExternalClasspathScriptValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputExternalClasspathScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptPath", "classpath://org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy"); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment public void testOutputExternalClasspathScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment(resources = { "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testOutputExternalDeploymentScriptValue.bpmn", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy" }) public void testOutputExternalDeploymentScriptValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment(resources = { "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testOutputExternalDeploymentScriptValueAsVariable.bpmn", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy" }) public void testOutputExternalDeploymentScriptValueAsVariable() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("scriptPath", "deployment://org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy"); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment(resources = { "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testOutputExternalDeploymentScriptValueAsBean.bpmn", "org/camunda/bpm/engine/test/bpmn/iomapping/oneplusone.groovy" }) public void testOutputExternalDeploymentScriptValueAsBean() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("onePlusOneBean", new OnePlusOneBean()); ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); assertEquals(2, variable.getValue()); assertEquals(pi.getId(), variable.getExecutionId()); } @Deployment @SuppressWarnings("unchecked") public void testOutputListElValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); List<Object> value = (List<Object>) variable.getValue(); assertEquals(2l, value.get(0)); assertEquals(3l, value.get(1)); assertEquals(4l, value.get(2)); } @Deployment @SuppressWarnings("unchecked") public void testOutputListMixedValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); List<Object> value = (List<Object>) variable.getValue(); assertEquals("constantStringValue", value.get(0)); assertEquals("elValue", value.get(1)); assertEquals("scriptValue", value.get(2)); } @Deployment @SuppressWarnings("unchecked") public void testOutputMapElValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); TreeMap<String, Object> value = (TreeMap) variable.getValue(); assertEquals(2l, value.get("a")); assertEquals(3l, value.get("b")); assertEquals(4l, value.get("c")); } @Deployment public void testOutputMultipleElValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance var1 = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(var1); assertEquals(2l, var1.getValue()); assertEquals(pi.getId(), var1.getExecutionId()); VariableInstance var2 = runtimeService.createVariableInstanceQuery().variableName("var2").singleResult(); assertNotNull(var2); assertEquals(3l, var2.getValue()); assertEquals(pi.getId(), var2.getExecutionId()); } @Deployment public void testOutputMultipleMixedValue() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance var1 = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(var1); assertEquals(2l, var1.getValue()); assertEquals(pi.getId(), var1.getExecutionId()); VariableInstance var2 = runtimeService.createVariableInstanceQuery().variableName("var2").singleResult(); assertNotNull(var2); assertEquals("stringConstantValue", var2.getValue()); assertEquals(pi.getId(), var2.getExecutionId()); } @Deployment @SuppressWarnings("unchecked") public void testOutputNested() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance var1 = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); TreeMap<String, Object> value = (TreeMap) var1.getValue(); List<Object> nestedList = (List<Object>) value.get("a"); assertEquals("stringInListNestedInMap", nestedList.get(0)); assertEquals("b", nestedList.get(1)); assertEquals(pi.getId(), var1.getExecutionId()); VariableInstance var2 = runtimeService.createVariableInstanceQuery().variableName("var2").singleResult(); assertNotNull(var2); assertEquals("stringConstantValue", var2.getValue()); assertEquals(pi.getId(), var2.getExecutionId()); } @Deployment @SuppressWarnings("unchecked") public void testOutputListNestedValues() { runtimeService.startProcessInstanceByKey("testProcess"); VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("var1").singleResult(); assertNotNull(variable); List<Object> value = (List<Object>) variable.getValue(); assertEquals("constantStringValue", value.get(0)); assertEquals("elValue", value.get(1)); assertEquals("scriptValue", value.get(2)); List<Object> nestedList = (List<Object>) value.get(3); List<Object> nestedNestedList = (List<Object>) nestedList.get(0); assertEquals("a", nestedNestedList.get(0)); assertEquals("b", nestedNestedList.get(1)); assertEquals("c", nestedNestedList.get(2)); assertEquals("d", nestedList.get(1)); TreeMap<String, Object> nestedMap = (TreeMap<String, Object>) value.get(4); assertEquals("bar", nestedMap.get("foo")); assertEquals("world", nestedMap.get("hello")); } // ensure Io supported on event subprocess ///////////////////////////////// public void testInterruptingEventSubprocessIoSupport() { try { repositoryService .createDeployment() .addClasspathResource("org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testInterruptingEventSubprocessIoSupport.bpmn") .deploy(); fail("exception expected"); } catch (ProcessEngineException e) { // happy path assertTextPresent("camunda:inputOutput mapping unsupported for element type 'subProcess' with attribute 'triggeredByEvent = true'", e.getMessage()); } } @Deployment public void testSubprocessIoSupport() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("processVar", "value"); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testProcess", variables); Execution subprocessExecution = runtimeService.createExecutionQuery().activityId("subprocessTask").singleResult(); Map<String, Object> variablesLocal = runtimeService.getVariablesLocal(subprocessExecution.getId()); assertEquals(1, variablesLocal.size()); assertEquals("value", variablesLocal.get("innerVar")); Task task = taskService.createTaskQuery().singleResult(); taskService.complete(task.getId()); String outerVariable = (String) runtimeService.getVariableLocal(processInstance.getId(), "outerVar"); assertNotNull(outerVariable); assertEquals("value", outerVariable); } @Deployment public void testSequentialMIActivityIoSupport() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("counter", new AtomicInteger()); variables.put("nrOfLoops", 2); ProcessInstance instance = runtimeService.startProcessInstanceByKey("miSequentialActivity", variables); // first sequential mi execution Execution miExecution = runtimeService.createExecutionQuery().activityId("miTask").singleResult(); assertNotNull(miExecution); assertFalse(instance.getId().equals(miExecution.getId())); assertEquals(0, runtimeService.getVariable(miExecution.getId(), "loopCounter")); // input mapping assertEquals(1, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); assertEquals(1, runtimeService.getVariableLocal(miExecution.getId(), "miCounterValue")); Task task = taskService.createTaskQuery().singleResult(); taskService.complete(task.getId()); // second sequential mi execution miExecution = runtimeService.createExecutionQuery().activityId("miTask").singleResult(); assertNotNull(miExecution); assertFalse(instance.getId().equals(miExecution.getId())); assertEquals(1, runtimeService.getVariable(miExecution.getId(), "loopCounter")); // input mapping assertEquals(1, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); assertEquals(2, runtimeService.getVariableLocal(miExecution.getId(), "miCounterValue")); task = taskService.createTaskQuery().singleResult(); taskService.complete(task.getId()); // variable does not exist outside of scope assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); } @Deployment public void testSequentialMISubprocessIoSupport() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("counter", new AtomicInteger()); variables.put("nrOfLoops", 2); ProcessInstance instance = runtimeService.startProcessInstanceByKey("miSequentialSubprocess", variables); // first sequential mi execution Execution miScopeExecution = runtimeService.createExecutionQuery().activityId("task").singleResult(); assertNotNull(miScopeExecution); assertEquals(0, runtimeService.getVariable(miScopeExecution.getId(), "loopCounter")); // input mapping assertEquals(1, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); assertEquals(1, runtimeService.getVariableLocal(miScopeExecution.getId(), "miCounterValue")); Task task = taskService.createTaskQuery().singleResult(); taskService.complete(task.getId()); // second sequential mi execution miScopeExecution = runtimeService.createExecutionQuery().activityId("task").singleResult(); assertNotNull(miScopeExecution); assertFalse(instance.getId().equals(miScopeExecution.getId())); assertEquals(1, runtimeService.getVariable(miScopeExecution.getId(), "loopCounter")); // input mapping assertEquals(1, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); assertEquals(2, runtimeService.getVariableLocal(miScopeExecution.getId(), "miCounterValue")); task = taskService.createTaskQuery().singleResult(); taskService.complete(task.getId()); // variable does not exist outside of scope assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); } @Deployment public void testParallelMIActivityIoSupport() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("counter", new AtomicInteger()); variables.put("nrOfLoops", 2); ProcessInstance instance = runtimeService.startProcessInstanceByKey("miParallelActivity", variables); // first mi execution Execution miExecution1 = runtimeService.createExecutionQuery().activityId("miTask") .variableValueEquals("loopCounter", 0).singleResult(); assertNotNull(miExecution1); assertFalse(instance.getId().equals(miExecution1.getId())); assertEquals(1, runtimeService.getVariableLocal(miExecution1.getId(), "miCounterValue")); // second mi execution Execution miExecution2 = runtimeService.createExecutionQuery().activityId("miTask") .variableValueEquals("loopCounter", 1).singleResult(); assertNotNull(miExecution2); assertFalse(instance.getId().equals(miExecution2.getId())); assertEquals(2, runtimeService.getVariableLocal(miExecution2.getId(), "miCounterValue")); assertEquals(2, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); for (Task task : taskService.createTaskQuery().list()) { taskService.complete(task.getId()); } // variable does not exist outside of scope assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); } @Deployment public void testParallelMISubprocessIoSupport() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("counter", new AtomicInteger()); variables.put("nrOfLoops", 2); ProcessInstance instance = runtimeService.startProcessInstanceByKey("miParallelSubprocess", variables); // first parallel mi execution Execution miScopeExecution1 = runtimeService.createExecutionQuery().activityId("task") .variableValueEquals("loopCounter", 0).singleResult(); assertNotNull(miScopeExecution1); assertEquals(1, runtimeService.getVariableLocal(miScopeExecution1.getId(), "miCounterValue")); // second parallel mi execution Execution miScopeExecution2 = runtimeService.createExecutionQuery().activityId("task") .variableValueEquals("loopCounter", 1).singleResult(); assertNotNull(miScopeExecution2); assertFalse(instance.getId().equals(miScopeExecution2.getId())); assertEquals(2, runtimeService.getVariableLocal(miScopeExecution2.getId(), "miCounterValue")); assertEquals(2, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); for (Task task : taskService.createTaskQuery().list()) { taskService.complete(task.getId()); } // variable does not exist outside of scope assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("miCounterValue").count()); } public void testMIOutputMappingDisallowed() { try { repositoryService.createDeployment() .addClasspathResource("org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testMIOutputMappingDisallowed.bpmn20.xml") .deploy(); fail("Exception expected"); } catch (ProcessEngineException e) { assertTextPresent("camunda:outputParameter not allowed for multi-instance constructs", e.getMessage()); } } @Deployment(resources = "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testThrowErrorInScriptInputOutputMapping.bpmn") public void testBpmnErrorInScriptInputMapping() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("throwInMapping", "in"); variables.put("exception", new BpmnError("error")); runtimeService.startProcessInstanceByKey("testProcess", variables); //we will only reach the user task if the BPMNError from the script was handled by the boundary event Task task = taskService.createTaskQuery().singleResult(); assertThat(task.getName(), is("User Task")); } @Deployment(resources = "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testThrowErrorInScriptInputOutputMapping.bpmn") public void testExceptionInScriptInputMapping() { String exceptionMessage = "myException"; Map<String, Object> variables = new HashMap<String, Object>(); variables.put("throwInMapping", "in"); variables.put("exception", new RuntimeException(exceptionMessage)); try { runtimeService.startProcessInstanceByKey("testProcess", variables); } catch(RuntimeException re){ assertThat(re.getMessage(), containsString(exceptionMessage)); } } @Deployment(resources = "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testThrowErrorInScriptInputOutputMapping.bpmn") public void testBpmnErrorInScriptOutputMapping() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("throwInMapping", "out"); variables.put("exception", new BpmnError("error")); runtimeService.startProcessInstanceByKey("testProcess", variables); //we will only reach the user task if the BPMNError from the script was handled by the boundary event Task task = taskService.createTaskQuery().singleResult(); assertThat(task.getName(), is("User Task")); } @Deployment(resources = "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testThrowErrorInScriptInputOutputMapping.bpmn") public void testExceptionInScriptOutputMapping() { String exceptionMessage = "myException"; Map<String, Object> variables = new HashMap<String, Object>(); variables.put("throwInMapping", "out"); variables.put("exception", new RuntimeException(exceptionMessage)); try { runtimeService.startProcessInstanceByKey("testProcess", variables); } catch(RuntimeException re){ assertThat(re.getMessage(), containsString(exceptionMessage)); } } @Deployment public void FAILING_testOutputMappingOnErrorBoundaryEvent() { // case 1: no error occurs runtimeService.startProcessInstanceByKey("testProcess"); Task task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("taskOk", task.getTaskDefinitionKey()); // then: variable mapped exists assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("localNotMapped").count()); assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("localMapped").count()); assertEquals(1, runtimeService.createVariableInstanceQuery().variableName("mapped").count()); taskService.complete(task.getId()); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); // case 2: error occurs runtimeService.startProcessInstanceByKey("testProcess", Collections.<String, Object>singletonMap("throwError", true)); task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("taskError", task.getTaskDefinitionKey()); assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("localNotMapped").count()); assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("localMapped").count()); assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("mapped").count()); taskService.complete(task.getId()); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); } @Deployment public void FAILING_testOutputMappingOnMessageBoundaryEvent() { // case 1: no error occurs runtimeService.startProcessInstanceByKey("testProcess"); Task task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("wait", task.getTaskDefinitionKey()); taskService.complete(task.getId()); task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("taskOk", task.getTaskDefinitionKey()); // then: variable mapped exists assertEquals(1, runtimeService.createVariableInstanceQuery().variableName("mapped").count()); taskService.complete(task.getId()); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); // case 2: error occurs runtimeService.startProcessInstanceByKey("testProcess", Collections.<String, Object>singletonMap("throwError", true)); task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("wait", task.getTaskDefinitionKey()); runtimeService.correlateMessage("message"); task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("taskError", task.getTaskDefinitionKey()); assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("mapped").count()); taskService.complete(task.getId()); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); } @Deployment public void FAILING_testOutputMappingOnTimerBoundaryEvent() { // case 1: no error occurs runtimeService.startProcessInstanceByKey("testProcess"); Task task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("wait", task.getTaskDefinitionKey()); taskService.complete(task.getId()); task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("taskOk", task.getTaskDefinitionKey()); // then: variable mapped exists assertEquals(1, runtimeService.createVariableInstanceQuery().variableName("mapped").count()); taskService.complete(task.getId()); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); // case 2: error occurs runtimeService.startProcessInstanceByKey("testProcess", Collections.<String, Object>singletonMap("throwError", true)); task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("wait", task.getTaskDefinitionKey()); Job job = managementService.createJobQuery().singleResult(); assertNotNull(job); managementService.executeJob(job.getId()); task = taskService.createTaskQuery().singleResult(); assertNotNull(task); assertEquals("taskError", task.getTaskDefinitionKey()); assertEquals(0, runtimeService.createVariableInstanceQuery().variableName("mapped").count()); taskService.complete(task.getId()); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); } }
chore(engine): exclude failing test cases related to #CAM-3864
engine/src/test/java/org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.java
chore(engine): exclude failing test cases
<ide><path>ngine/src/test/java/org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.java <ide> } <ide> <ide> @Deployment(resources = "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testThrowErrorInScriptInputOutputMapping.bpmn") <del> public void testBpmnErrorInScriptInputMapping() { <add> public void FAILING_testBpmnErrorInScriptInputMapping() { <ide> Map<String, Object> variables = new HashMap<String, Object>(); <ide> variables.put("throwInMapping", "in"); <ide> variables.put("exception", new BpmnError("error")); <ide> } <ide> <ide> @Deployment(resources = "org/camunda/bpm/engine/test/bpmn/iomapping/InputOutputTest.testThrowErrorInScriptInputOutputMapping.bpmn") <del> public void testBpmnErrorInScriptOutputMapping() { <add> public void FAILING_testBpmnErrorInScriptOutputMapping() { <ide> Map<String, Object> variables = new HashMap<String, Object>(); <ide> variables.put("throwInMapping", "out"); <ide> variables.put("exception", new BpmnError("error"));
Java
apache-2.0
3ca1e817e46611b82d35641b433784002d793b58
0
apache/lenya,apache/lenya,apache/lenya,apache/lenya
/* * Copyright 1999-2004 The Apache Software Foundation * * 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. * */ /* $Id$ */ package org.apache.lenya.workflow.impl; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.lenya.workflow.Version; /** * A version of the workflow history. */ public class VersionImpl implements Version { private String event; private String state; private Map variableValues = new HashMap(); /** * @see org.apache.lenya.workflow.Version#getEvent() */ public String getEvent() { return this.event; } /** * @see org.apache.lenya.workflow.Version#getState() */ public String getState() { return this.state; } private Date date; private String userId; private String ipAddress; /** * Returns the date. * @return A string. */ public Date getDate() { return this.date; } /** * Sets the date. * @param _date A date. */ public void setDate(Date _date) { this.date = _date; } /** * Returns the user ID. * @return A string. */ public String getUserId() { return this.userId; } /** * Sets the user ID. * @param _userId A user ID. */ public void setUserId(String _userId) { this.userId = _userId; } /** * Returns the ip address. * @return A string. */ public String getIPAddress() { return this.ipAddress; } /** * Sets the ip address. * @param _ipaddress A ip address. */ public void setIPAddress(String _ipaddress){ this.ipAddress = _ipaddress; } /** * Ctor. * @param _event The event that caused the version change. * @param _state The destination state. */ public VersionImpl(String _event, String _state) { this.event = _event; this.state = _state; } /** * @see org.apache.lenya.workflow.Version#getValue(java.lang.String) */ public boolean getValue(String variableName) { Boolean value = (Boolean) this.variableValues.get(variableName); if (value == null) { throw new RuntimeException("No value set for variable [" + variableName + "]"); } return value.booleanValue(); } /** * @see org.apache.lenya.workflow.Version#setValue(java.lang.String, boolean) */ public void setValue(String variableName, boolean value) { this.variableValues.put(variableName, Boolean.valueOf(value)); } }
src/java/org/apache/lenya/workflow/impl/VersionImpl.java
/* * Copyright 1999-2004 The Apache Software Foundation * * 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. * */ /* $Id$ */ package org.apache.lenya.workflow.impl; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.lenya.workflow.Version; /** * A version of the workflow history. */ public class VersionImpl implements Version { private String event; private String state; private Map variableValues = new HashMap(); /** * @see org.apache.lenya.workflow.Version#getEvent() */ public String getEvent() { return this.event; } /** * @see org.apache.lenya.workflow.Version#getState() */ public String getState() { return this.state; } private Date date; private String userId; private String ipAddress; /** * Returns the date. * @return A string. */ public Date getDate() { return this.date; } /** * Sets the date. * @param _date A date. */ public void setDate(Date _date) { this.date = _date; } /** * Returns the user ID. * @return A string. */ public String getUserId() { return this.userId; } /** * Sets the user ID. * @param _userId A user ID. */ public void setUserId(String _userId) { this.userId = _userId; } /** * Returns the ip address. * @return A string. */ public String getIPAddress() { return this.ipAddress; } /** * Sets the ip address. * @param _ipaddress A ip address. */ public void setIPAddress(String _ipaddress){ this.ipAddress = _ipaddress; } /** * Ctor. * @param _event The event that caused the version change. * @param _state The destination state. */ public VersionImpl(String _event, String _state) { this.event = _event; this.state = _state; } /** * @see org.apache.lenya.workflow.Version#getValue(java.lang.String) */ public boolean getValue(String variableName) { Boolean value = (Boolean) this.variableValues.get(variableName); return value.booleanValue(); } /** * @see org.apache.lenya.workflow.Version#setValue(java.lang.String, boolean) */ public void setValue(String variableName, boolean value) { this.variableValues.put(variableName, Boolean.valueOf(value)); } }
Throw appropriate exception if workflow variable does not exist git-svn-id: c334bb69c16d150e1b06e84516f7aa90b3181ca2@372568 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/lenya/workflow/impl/VersionImpl.java
Throw appropriate exception if workflow variable does not exist
<ide><path>rc/java/org/apache/lenya/workflow/impl/VersionImpl.java <ide> */ <ide> public boolean getValue(String variableName) { <ide> Boolean value = (Boolean) this.variableValues.get(variableName); <add> if (value == null) { <add> throw new RuntimeException("No value set for variable [" + variableName + "]"); <add> } <ide> return value.booleanValue(); <ide> } <ide>
Java
apache-2.0
818e744062313e946e8723d34bb95888262df840
0
sunmiqa/SunmiAuto
package sunmi.com.sunmiauto; import android.app.Instrumentation; import android.os.Build; import android.os.Environment; import android.os.RemoteException; import android.support.test.InstrumentationRegistry; import android.support.test.uiautomator.By; import android.support.test.uiautomator.UiDevice; import android.support.test.uiautomator.UiObject2; import android.support.test.uiautomator.Until; import android.util.Log; import java.io.File; /** * Created by fengy on 2017/7/8. */ public class SunmiUtil { static Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); static UiDevice device = UiDevice.getInstance(instrumentation); static final int timeoutSeconds = 20000; //清除最近使用程序 public static void clearAllRecentApps() throws RemoteException { try{ device.pressHome(); device.pressHome(); device.pressRecentApps(); device.wait(Until.hasObject(By.res("com.android.systemui:id/loading")),timeoutSeconds); sleep(2000); UiObject2 clearObj = device.findObject(By.res("com.android.systemui:id/loading")); clearObj.clickAndWait(Until.newWindow(),timeoutSeconds); }catch (NullPointerException e){ device.pressHome(); device.pressHome(); device.pressRecentApps(); device.wait(Until.hasObject(By.res("com.android.systemui:id/loading")),timeoutSeconds); sleep(2000); UiObject2 clearObj = device.findObject(By.res("com.android.systemui:id/loading")); clearObj.clickAndWait(Until.newWindow(),timeoutSeconds); } } //传递一个应用名称,找到该名称的应用,找到返回true,未找到返回false public static boolean findAppByText(String appName){ device.pressHome(); device.pressHome(); UiObject2 appIcon = device.findObject(By.text(appName)); if(null != appIcon){ return true; } device.wait(Until.hasObject(By.res("com.woyou.launcher:id/page_indicator")),timeoutSeconds); UiObject2 indicatorObj = device.findObject(By.res("com.woyou.launcher:id/page_indicator")); int pages = indicatorObj.getChildCount(); Log.v("sssss",Integer.toString(pages)); device.swipe(5,device.getDisplayHeight()/2,device.getDisplayWidth()-5,device.getDisplayHeight()/2,20); sleep(2000); for(int i = 0;i < pages;i++){ Log.v("ssss",Integer.toString(i)); UiObject2 appObj = device.findObject(By.text(appName)); if(null != appObj){ return true; } else { sleep(2000); device.swipe(device.getDisplayWidth()-5,device.getDisplayHeight()/2,5,device.getDisplayHeight()/2,10); sleep(2000); } } return false; } //传递一个应用名称,找到该名称的应用并打开,找到返回true,未找到返回false public static boolean findAppAndOpenByText(String appName){ device.pressHome(); device.pressHome(); UiObject2 appIcon = device.findObject(By.text(appName)); if(null != appIcon){ appIcon.clickAndWait(Until.newWindow(),timeoutSeconds); return true; } device.wait(Until.hasObject(By.res("com.woyou.launcher:id/page_indicator")),timeoutSeconds); int pages = device.findObject(By.res("com.woyou.launcher:id/page_indicator")).getChildCount(); Log.v("sssss",Integer.toString(pages)); device.swipe(5,device.getDisplayHeight()/2,device.getDisplayWidth()-5,device.getDisplayHeight()/2,20); sleep(2000); int i = 0; while(i < pages){ UiObject2 appObj = device.findObject(By.text(appName)); if(null != appObj){ appObj.clickAndWait(Until.newWindow(),timeoutSeconds); device.waitForIdle(); return true; } else if(i < pages -1){ sleep(2000); device.swipe(device.getDisplayWidth()-5,device.getDisplayHeight()/2,5,device.getDisplayHeight()/2,10); sleep(2000); } i++; } return false; } //截图并保存图片到相关的测试类,测试case目录下 public static void screenshotCap(String tag) { StackTraceElement testClass = findTestClassTraceElement(Thread.currentThread().getStackTrace()); String className = testClass.getClassName().replaceAll("[^A-Za-z0-9._-]", "_"); String methodName = testClass.getMethodName(); Log.v("Extenrnal", Environment.getExternalStorageState()); File dir = new File(Environment.getExternalStorageDirectory() + File.separator + "app_spoon-screenshots" + File.separator + className + File.separator + methodName); Log.v("TEST", dir.getAbsolutePath()); if (!dir.exists()) { dir.mkdirs(); } String screenshotName = System.currentTimeMillis() + "_" + tag + ".png"; File screenshotFile = new File(dir, screenshotName); sleep(1000); device.takeScreenshot(screenshotFile, 0.2F, 50); sleep(2000); } //获取栈信息,该方法用于获取当前正在进行的测试case类信息,方法信息 public static StackTraceElement findTestClassTraceElement(StackTraceElement[] trace) { for (StackTraceElement e : trace) { Log.v("traceTest", e.getClassName() + ":" + e.getMethodName()); } for (int i = trace.length - 1; i >= 0; --i) { StackTraceElement element = trace[i]; if ("android.test.InstrumentationTestCase".equals(element.getClassName()) && "runMethod".equals(element.getMethodName())) { if (Build.VERSION.SDK_INT >= 23) { return trace[i - 2]; } else { return trace[i - 3]; } } if ("org.junit.runners.model.FrameworkMethod$1".equals(element.getClassName()) && "runReflectiveCall".equals(element.getMethodName())) { if (Build.VERSION.SDK_INT >= 23) { return trace[i - 2]; } else { return trace[i - 3]; } } } throw new IllegalArgumentException("Could not find test class!"); } //sleep方法 public static void sleep(int sleep) { try { Thread.sleep(sleep); } catch (InterruptedException e) { e.printStackTrace(); } } }
app/src/androidTest/java/sunmi/com/sunmiauto/SunmiUtil.java
package sunmi.com.sunmiauto; import android.app.Instrumentation; import android.os.Build; import android.os.Environment; import android.os.RemoteException; import android.support.test.InstrumentationRegistry; import android.support.test.uiautomator.By; import android.support.test.uiautomator.UiDevice; import android.support.test.uiautomator.UiObject2; import android.support.test.uiautomator.Until; import android.util.Log; import java.io.File; /** * Created by fengy on 2017/7/8. */ public class SunmiUtil { static Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); static UiDevice device = UiDevice.getInstance(instrumentation); static final int timeoutSeconds = 20000; //清除最近使用程序 public static void clearAllRecentApps() throws RemoteException { try{ device.pressHome(); device.pressHome(); device.pressRecentApps(); device.wait(Until.hasObject(By.res("com.android.systemui:id/loading")),timeoutSeconds); sleep(2000); UiObject2 clearObj = device.findObject(By.res("com.android.systemui:id/loading")); clearObj.clickAndWait(Until.newWindow(),timeoutSeconds); }catch (NullPointerException e){ device.pressHome(); device.pressHome(); device.pressRecentApps(); device.wait(Until.hasObject(By.res("com.android.systemui:id/loading")),timeoutSeconds); sleep(2000); UiObject2 clearObj = device.findObject(By.res("com.android.systemui:id/loading")); clearObj.clickAndWait(Until.newWindow(),timeoutSeconds); } } //传递一个应用名称,找到该名称的应用,找到返回true,未找到返回false public static boolean findAppByText(String appName){ device.pressHome(); device.pressHome(); UiObject2 appIcon = device.findObject(By.text(appName)); if(null != appIcon){ return true; } device.wait(Until.hasObject(By.res("com.woyou.launcher:id/page_indicator")),timeoutSeconds); UiObject2 indicatorObj = device.findObject(By.res("com.woyou.launcher:id/page_indicator")); int pages = indicatorObj.getChildCount(); Log.v("sssss",Integer.toString(pages)); device.swipe(5,device.getDisplayHeight()/2,device.getDisplayWidth()-5,device.getDisplayHeight()/2,20); sleep(2000); for(int i = 0;i < pages - 1;i++){ Log.v("ssss",Integer.toString(i)); UiObject2 appObj = device.findObject(By.text(appName)); if(null != appObj){ return true; } else { sleep(2000); device.swipe(device.getDisplayWidth()-5,device.getDisplayHeight()/2,5,device.getDisplayHeight()/2,10); sleep(2000); } } return false; } //传递一个应用名称,找到该名称的应用并打开,找到返回true,未找到返回false public static boolean findAppAndOpenByText(String appName){ device.pressHome(); device.pressHome(); UiObject2 appIcon = device.findObject(By.text(appName)); if(null != appIcon){ appIcon.clickAndWait(Until.newWindow(),timeoutSeconds); return true; } device.wait(Until.hasObject(By.res("com.woyou.launcher:id/page_indicator")),timeoutSeconds); int pages = device.findObject(By.res("com.woyou.launcher:id/page_indicator")).getChildCount(); Log.v("sssss",Integer.toString(pages)); device.swipe(5,device.getDisplayHeight()/2,device.getDisplayWidth()-5,device.getDisplayHeight()/2,20); sleep(2000); int i = 0; while(i < pages){ UiObject2 appObj = device.findObject(By.text(appName)); if(null != appObj){ appObj.clickAndWait(Until.newWindow(),timeoutSeconds); device.waitForIdle(); return true; } else if(i < pages -1){ sleep(2000); device.swipe(device.getDisplayWidth()-5,device.getDisplayHeight()/2,5,device.getDisplayHeight()/2,10); sleep(2000); } i++; } return false; } //截图并保存图片到相关的测试类,测试case目录下 public static void screenshotCap(String tag) { StackTraceElement testClass = findTestClassTraceElement(Thread.currentThread().getStackTrace()); String className = testClass.getClassName().replaceAll("[^A-Za-z0-9._-]", "_"); String methodName = testClass.getMethodName(); Log.v("Extenrnal", Environment.getExternalStorageState()); File dir = new File(Environment.getExternalStorageDirectory() + File.separator + "app_spoon-screenshots" + File.separator + className + File.separator + methodName); Log.v("TEST", dir.getAbsolutePath()); if (!dir.exists()) { dir.mkdirs(); } String screenshotName = System.currentTimeMillis() + "_" + tag + ".png"; File screenshotFile = new File(dir, screenshotName); sleep(1000); device.takeScreenshot(screenshotFile, 0.2F, 50); sleep(2000); } //获取栈信息,该方法用于获取当前正在进行的测试case类信息,方法信息 public static StackTraceElement findTestClassTraceElement(StackTraceElement[] trace) { for (StackTraceElement e : trace) { Log.v("traceTest", e.getClassName() + ":" + e.getMethodName()); } for (int i = trace.length - 1; i >= 0; --i) { StackTraceElement element = trace[i]; if ("android.test.InstrumentationTestCase".equals(element.getClassName()) && "runMethod".equals(element.getMethodName())) { if (Build.VERSION.SDK_INT >= 23) { return trace[i - 2]; } else { return trace[i - 3]; } } if ("org.junit.runners.model.FrameworkMethod$1".equals(element.getClassName()) && "runReflectiveCall".equals(element.getMethodName())) { if (Build.VERSION.SDK_INT >= 23) { return trace[i - 2]; } else { return trace[i - 3]; } } } throw new IllegalArgumentException("Could not find test class!"); } //sleep方法 public static void sleep(int sleep) { try { Thread.sleep(sleep); } catch (InterruptedException e) { e.printStackTrace(); } } }
fix findappbytext bug
app/src/androidTest/java/sunmi/com/sunmiauto/SunmiUtil.java
fix findappbytext bug
<ide><path>pp/src/androidTest/java/sunmi/com/sunmiauto/SunmiUtil.java <ide> Log.v("sssss",Integer.toString(pages)); <ide> device.swipe(5,device.getDisplayHeight()/2,device.getDisplayWidth()-5,device.getDisplayHeight()/2,20); <ide> sleep(2000); <del> for(int i = 0;i < pages - 1;i++){ <add> for(int i = 0;i < pages;i++){ <ide> Log.v("ssss",Integer.toString(i)); <ide> UiObject2 appObj = device.findObject(By.text(appName)); <ide> if(null != appObj){
Java
bsd-2-clause
5edf634cabd5f8f02ccfe43b4bdc346658225fd2
0
BrunoReX/jmkvpropedit,BrunoReX/jmkvpropedit,BrunoReX/jmkvpropedit
/* * Copyright (c) 2012 Bruno Barbieri * 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. * * 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 HOLDER 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.googlecode.jmkvpropedit; import java.awt.*; import java.awt.event.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.*; import javax.swing.*; import javax.swing.filechooser.*; import org.ini4j.*; public class JMkvpropedit { private JFrame frmJMkvpropedit; private int maxStreams = 30; // Track number limit for batch mode Runtime rt = Runtime.getRuntime(); private Process proc = null; private SwingWorker<Void, Void> worker = null; private JPanel[] subPnlVideo = new JPanel[maxStreams]; private JCheckBox[] chbEditVideo = new JCheckBox[maxStreams]; private JCheckBox[] chbDefaultVideo = new JCheckBox[maxStreams]; private JRadioButton[] rbYesDefVideo = new JRadioButton[maxStreams]; private JRadioButton[] rbNoDefVideo = new JRadioButton[maxStreams]; private ButtonGroup[] bgRbDefVideo = new ButtonGroup[maxStreams]; private JCheckBox[] chbForcedVideo = new JCheckBox[maxStreams]; private JRadioButton[] rbYesForcedVideo = new JRadioButton[maxStreams]; private JRadioButton[] rbNoForcedVideo = new JRadioButton[maxStreams]; private ButtonGroup[] bgRbForcedVideo = new ButtonGroup[maxStreams]; private JCheckBox[] chbNameVideo = new JCheckBox[maxStreams]; private JTextField[] txtNameVideo = new JTextField[maxStreams]; private JCheckBox[] cbNumbVideo = new JCheckBox[maxStreams]; private JTextField[] txtNumbStartVideo = new JTextField[maxStreams]; private JLabel[] lblNumbStartVideo = new JLabel[maxStreams]; private JLabel[] lblNumbExplainVideo = new JLabel[maxStreams]; private JLabel[] lblNumbPadVideo = new JLabel[maxStreams]; private JTextField[] txtNumbPadVideo = new JTextField[maxStreams]; private JCheckBox[] chbLangVideo = new JCheckBox[maxStreams]; private JComboBox[] cbLangVideo = new JComboBox[maxStreams]; private JCheckBox[] chbExtraCmdVideo = new JCheckBox[maxStreams]; private JTextField[] txtExtraCmdVideo = new JTextField[maxStreams]; private JPanel[] subPnlAudio = new JPanel[maxStreams]; private JCheckBox[] chbEditAudio = new JCheckBox[maxStreams]; private JCheckBox[] chbDefaultAudio = new JCheckBox[maxStreams]; private JRadioButton[] rbYesDefAudio = new JRadioButton[maxStreams]; private JRadioButton[] rbNoDefAudio = new JRadioButton[maxStreams]; private ButtonGroup[] bgRbDefAudio = new ButtonGroup[maxStreams]; private JCheckBox[] chbForcedAudio = new JCheckBox[maxStreams]; private JRadioButton[] rbYesForcedAudio = new JRadioButton[maxStreams]; private JRadioButton[] rbNoForcedAudio = new JRadioButton[maxStreams]; private ButtonGroup[] bgRbForcedAudio = new ButtonGroup[maxStreams]; private JCheckBox[] chbNameAudio = new JCheckBox[maxStreams]; private JTextField[] txtNameAudio = new JTextField[maxStreams]; private JCheckBox[] cbNumbAudio = new JCheckBox[maxStreams]; private JTextField[] txtNumbStartAudio = new JTextField[maxStreams]; private JLabel[] lblNumbStartAudio = new JLabel[maxStreams]; private JLabel[] lblNumbExplainAudio = new JLabel[maxStreams]; private JLabel[] lblNumbPadAudio = new JLabel[maxStreams]; private JTextField[] txtNumbPadAudio = new JTextField[maxStreams]; private JCheckBox[] chbLangAudio = new JCheckBox[maxStreams]; private JComboBox[] cbLangAudio = new JComboBox[maxStreams]; private JCheckBox[] chbExtraCmdAudio = new JCheckBox[maxStreams]; private JTextField[] txtExtraCmdAudio = new JTextField[maxStreams]; private JPanel[] subPnlSubtitle = new JPanel[maxStreams]; private JCheckBox[] chbEditSubtitle = new JCheckBox[maxStreams]; private JCheckBox[] chbDefaultSubtitle = new JCheckBox[maxStreams]; private JRadioButton[] rbYesDefSubtitle = new JRadioButton[maxStreams]; private JRadioButton[] rbNoDefSubtitle = new JRadioButton[maxStreams]; private ButtonGroup[] bgRbDefSubtitle = new ButtonGroup[maxStreams]; private JCheckBox[] chbForcedSubtitle = new JCheckBox[maxStreams]; private JRadioButton[] rbYesForcedSubtitle = new JRadioButton[maxStreams]; private JRadioButton[] rbNoForcedSubtitle = new JRadioButton[maxStreams]; private ButtonGroup[] bgRbForcedSubtitle = new ButtonGroup[maxStreams]; private JCheckBox[] chbNameSubtitle = new JCheckBox[maxStreams]; private JTextField[] txtNameSubtitle = new JTextField[maxStreams]; private JCheckBox[] cbNumbSubtitle = new JCheckBox[maxStreams]; private JTextField[] txtNumbStartSubtitle = new JTextField[maxStreams]; private JLabel[] lblNumbStartSubtitle = new JLabel[maxStreams]; private JLabel[] lblNumbExplainSubtitle = new JLabel[maxStreams]; private JLabel[] lblNumbPadSubtitle = new JLabel[maxStreams]; private JTextField[] txtNumbPadSubtitle = new JTextField[maxStreams]; private JCheckBox[] chbLangSubtitle = new JCheckBox[maxStreams]; private JComboBox[] cbLangSubtitle = new JComboBox[maxStreams]; private JCheckBox[] chbExtraCmdSubtitle = new JCheckBox[maxStreams]; private JTextField[] txtExtraCmdSubtitle = new JTextField[maxStreams]; private JCheckBox chbTitleGeneral; private JTextField txtTitleGeneral; private JCheckBox cbNumbGeneral; private JTextField txtNumbStartGeneral; private JTextField txtNumbPadGeneral; private JCheckBox chbRemoveChapters; private JCheckBox chbRemoveTags; private JCheckBox chbExtraCmdGeneral; private JTextField txtExtraCmdGeneral; private JTextField txtMkvPropExe; private JCheckBox cbMkvPropExeDef; private JTabbedPane tabbedPane; private DefaultListModel modelFiles; private JList listFiles; private JComboBox cbVideo; private JComboBox cbAudio; private JComboBox cbSubtitle; private JLayeredPane lyrdPnlVideo; private JLayeredPane lyrdPnlAudio; private JLayeredPane lyrdPnlSubtitle; private JButton btnProcessFiles; private JButton btnGenerateCmdLine; private JTextArea txtOutput; private int nVideo = 0; private int nAudio = 0; private int nSubtitle = 0; MkvLanguage mkvLang = new MkvLanguage(); URL imgRes = null; JFileChooser chooser = null; private File iniFile = new File("JMkvpropedit.ini"); private String[] cmdLineGeneral = null; private String[] cmdLineGeneralOpt = null; private String[] cmdLineVideo = null; private String[] cmdLineVideoOpt = null; private String[] cmdLineAudio = null; private String[] cmdLineAudioOpt = null; private String[] cmdLineSubtitle = null; private String[] cmdLineSubtitleOpt = null; private ArrayList<String> cmdLineBatch = null; private ArrayList<String> cmdLineBatchOpt = null; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // Use native theme for GUI JMkvpropedit window = new JMkvpropedit(); window.frmJMkvpropedit.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public JMkvpropedit() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frmJMkvpropedit = new JFrame(); frmJMkvpropedit.setTitle("JMkvpropedit 1.0.3.1"); /* Version */ frmJMkvpropedit.setResizable(false); frmJMkvpropedit.setBounds(100, 100, 759, 444); frmJMkvpropedit.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frmJMkvpropedit.getContentPane().setLayout(null); tabbedPane = new JTabbedPane(JTabbedPane.TOP); tabbedPane.setBounds(10, 11, 733, 360); frmJMkvpropedit.getContentPane().add(tabbedPane); JPanel pnlInput = new JPanel(); tabbedPane.addTab("Input", null, pnlInput, null); pnlInput.setLayout(null); JScrollPane scrollFiles = new JScrollPane(); scrollFiles.setBounds(10, 11, 676, 310); pnlInput.add(scrollFiles); modelFiles = new DefaultListModel(); listFiles = new JList(modelFiles); scrollFiles.setViewportView(listFiles); imgRes = ClassLoader.getSystemResource("res/list-add.png"); JButton btnAddFiles = new JButton(""); btnAddFiles.setIcon(new ImageIcon(imgRes)); btnAddFiles.setBounds(696, 21, 22, 23); pnlInput.add(btnAddFiles); imgRes = ClassLoader.getSystemResource("res/list-remove.png"); JButton btnRemoveFiles = new JButton(""); btnRemoveFiles.setIcon(new ImageIcon(imgRes)); btnRemoveFiles.setBounds(696, 65, 22, 23); pnlInput.add(btnRemoveFiles); imgRes = ClassLoader.getSystemResource("res/edit-clear.png"); JButton btnClearFiles = new JButton(""); btnClearFiles.setIcon(new ImageIcon(imgRes)); btnClearFiles.setBounds(696, 109, 22, 23); pnlInput.add(btnClearFiles); imgRes = ClassLoader.getSystemResource("res/go-top.png"); JButton btnTopFiles = new JButton(""); btnTopFiles.setIcon(new ImageIcon(imgRes)); btnTopFiles.setBounds(696, 153, 22, 23); pnlInput.add(btnTopFiles); imgRes = ClassLoader.getSystemResource("res/go-up.png"); JButton btnUpFiles = new JButton(""); btnUpFiles.setIcon(new ImageIcon(imgRes)); btnUpFiles.setBounds(696, 197, 22, 23); pnlInput.add(btnUpFiles); imgRes = ClassLoader.getSystemResource("res/go-down.png"); JButton btnDownFiles = new JButton(""); btnDownFiles.setIcon(new ImageIcon(imgRes)); btnDownFiles.setBounds(696, 241, 22, 23); pnlInput.add(btnDownFiles); imgRes = ClassLoader.getSystemResource("res/go-bottom.png"); JButton btnBottomFiles = new JButton(""); btnBottomFiles.setIcon(new ImageIcon(imgRes)); btnBottomFiles.setBounds(696, 285, 22, 23); pnlInput.add(btnBottomFiles); chooser = new JFileChooser(); chooser.setDialogType(JFileChooser.OPEN_DIALOG); chooser.setFileHidingEnabled(true); chooser.setAcceptAllFileFilterUsed(false); JPanel pnlGeneral = new JPanel(); tabbedPane.addTab("General", null, pnlGeneral, null); pnlGeneral.setLayout(null); chbTitleGeneral = new JCheckBox("Title"); chbTitleGeneral.setBounds(6, 7, 45, 23); if (!isWindows()) chbTitleGeneral.setBounds(6, 7, 66, 23); pnlGeneral.add(chbTitleGeneral); txtTitleGeneral = new JTextField(); txtTitleGeneral.setEnabled(false); txtTitleGeneral.setBounds(57, 8, 661, 20); if (!isWindows()) txtTitleGeneral.setBounds(78, 8, 640, 20); pnlGeneral.add(txtTitleGeneral); txtTitleGeneral.setColumns(10); cbNumbGeneral = new JCheckBox("Numbering"); cbNumbGeneral.setEnabled(false); cbNumbGeneral.setBounds(16, 37, 104, 23); pnlGeneral.add(cbNumbGeneral); final JLabel lblNumbStartGeneral = new JLabel("Start"); lblNumbStartGeneral.setEnabled(false); lblNumbStartGeneral.setBounds(191, 40, 31, 14); if (!isWindows()) lblNumbStartGeneral.setBounds(191, 40, 45, 14); pnlGeneral.add(lblNumbStartGeneral); txtNumbStartGeneral = new JTextField(); txtNumbStartGeneral.setEnabled(false); txtNumbStartGeneral.setText("1"); txtNumbStartGeneral.setBounds(220, 38, 70, 20); if (!isWindows()) txtNumbStartGeneral.setBounds(232, 38, 70, 20); pnlGeneral.add(txtNumbStartGeneral); txtNumbStartGeneral.setColumns(10); final JLabel lblNumbPadGeneral = new JLabel("Padding"); lblNumbPadGeneral.setEnabled(false); lblNumbPadGeneral.setBounds(322, 40, 45, 14); if (!isWindows()) lblNumbPadGeneral.setBounds(337, 40, 64, 14); pnlGeneral.add(lblNumbPadGeneral); txtNumbPadGeneral = new JTextField(); txtNumbPadGeneral.setEnabled(false); txtNumbPadGeneral.setText("1"); txtNumbPadGeneral.setBounds(366, 38, 70, 20); if (!isWindows()) txtNumbPadGeneral.setBounds(402, 38, 70, 20); pnlGeneral.add(txtNumbPadGeneral); txtNumbPadGeneral.setColumns(10); final JLabel lblNumbExplainGeneral = new JLabel("To use it, add {num} to tittle (e.g. \"My Title {num}\")"); lblNumbExplainGeneral.setEnabled(false); lblNumbExplainGeneral.setBounds(33, 67, 473, 14); pnlGeneral.add(lblNumbExplainGeneral); chbRemoveChapters = new JCheckBox("Remove chapters"); chbRemoveChapters.setBounds(6, 88, 150, 23); pnlGeneral.add(chbRemoveChapters); chbRemoveTags = new JCheckBox("Remove tags"); chbRemoveTags.setBounds(6, 114, 150, 23); pnlGeneral.add(chbRemoveTags); chbExtraCmdGeneral = new JCheckBox("Extra parameters"); chbExtraCmdGeneral.setBounds(6, 140, 114, 23); if (!isWindows()) chbExtraCmdGeneral.setBounds(6, 140, 150, 23); pnlGeneral.add(chbExtraCmdGeneral); txtExtraCmdGeneral = new JTextField(); txtExtraCmdGeneral.setEnabled(false); txtExtraCmdGeneral.setBounds(126, 141, 592, 20); if (!isWindows()) txtExtraCmdGeneral.setBounds(166, 141, 552, 20); pnlGeneral.add(txtExtraCmdGeneral); txtExtraCmdGeneral.setColumns(10); txtMkvPropExe = new JTextField(); txtMkvPropExe.setText("mkvpropedit.exe"); if (!isWindows()) txtMkvPropExe.setText("/usr/bin/mkvpropedit"); txtMkvPropExe.setEditable(false); txtMkvPropExe.setBounds(10, 272, 708, 20); pnlGeneral.add(txtMkvPropExe); txtMkvPropExe.setColumns(10); JLabel lblMkvPropExe = new JLabel("Mkvpropedit executable"); lblMkvPropExe.setBounds(10, 255, 209, 14); pnlGeneral.add(lblMkvPropExe); cbMkvPropExeDef = new JCheckBox("Use default"); cbMkvPropExeDef.setEnabled(false); cbMkvPropExeDef.setSelected(true); cbMkvPropExeDef.setBounds(6, 292, 120, 23); pnlGeneral.add(cbMkvPropExeDef); JButton btnBrowseMkvPropExe = new JButton("Browse..."); btnBrowseMkvPropExe.setBounds(618, 295, 100, 23); if (!isWindows()) btnBrowseMkvPropExe.setBounds(583, 295, 135, 23); pnlGeneral.add(btnBrowseMkvPropExe); final JPanel pnlVideo = new JPanel(); tabbedPane.addTab("Video", null, pnlVideo, null); pnlVideo.setLayout(null); cbVideo = new JComboBox(); cbVideo.setBounds(10, 10, 146, 20); pnlVideo.add(cbVideo); imgRes = ClassLoader.getSystemResource("res/list-add.png"); final JButton btnAddVideo = new JButton(""); btnAddVideo.setIcon(new ImageIcon(imgRes)); btnAddVideo.setBounds(166, 10, 22, 20); pnlVideo.add(btnAddVideo); lyrdPnlVideo = new JLayeredPane(); lyrdPnlVideo.setBounds(0, 38, 728, 294); pnlVideo.add(lyrdPnlVideo); final JPanel pnlAudio = new JPanel(); tabbedPane.addTab("Audio", null, pnlAudio, null); pnlAudio.setLayout(null); cbAudio = new JComboBox(); cbAudio.setBounds(10, 10, 146, 20); pnlAudio.add(cbAudio); final JButton btnAddAudio = new JButton(""); btnAddAudio.setIcon(new ImageIcon(imgRes)); btnAddAudio.setBounds(166, 10, 22, 20); pnlAudio.add(btnAddAudio); lyrdPnlAudio = new JLayeredPane(); lyrdPnlAudio.setBounds(0, 38, 728, 294); pnlAudio.add(lyrdPnlAudio); final JPanel pnlSubtitle = new JPanel(); tabbedPane.addTab("Subtitle", null, pnlSubtitle, null); pnlSubtitle.setLayout(null); cbSubtitle = new JComboBox(); cbSubtitle.setBounds(10, 10, 146, 20); pnlSubtitle.add(cbSubtitle); final JButton btnAddSubtitle = new JButton(""); btnAddSubtitle.setIcon(new ImageIcon(imgRes)); btnAddSubtitle.setBounds(166, 10, 22, 20); pnlSubtitle.add(btnAddSubtitle); lyrdPnlSubtitle = new JLayeredPane(); lyrdPnlSubtitle.setBounds(0, 38, 728, 294); pnlSubtitle.add(lyrdPnlSubtitle); JPanel pnlOutput = new JPanel(); tabbedPane.addTab("Output", null, pnlOutput, null); pnlOutput.setLayout(new BorderLayout(0, 0)); txtOutput = new JTextArea(); txtOutput.setLineWrap(true); txtOutput.setEditable(false); JScrollPane scrollOutput = new JScrollPane(txtOutput); pnlOutput.add(scrollOutput); btnProcessFiles = new JButton("Process files"); btnProcessFiles.setBounds(151, 382, 150, 23); if (!isWindows()) btnProcessFiles.setBounds(94, 382, 235, 23); frmJMkvpropedit.getContentPane().add(btnProcessFiles); btnGenerateCmdLine = new JButton("Generate command line"); btnGenerateCmdLine.setBounds(452, 382, 150, 23); if (!isWindows()) btnGenerateCmdLine.setBounds(423, 382, 235, 23); frmJMkvpropedit.getContentPane().add(btnGenerateCmdLine); frmJMkvpropedit.addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent arg0) { readIniFile(); addVideoTrack(); addAudioTrack(); addSubtitleTrack(); } @Override public void windowClosing(WindowEvent e) { boolean wRunning; try { wRunning = !worker.isDone(); } catch (Exception e1) { wRunning = false; } if (wRunning) { int choice = JOptionPane.showConfirmDialog(frmJMkvpropedit, "Do you really wanna exit?", "", JOptionPane.YES_NO_OPTION); if (choice == JOptionPane.YES_OPTION) { worker.cancel(true); frmJMkvpropedit.dispose(); System.exit(0); } } else { frmJMkvpropedit.dispose(); System.exit(0); } } }); /* Button "Process files" */ btnProcessFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File mkvPropExe = new File(txtMkvPropExe.getText()); if (modelFiles.getSize() == 0) { JOptionPane.showMessageDialog(frmJMkvpropedit, "The file list is empty!", "Empty list", JOptionPane.ERROR_MESSAGE); } else if (!mkvPropExe.exists()) { JOptionPane.showMessageDialog(frmJMkvpropedit, "Mkvpropedit executable not found!" + "\nPlease set the right path for it or copy it to the working folder (default setting).", "Mkvpropedit not found", JOptionPane.ERROR_MESSAGE); } else { setCmdLine(); if (cmdLineBatchOpt.size() == 0) { JOptionPane.showMessageDialog(frmJMkvpropedit, "Nothing to do!", "", JOptionPane.INFORMATION_MESSAGE); } else { executeBatch(); } } } }); /* Button "Generate command line" */ btnGenerateCmdLine.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (modelFiles.getSize() == 0) { JOptionPane.showMessageDialog(frmJMkvpropedit, "The file list is empty!", "Empty list", JOptionPane.ERROR_MESSAGE); } else { setCmdLine(); if (cmdLineBatch.size() == 0) { JOptionPane.showMessageDialog(frmJMkvpropedit, "Nothing to do!", "", JOptionPane.INFORMATION_MESSAGE); } else { txtOutput.setText(""); if (cmdLineBatch.size() > 0) { for (int i = 0; i < modelFiles.size(); i++) { txtOutput.append(cmdLineBatch.get(i) + "\n"); } tabbedPane.setSelectedIndex(tabbedPane.getTabCount()-1); } } } } }); new FileDrop(listFiles, new FileDrop.Listener() { public void filesDropped(java.io.File[] files) { for (int i = 0; i < files.length; i++) { try { FileFilter filter = new FileNameExtensionFilter("Matroska files (*.mkv; *.mka; *.mk3d) ", "mkv", "mka", "mk3d"); if (!modelFiles.contains(files[i].getCanonicalPath()) && filter.accept(files[i]) && !files[i].isDirectory()) modelFiles.add(modelFiles.getSize(), files[i].getCanonicalPath()); } catch(java.io.IOException e) { } } } }); btnAddFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File[] files = null; chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setDialogTitle("Select Matroska file to edit"); chooser.setMultiSelectionEnabled(true); FileFilter filter = new FileNameExtensionFilter("Matroska files (*.mkv; *.mka; *.mk3d) ", "mkv", "mka", "mk3d"); chooser.resetChoosableFileFilters(); chooser.setFileFilter(filter); int open = chooser.showOpenDialog(frmJMkvpropedit); if (open == JFileChooser.APPROVE_OPTION) { files = chooser.getSelectedFiles(); for (int i = 0; i < files.length; i++) { try { if (!modelFiles.contains(files[i].getCanonicalPath())) modelFiles.add(modelFiles.getSize(), files[i].getCanonicalPath()); } catch (IOException e1) { } } } } }); btnRemoveFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (modelFiles.getSize() > 0) { while (listFiles.getSelectedIndex() != -1) { int[] idx = listFiles.getSelectedIndices(); modelFiles.remove(idx[0]); } } } }); btnClearFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { modelFiles.removeAllElements(); } }); btnTopFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] idx = listFiles.getSelectedIndices(); for (int i = 0; i < idx.length; i++) { int pos = idx[i]; if (pos > 0) { String temp = (String)modelFiles.remove(pos); modelFiles.add(i, temp); listFiles.ensureIndexIsVisible(0); idx[i] = i; } } listFiles.setSelectedIndices(idx); } }); btnUpFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] idx = listFiles.getSelectedIndices(); for (int i = 0; i < idx.length; i++) { int pos = idx[i]; if (pos > 0 && listFiles.getMinSelectionIndex() != 0) { String temp = (String)modelFiles.remove(pos); modelFiles.add(pos-1, temp); listFiles.ensureIndexIsVisible(pos-1); idx[i]--; } } listFiles.setSelectedIndices(idx); } }); btnDownFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] idx = listFiles.getSelectedIndices(); for (int i = idx.length-1; i > -1; i--) { int pos = idx[i]; if (pos < modelFiles.getSize()-1 && listFiles.getMaxSelectionIndex() != modelFiles.getSize()-1) { String temp = (String)modelFiles.remove(pos); modelFiles.add(pos+1, temp); listFiles.ensureIndexIsVisible(pos+1); idx[i]++; } } listFiles.setSelectedIndices(idx); } }); btnBottomFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] idx = listFiles.getSelectedIndices(); int j = 0; for (int i = idx.length-1; i > -1; i--) { int pos = idx[i]; if (pos < modelFiles.getSize()-1 && listFiles.getMaxSelectionIndex() != modelFiles.getSize()-1) { String temp = (String)modelFiles.remove(pos); modelFiles.add(modelFiles.getSize()-j, temp); j++; listFiles.ensureIndexIsVisible(modelFiles.getSize()-1); idx[i] = modelFiles.getSize()-j; } } listFiles.setSelectedIndices(idx); } }); chbTitleGeneral.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean state = txtTitleGeneral.isEnabled(); if (txtTitleGeneral.isEnabled() || chbTitleGeneral.isSelected()) { txtTitleGeneral.setEnabled(!state); cbNumbGeneral.setEnabled(!state); if (cbNumbGeneral.isSelected()) { lblNumbStartGeneral.setEnabled(!state); txtNumbStartGeneral.setEnabled(!state); lblNumbPadGeneral.setEnabled(!state); txtNumbPadGeneral.setEnabled(!state); lblNumbExplainGeneral.setEnabled(!state); } } } }); cbNumbGeneral.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean state = txtNumbStartGeneral.isEnabled(); lblNumbStartGeneral.setEnabled(!state); txtNumbStartGeneral.setEnabled(!state); lblNumbPadGeneral.setEnabled(!state); txtNumbPadGeneral.setEnabled(!state); lblNumbExplainGeneral.setEnabled(!state); } }); txtNumbStartGeneral.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { try { if (Integer.parseInt(txtNumbStartGeneral.getText()) < 0) txtNumbStartGeneral.setText("1"); } catch (NumberFormatException e1) { txtNumbStartGeneral.setText("1"); } } }); txtNumbPadGeneral.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { try { if (Integer.parseInt(txtNumbPadGeneral.getText()) < 0) txtNumbPadGeneral.setText("1"); } catch (NumberFormatException e1) { txtNumbPadGeneral.setText("1"); } } }); chbExtraCmdGeneral.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean state = txtExtraCmdGeneral.isEnabled(); txtExtraCmdGeneral.setEnabled(!state); } }); btnBrowseMkvPropExe.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setDialogTitle("Select mkvpropedit executable"); chooser.setMultiSelectionEnabled(false); FileFilter filter = new FileNameExtensionFilter("Excecutable files (*.exe)", "exe"); chooser.resetChoosableFileFilters(); chooser.setFileFilter(filter); int open = chooser.showOpenDialog(frmJMkvpropedit); if (open == JFileChooser.APPROVE_OPTION) { saveIniFile(chooser.getSelectedFile()); } } }); cbMkvPropExeDef.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (isWindows()) { txtMkvPropExe.setText("mkvpropedit.exe"); cbMkvPropExeDef.setEnabled(false); defaultIniFile(); } else { txtMkvPropExe.setText("/usr/bin/mkvpropedit"); cbMkvPropExeDef.setEnabled(false); defaultIniFile(); } } }); cbVideo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (cbVideo.getItemCount() != 0) lyrdPnlVideo.moveToFront(subPnlVideo[cbVideo.getSelectedIndex()]); } }); btnAddVideo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addVideoTrack(); cbVideo.setSelectedIndex(cbVideo.getItemCount()-1); if (cbVideo.getItemCount() == maxStreams) { btnAddVideo.setEnabled(false); } } }); cbAudio.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (cbAudio.getItemCount() != 0) lyrdPnlAudio.moveToFront(subPnlAudio[cbAudio.getSelectedIndex()]); } }); btnAddAudio.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addAudioTrack(); cbAudio.setSelectedIndex(cbAudio.getItemCount()-1); if (cbAudio.getItemCount() == maxStreams) { btnAddAudio.setEnabled(false); } } }); cbSubtitle.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (cbSubtitle.getItemCount() != 0) lyrdPnlSubtitle.moveToFront(subPnlSubtitle[cbSubtitle.getSelectedIndex()]); } }); btnAddSubtitle.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addSubtitleTrack(); cbSubtitle.setSelectedIndex(cbSubtitle.getItemCount()-1); if (cbSubtitle.getItemCount() == maxStreams) { btnAddSubtitle.setEnabled(false); } } }); } /* Start of track addition operations */ private void addVideoTrack() { if (nVideo < maxStreams) { subPnlVideo[nVideo] = new JPanel(); subPnlVideo[nVideo].setBounds(0, 0, 728, 294); lyrdPnlVideo.add(subPnlVideo[nVideo]); subPnlVideo[nVideo].setLayout(null); chbEditVideo[nVideo] = new JCheckBox("Edit this track"); chbEditVideo[nVideo].setBounds(6, 7, 139, 23); subPnlVideo[nVideo].add(chbEditVideo[nVideo]); chbDefaultVideo[nVideo] = new JCheckBox("Default track"); chbDefaultVideo[nVideo].setEnabled(false); chbDefaultVideo[nVideo].setBounds(6, 32, 91, 23); if (!isWindows()) chbDefaultVideo[nVideo].setBounds(6, 32, 120, 23); subPnlVideo[nVideo].add(chbDefaultVideo[nVideo]); rbYesDefVideo[nVideo] = new JRadioButton("Yes"); rbYesDefVideo[nVideo].setSelected(true); rbYesDefVideo[nVideo].setBounds(99, 32, 46, 23); if (!isWindows()) rbYesDefVideo[nVideo].setBounds(131, 32, 55, 23); rbYesDefVideo[nVideo].setEnabled(false); subPnlVideo[nVideo].add(rbYesDefVideo[nVideo]); rbNoDefVideo[nVideo] = new JRadioButton("No"); rbNoDefVideo[nVideo].setBounds(143, 32, 46, 23); if (!isWindows()) rbNoDefVideo[nVideo].setBounds(194, 32, 46, 23); rbNoDefVideo[nVideo].setEnabled(false); subPnlVideo[nVideo].add(rbNoDefVideo[nVideo]); bgRbDefVideo[nVideo] = new ButtonGroup(); bgRbDefVideo[nVideo].add(rbYesDefVideo[nVideo]); bgRbDefVideo[nVideo].add(rbNoDefVideo[nVideo]); chbForcedVideo[nVideo] = new JCheckBox("Forced track"); chbForcedVideo[nVideo].setEnabled(false); chbForcedVideo[nVideo].setBounds(6, 57, 85, 23); if (!isWindows()) chbForcedVideo[nVideo].setBounds(6, 57, 120, 23); subPnlVideo[nVideo].add(chbForcedVideo[nVideo]); rbYesForcedVideo[nVideo] = new JRadioButton("Yes"); rbYesForcedVideo[nVideo].setSelected(true); rbYesForcedVideo[nVideo].setBounds(99, 57, 46, 23); if (!isWindows()) rbYesForcedVideo[nVideo].setBounds(131, 57, 55, 23); rbYesForcedVideo[nVideo].setEnabled(false); subPnlVideo[nVideo].add(rbYesForcedVideo[nVideo]); rbNoForcedVideo[nVideo] = new JRadioButton("No"); rbNoForcedVideo[nVideo].setBounds(143, 57, 46, 23); if (!isWindows()) rbNoForcedVideo[nVideo].setBounds(194, 57, 46, 23); rbNoForcedVideo[nVideo].setEnabled(false); subPnlVideo[nVideo].add(rbNoForcedVideo[nVideo]); bgRbForcedVideo[nVideo] = new ButtonGroup(); bgRbForcedVideo[nVideo].add(rbYesForcedVideo[nVideo]); bgRbForcedVideo[nVideo].add(rbNoForcedVideo[nVideo]); chbNameVideo[nVideo] = new JCheckBox("Track name"); chbNameVideo[nVideo].setEnabled(false); chbNameVideo[nVideo].setBounds(6, 82, 81, 23); if (!isWindows()) chbNameVideo[nVideo].setBounds(6, 82, 114, 23); subPnlVideo[nVideo].add(chbNameVideo[nVideo]); txtNameVideo[nVideo] = new JTextField(); txtNameVideo[nVideo].setEnabled(false); txtNameVideo[nVideo].setBounds(93, 83, 625, 20); if (!isWindows()) txtNameVideo[nVideo].setBounds(123, 83, 595, 20); subPnlVideo[nVideo].add(txtNameVideo[nVideo]); txtNameVideo[nVideo].setColumns(10); cbNumbVideo[nVideo] = new JCheckBox("Numbering"); cbNumbVideo[nVideo].setEnabled(false); cbNumbVideo[nVideo].setBounds(16, 113, 81, 23); if (!isWindows()) cbNumbVideo[nVideo].setBounds(16, 113, 104, 23); subPnlVideo[nVideo].add(cbNumbVideo[nVideo]); lblNumbStartVideo[nVideo] = new JLabel("Start"); lblNumbStartVideo[nVideo].setEnabled(false); lblNumbStartVideo[nVideo].setBounds(191, 115, 31, 14); if (!isWindows()) lblNumbStartVideo[nVideo].setBounds(191, 115, 45, 14); subPnlVideo[nVideo].add(lblNumbStartVideo[nVideo]); txtNumbStartVideo[nVideo] = new JTextField(); txtNumbStartVideo[nVideo].setEnabled(false); txtNumbStartVideo[nVideo].setText("1"); txtNumbStartVideo[nVideo].setBounds(220, 113, 70, 20); if (!isWindows()) txtNumbStartVideo[nVideo].setBounds(232, 113, 70, 20); subPnlVideo[nVideo].add(txtNumbStartVideo[nVideo]); txtNumbStartVideo[nVideo].setColumns(10); lblNumbPadVideo[nVideo] = new JLabel("Padding"); lblNumbPadVideo[nVideo].setEnabled(false); lblNumbPadVideo[nVideo].setBounds(322, 115, 45, 14); if (!isWindows()) lblNumbPadVideo[nVideo].setBounds(337, 115, 64, 14); subPnlVideo[nVideo].add(lblNumbPadVideo[nVideo]); txtNumbPadVideo[nVideo] = new JTextField(); txtNumbPadVideo[nVideo].setEnabled(false); txtNumbPadVideo[nVideo].setText("1"); txtNumbPadVideo[nVideo].setBounds(366, 113, 70, 20); if (!isWindows()) txtNumbPadVideo[nVideo].setBounds(402, 113, 70, 20); subPnlVideo[nVideo].add(txtNumbPadVideo[nVideo]); txtNumbPadVideo[nVideo].setColumns(10); lblNumbExplainVideo[nVideo] = new JLabel("To use it, add {num} to track name (e.g. \"My Video {num}\")"); lblNumbExplainVideo[nVideo].setEnabled(false); lblNumbExplainVideo[nVideo].setBounds(33, 143, 473, 14); if (!isWindows()) lblNumbExplainVideo[nVideo].setBounds(33, 143, 473, 14); subPnlVideo[nVideo].add(lblNumbExplainVideo[nVideo]); chbLangVideo[nVideo] = new JCheckBox("Language"); chbLangVideo[nVideo].setEnabled(false); chbLangVideo[nVideo].setBounds(6, 164, 73, 23); if (!isWindows()) chbLangVideo[nVideo].setBounds(6, 164, 104, 23); subPnlVideo[nVideo].add(chbLangVideo[nVideo]); cbLangVideo[nVideo] = new JComboBox(); cbLangVideo[nVideo].setEnabled(false); cbLangVideo[nVideo].setBounds(93, 164, 430, 20); if (!isWindows()) cbLangVideo[nVideo].setBounds(123, 164, 595, 20); cbLangVideo[nVideo].setModel(new DefaultComboBoxModel(mkvLang.getLangName())); subPnlVideo[nVideo].add(cbLangVideo[nVideo]); int pos = mkvLang.getAsLangCode().indexOf("und"); cbLangVideo[nVideo].setSelectedIndex(pos); chbExtraCmdVideo[nVideo] = new JCheckBox("Extra parameters"); chbExtraCmdVideo[nVideo].setEnabled(false); chbExtraCmdVideo[nVideo].setBounds(6, 190, 109, 23); if (!isWindows()) chbExtraCmdVideo[nVideo].setBounds(6, 190, 153, 23); subPnlVideo[nVideo].add(chbExtraCmdVideo[nVideo]); txtExtraCmdVideo[nVideo] = new JTextField(); txtExtraCmdVideo[nVideo].setEnabled(false); txtExtraCmdVideo[nVideo].setBounds(126, 191, 592, 20); if (!isWindows()) txtExtraCmdVideo[nVideo].setBounds(165, 191, 553, 20); subPnlVideo[nVideo].add(txtExtraCmdVideo[nVideo]); txtExtraCmdVideo[nVideo].setColumns(10); chbEditVideo[nVideo].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); boolean state = chbDefaultVideo[curCbVideo].isEnabled(); chbDefaultVideo[curCbVideo].setEnabled(!state); chbForcedVideo[curCbVideo].setEnabled(!state); chbNameVideo[curCbVideo].setEnabled(!state); chbLangVideo[curCbVideo].setEnabled(!state); chbExtraCmdVideo[curCbVideo].setEnabled(!state); if (txtNameVideo[curCbVideo].isEnabled() || chbNameVideo[curCbVideo].isSelected()) { txtNameVideo[curCbVideo].setEnabled(!state); cbNumbVideo[curCbVideo].setEnabled(!state); if (cbNumbVideo[curCbVideo].isSelected()) { lblNumbStartVideo[curCbVideo].setEnabled(!state); txtNumbStartVideo[curCbVideo].setEnabled(!state); lblNumbPadVideo[curCbVideo].setEnabled(!state); txtNumbPadVideo[curCbVideo].setEnabled(!state); lblNumbExplainVideo[curCbVideo].setEnabled(!state); } } if (rbNoDefVideo[curCbVideo].isEnabled() || chbDefaultVideo[curCbVideo].isSelected()) { rbNoDefVideo[curCbVideo].setEnabled(!state); rbYesDefVideo[curCbVideo].setEnabled(!state); } if (rbNoForcedVideo[curCbVideo].isEnabled() || chbForcedVideo[curCbVideo].isSelected()) { rbNoForcedVideo[curCbVideo].setEnabled(!state); rbYesForcedVideo[curCbVideo].setEnabled(!state); } if (cbLangVideo[curCbVideo].isEnabled() || chbLangVideo[curCbVideo].isSelected()) { cbLangVideo[curCbVideo].setEnabled(!state); } if (txtExtraCmdVideo[curCbVideo].isEnabled() || chbExtraCmdVideo[curCbVideo].isSelected()) { chbExtraCmdVideo[curCbVideo].setEnabled(!state); txtExtraCmdVideo[curCbVideo].setEnabled(!state); } } }); chbNameVideo[nVideo].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); boolean state = cbNumbVideo[curCbVideo].isEnabled(); cbNumbVideo[curCbVideo].setEnabled(!state); txtNameVideo[curCbVideo].setEnabled(!state); if (cbNumbVideo[curCbVideo].isSelected()) { lblNumbStartVideo[curCbVideo].setEnabled(!state); txtNumbStartVideo[curCbVideo].setEnabled(!state); lblNumbPadVideo[curCbVideo].setEnabled(!state); txtNumbPadVideo[curCbVideo].setEnabled(!state); lblNumbExplainVideo[curCbVideo].setEnabled(!state); } } }); chbDefaultVideo[nVideo].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); boolean state = rbNoDefVideo[curCbVideo].isEnabled(); rbNoDefVideo[curCbVideo].setEnabled(!state); rbYesDefVideo[curCbVideo].setEnabled(!state); } }); chbForcedVideo[nVideo].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); boolean state = rbNoForcedVideo[curCbVideo].isEnabled(); rbNoForcedVideo[curCbVideo].setEnabled(!state); rbYesForcedVideo[curCbVideo].setEnabled(!state); } }); cbNumbVideo[nVideo].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); boolean state = txtNumbStartVideo[curCbVideo].isEnabled(); lblNumbStartVideo[curCbVideo].setEnabled(!state); txtNumbStartVideo[curCbVideo].setEnabled(!state); lblNumbPadVideo[curCbVideo].setEnabled(!state); txtNumbPadVideo[curCbVideo].setEnabled(!state); lblNumbExplainVideo[curCbVideo].setEnabled(!state); } }); chbLangVideo[nVideo].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); boolean state = cbLangVideo[curCbVideo].isEnabled(); cbLangVideo[curCbVideo].setEnabled(!state); } }); txtNumbStartVideo[nVideo].addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); try { if (Integer.parseInt(txtNumbStartVideo[curCbVideo].getText()) < 0) txtNumbStartVideo[curCbVideo].setText("1"); } catch (NumberFormatException e1) { txtNumbStartVideo[curCbVideo].setText("1"); } } }); txtNumbPadVideo[nVideo].addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); try { if (Integer.parseInt(txtNumbPadVideo[curCbVideo].getText()) < 0) txtNumbPadVideo[curCbVideo].setText("1"); } catch (NumberFormatException e1) { txtNumbPadVideo[curCbVideo].setText("1"); } } }); chbExtraCmdVideo[nVideo].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); boolean state = txtExtraCmdVideo[curCbVideo].isEnabled(); txtExtraCmdVideo[curCbVideo].setEnabled(!state); } }); cbVideo.addItem("Video Track " + (nVideo+1)); } nVideo++; } private void addAudioTrack() { if (nAudio < maxStreams) { subPnlAudio[nAudio] = new JPanel(); subPnlAudio[nAudio].setBounds(0, 0, 728, 294); lyrdPnlAudio.add(subPnlAudio[nAudio]); subPnlAudio[nAudio].setLayout(null); chbEditAudio[nAudio] = new JCheckBox("Edit this track"); chbEditAudio[nAudio].setBounds(6, 7, 139, 23); subPnlAudio[nAudio].add(chbEditAudio[nAudio]); chbDefaultAudio[nAudio] = new JCheckBox("Default track"); chbDefaultAudio[nAudio].setEnabled(false); chbDefaultAudio[nAudio].setBounds(6, 32, 91, 23); if (!isWindows()) chbDefaultAudio[nAudio].setBounds(6, 32, 120, 23); subPnlAudio[nAudio].add(chbDefaultAudio[nAudio]); rbYesDefAudio[nAudio] = new JRadioButton("Yes"); rbYesDefAudio[nAudio].setSelected(true); rbYesDefAudio[nAudio].setBounds(99, 32, 46, 23); if (!isWindows()) rbYesDefAudio[nAudio].setBounds(131, 32, 55, 23); rbYesDefAudio[nAudio].setEnabled(false); subPnlAudio[nAudio].add(rbYesDefAudio[nAudio]); rbNoDefAudio[nAudio] = new JRadioButton("No"); rbNoDefAudio[nAudio].setBounds(143, 32, 46, 23); if (!isWindows()) rbNoDefAudio[nAudio].setBounds(194, 32, 46, 23); rbNoDefAudio[nAudio].setEnabled(false); subPnlAudio[nAudio].add(rbNoDefAudio[nAudio]); bgRbDefAudio[nAudio] = new ButtonGroup(); bgRbDefAudio[nAudio].add(rbYesDefAudio[nAudio]); bgRbDefAudio[nAudio].add(rbNoDefAudio[nAudio]); chbForcedAudio[nAudio] = new JCheckBox("Forced track"); chbForcedAudio[nAudio].setEnabled(false); chbForcedAudio[nAudio].setBounds(6, 57, 85, 23); if (!isWindows()) chbForcedAudio[nAudio].setBounds(6, 57, 120, 23); subPnlAudio[nAudio].add(chbForcedAudio[nAudio]); rbYesForcedAudio[nAudio] = new JRadioButton("Yes"); rbYesForcedAudio[nAudio].setSelected(true); rbYesForcedAudio[nAudio].setBounds(99, 57, 46, 23); if (!isWindows()) rbYesForcedAudio[nAudio].setBounds(131, 57, 55, 23); rbYesForcedAudio[nAudio].setEnabled(false); subPnlAudio[nAudio].add(rbYesForcedAudio[nAudio]); rbNoForcedAudio[nAudio] = new JRadioButton("No"); rbNoForcedAudio[nAudio].setBounds(143, 57, 46, 23); if (!isWindows()) rbNoForcedAudio[nAudio].setBounds(194, 57, 46, 23); rbNoForcedAudio[nAudio].setEnabled(false); subPnlAudio[nAudio].add(rbNoForcedAudio[nAudio]); bgRbForcedAudio[nAudio] = new ButtonGroup(); bgRbForcedAudio[nAudio].add(rbYesForcedAudio[nAudio]); bgRbForcedAudio[nAudio].add(rbNoForcedAudio[nAudio]); chbNameAudio[nAudio] = new JCheckBox("Track name"); chbNameAudio[nAudio].setEnabled(false); chbNameAudio[nAudio].setBounds(6, 82, 81, 23); if (!isWindows()) chbNameAudio[nAudio].setBounds(6, 82, 114, 23); subPnlAudio[nAudio].add(chbNameAudio[nAudio]); txtNameAudio[nAudio] = new JTextField(); txtNameAudio[nAudio].setEnabled(false); txtNameAudio[nAudio].setBounds(93, 83, 625, 20); if (!isWindows()) txtNameAudio[nAudio].setBounds(123, 83, 595, 20); subPnlAudio[nAudio].add(txtNameAudio[nAudio]); txtNameAudio[nAudio].setColumns(10); cbNumbAudio[nAudio] = new JCheckBox("Numbering"); cbNumbAudio[nAudio].setEnabled(false); cbNumbAudio[nAudio].setBounds(16, 113, 81, 23); if (!isWindows()) cbNumbAudio[nAudio].setBounds(16, 113, 104, 23); subPnlAudio[nAudio].add(cbNumbAudio[nAudio]); lblNumbStartAudio[nAudio] = new JLabel("Start"); lblNumbStartAudio[nAudio].setEnabled(false); lblNumbStartAudio[nAudio].setBounds(191, 115, 31, 14); if (!isWindows()) lblNumbStartAudio[nAudio].setBounds(191, 115, 45, 14); subPnlAudio[nAudio].add(lblNumbStartAudio[nAudio]); txtNumbStartAudio[nAudio] = new JTextField(); txtNumbStartAudio[nAudio].setEnabled(false); txtNumbStartAudio[nAudio].setText("1"); txtNumbStartAudio[nAudio].setBounds(220, 113, 70, 20); if (!isWindows()) txtNumbStartAudio[nAudio].setBounds(232, 113, 70, 20); subPnlAudio[nAudio].add(txtNumbStartAudio[nAudio]); txtNumbStartAudio[nAudio].setColumns(10); lblNumbPadAudio[nAudio] = new JLabel("Padding"); lblNumbPadAudio[nAudio].setEnabled(false); lblNumbPadAudio[nAudio].setBounds(322, 115, 45, 14); if (!isWindows()) lblNumbPadAudio[nAudio].setBounds(337, 115, 64, 14); subPnlAudio[nAudio].add(lblNumbPadAudio[nAudio]); txtNumbPadAudio[nAudio] = new JTextField(); txtNumbPadAudio[nAudio].setEnabled(false); txtNumbPadAudio[nAudio].setText("1"); txtNumbPadAudio[nAudio].setBounds(366, 113, 70, 20); if (!isWindows()) txtNumbPadAudio[nAudio].setBounds(402, 113, 70, 20); subPnlAudio[nAudio].add(txtNumbPadAudio[nAudio]); txtNumbPadAudio[nAudio].setColumns(10); lblNumbExplainAudio[nAudio] = new JLabel("To use it, add {num} to track name (e.g. \"My Audio {num}\")"); lblNumbExplainAudio[nAudio].setEnabled(false); lblNumbExplainAudio[nAudio].setBounds(33, 143, 473, 14); if (!isWindows()) lblNumbExplainAudio[nAudio].setBounds(33, 143, 473, 14); subPnlAudio[nAudio].add(lblNumbExplainAudio[nAudio]); chbLangAudio[nAudio] = new JCheckBox("Language"); chbLangAudio[nAudio].setEnabled(false); chbLangAudio[nAudio].setBounds(6, 164, 73, 23); if (!isWindows()) chbLangAudio[nAudio].setBounds(6, 164, 104, 23); subPnlAudio[nAudio].add(chbLangAudio[nAudio]); cbLangAudio[nAudio] = new JComboBox(); cbLangAudio[nAudio].setEnabled(false); cbLangAudio[nAudio].setBounds(93, 164, 430, 20); if (!isWindows()) cbLangAudio[nAudio].setBounds(123, 164, 595, 20); cbLangAudio[nAudio].setModel(new DefaultComboBoxModel(mkvLang.getLangName())); subPnlAudio[nAudio].add(cbLangAudio[nAudio]); int pos = mkvLang.getAsLangCode().indexOf("und"); cbLangAudio[nAudio].setSelectedIndex(pos); chbExtraCmdAudio[nAudio] = new JCheckBox("Extra parameters"); chbExtraCmdAudio[nAudio].setEnabled(false); chbExtraCmdAudio[nAudio].setBounds(6, 190, 109, 23); if (!isWindows()) chbExtraCmdAudio[nAudio].setBounds(6, 190, 153, 23); subPnlAudio[nAudio].add(chbExtraCmdAudio[nAudio]); txtExtraCmdAudio[nAudio] = new JTextField(); txtExtraCmdAudio[nAudio].setEnabled(false); txtExtraCmdAudio[nAudio].setBounds(126, 191, 592, 20); if (!isWindows()) txtExtraCmdAudio[nAudio].setBounds(165, 191, 553, 20); subPnlAudio[nAudio].add(txtExtraCmdAudio[nAudio]); txtExtraCmdAudio[nAudio].setColumns(10); chbEditAudio[nAudio].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); boolean state = chbDefaultAudio[curCbAudio].isEnabled(); chbDefaultAudio[curCbAudio].setEnabled(!state); chbForcedAudio[curCbAudio].setEnabled(!state); chbNameAudio[curCbAudio].setEnabled(!state); chbLangAudio[curCbAudio].setEnabled(!state); chbExtraCmdAudio[curCbAudio].setEnabled(!state); if (txtNameAudio[curCbAudio].isEnabled() || chbNameAudio[curCbAudio].isSelected()) { txtNameAudio[curCbAudio].setEnabled(!state); cbNumbAudio[curCbAudio].setEnabled(!state); if (cbNumbAudio[curCbAudio].isSelected()) { lblNumbStartAudio[curCbAudio].setEnabled(!state); txtNumbStartAudio[curCbAudio].setEnabled(!state); lblNumbPadAudio[curCbAudio].setEnabled(!state); txtNumbPadAudio[curCbAudio].setEnabled(!state); lblNumbExplainAudio[curCbAudio].setEnabled(!state); } } if (rbNoDefAudio[curCbAudio].isEnabled() || chbDefaultAudio[curCbAudio].isSelected()) { rbNoDefAudio[curCbAudio].setEnabled(!state); rbYesDefAudio[curCbAudio].setEnabled(!state); } if (rbNoForcedAudio[curCbAudio].isEnabled() || chbForcedAudio[curCbAudio].isSelected()) { rbNoForcedAudio[curCbAudio].setEnabled(!state); rbYesForcedAudio[curCbAudio].setEnabled(!state); } if (cbLangAudio[curCbAudio].isEnabled() || chbLangAudio[curCbAudio].isSelected()) { cbLangAudio[curCbAudio].setEnabled(!state); } if (txtExtraCmdAudio[curCbAudio].isEnabled() || chbExtraCmdAudio[curCbAudio].isSelected()) { chbExtraCmdAudio[curCbAudio].setEnabled(!state); txtExtraCmdAudio[curCbAudio].setEnabled(!state); } } }); chbNameAudio[nAudio].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); boolean state = cbNumbAudio[curCbAudio].isEnabled(); cbNumbAudio[curCbAudio].setEnabled(!state); txtNameAudio[curCbAudio].setEnabled(!state); if (cbNumbAudio[curCbAudio].isSelected()) { lblNumbStartAudio[curCbAudio].setEnabled(!state); txtNumbStartAudio[curCbAudio].setEnabled(!state); lblNumbPadAudio[curCbAudio].setEnabled(!state); txtNumbPadAudio[curCbAudio].setEnabled(!state); lblNumbExplainAudio[curCbAudio].setEnabled(!state); } } }); chbDefaultAudio[nAudio].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); boolean state = rbNoDefAudio[curCbAudio].isEnabled(); rbNoDefAudio[curCbAudio].setEnabled(!state); rbYesDefAudio[curCbAudio].setEnabled(!state); } }); chbForcedAudio[nAudio].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); boolean state = rbNoForcedAudio[curCbAudio].isEnabled(); rbNoForcedAudio[curCbAudio].setEnabled(!state); rbYesForcedAudio[curCbAudio].setEnabled(!state); } }); cbNumbAudio[nAudio].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); boolean state = txtNumbStartAudio[curCbAudio].isEnabled(); lblNumbStartAudio[curCbAudio].setEnabled(!state); txtNumbStartAudio[curCbAudio].setEnabled(!state); lblNumbPadAudio[curCbAudio].setEnabled(!state); txtNumbPadAudio[curCbAudio].setEnabled(!state); lblNumbExplainAudio[curCbAudio].setEnabled(!state); } }); chbLangAudio[nAudio].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); boolean state = cbLangAudio[curCbAudio].isEnabled(); cbLangAudio[curCbAudio].setEnabled(!state); } }); txtNumbStartAudio[nAudio].addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); try { if (Integer.parseInt(txtNumbStartAudio[curCbAudio].getText()) < 0) txtNumbStartAudio[curCbAudio].setText("1"); } catch (NumberFormatException e1) { txtNumbStartAudio[curCbAudio].setText("1"); } } }); txtNumbPadAudio[nAudio].addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); try { if (Integer.parseInt(txtNumbPadAudio[curCbAudio].getText()) < 0) txtNumbPadAudio[curCbAudio].setText("1"); } catch (NumberFormatException e1) { txtNumbPadAudio[curCbAudio].setText("1"); } } }); chbExtraCmdAudio[nAudio].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); boolean state = txtExtraCmdAudio[curCbAudio].isEnabled(); txtExtraCmdAudio[curCbAudio].setEnabled(!state); } }); cbAudio.addItem("Audio Track " + (nAudio+1)); } nAudio++; } private void addSubtitleTrack() { if (nSubtitle < maxStreams) { subPnlSubtitle[nSubtitle] = new JPanel(); subPnlSubtitle[nSubtitle].setBounds(0, 0, 728, 294); lyrdPnlSubtitle.add(subPnlSubtitle[nSubtitle]); subPnlSubtitle[nSubtitle].setLayout(null); chbEditSubtitle[nSubtitle] = new JCheckBox("Edit this track"); chbEditSubtitle[nSubtitle].setBounds(6, 7, 139, 23); subPnlSubtitle[nSubtitle].add(chbEditSubtitle[nSubtitle]); chbDefaultSubtitle[nSubtitle] = new JCheckBox("Default track"); chbDefaultSubtitle[nSubtitle].setEnabled(false); chbDefaultSubtitle[nSubtitle].setBounds(6, 32, 91, 23); if (!isWindows()) chbDefaultSubtitle[nSubtitle].setBounds(6, 32, 120, 23); subPnlSubtitle[nSubtitle].add(chbDefaultSubtitle[nSubtitle]); rbYesDefSubtitle[nSubtitle] = new JRadioButton("Yes"); rbYesDefSubtitle[nSubtitle].setSelected(true); rbYesDefSubtitle[nSubtitle].setBounds(99, 32, 46, 23); if (!isWindows()) rbYesDefSubtitle[nSubtitle].setBounds(131, 32, 55, 23); rbYesDefSubtitle[nSubtitle].setEnabled(false); subPnlSubtitle[nSubtitle].add(rbYesDefSubtitle[nSubtitle]); rbNoDefSubtitle[nSubtitle] = new JRadioButton("No"); rbNoDefSubtitle[nSubtitle].setBounds(143, 32, 46, 23); if (!isWindows()) rbNoDefSubtitle[nSubtitle].setBounds(194, 32, 46, 23); rbNoDefSubtitle[nSubtitle].setEnabled(false); subPnlSubtitle[nSubtitle].add(rbNoDefSubtitle[nSubtitle]); bgRbDefSubtitle[nSubtitle] = new ButtonGroup(); bgRbDefSubtitle[nSubtitle].add(rbYesDefSubtitle[nSubtitle]); bgRbDefSubtitle[nSubtitle].add(rbNoDefSubtitle[nSubtitle]); chbForcedSubtitle[nSubtitle] = new JCheckBox("Forced track"); chbForcedSubtitle[nSubtitle].setEnabled(false); chbForcedSubtitle[nSubtitle].setBounds(6, 57, 85, 23); if (!isWindows()) chbForcedSubtitle[nSubtitle].setBounds(6, 57, 120, 23); subPnlSubtitle[nSubtitle].add(chbForcedSubtitle[nSubtitle]); rbYesForcedSubtitle[nSubtitle] = new JRadioButton("Yes"); rbYesForcedSubtitle[nSubtitle].setSelected(true); rbYesForcedSubtitle[nSubtitle].setBounds(99, 57, 46, 23); if (!isWindows()) rbYesForcedSubtitle[nSubtitle].setBounds(131, 57, 55, 23); rbYesForcedSubtitle[nSubtitle].setEnabled(false); subPnlSubtitle[nSubtitle].add(rbYesForcedSubtitle[nSubtitle]); rbNoForcedSubtitle[nSubtitle] = new JRadioButton("No"); rbNoForcedSubtitle[nSubtitle].setBounds(143, 57, 46, 23); if (!isWindows()) rbNoForcedSubtitle[nSubtitle].setBounds(194, 57, 46, 23); rbNoForcedSubtitle[nSubtitle].setEnabled(false); subPnlSubtitle[nSubtitle].add(rbNoForcedSubtitle[nSubtitle]); bgRbForcedSubtitle[nSubtitle] = new ButtonGroup(); bgRbForcedSubtitle[nSubtitle].add(rbYesForcedSubtitle[nSubtitle]); bgRbForcedSubtitle[nSubtitle].add(rbNoForcedSubtitle[nSubtitle]); chbNameSubtitle[nSubtitle] = new JCheckBox("Track name"); chbNameSubtitle[nSubtitle].setEnabled(false); chbNameSubtitle[nSubtitle].setBounds(6, 82, 81, 23); if (!isWindows()) chbNameSubtitle[nSubtitle].setBounds(6, 82, 114, 23); subPnlSubtitle[nSubtitle].add(chbNameSubtitle[nSubtitle]); txtNameSubtitle[nSubtitle] = new JTextField(); txtNameSubtitle[nSubtitle].setEnabled(false); txtNameSubtitle[nSubtitle].setBounds(93, 83, 625, 20); if (!isWindows()) txtNameSubtitle[nSubtitle].setBounds(123, 83, 595, 20); subPnlSubtitle[nSubtitle].add(txtNameSubtitle[nSubtitle]); txtNameSubtitle[nSubtitle].setColumns(10); cbNumbSubtitle[nSubtitle] = new JCheckBox("Numbering"); cbNumbSubtitle[nSubtitle].setEnabled(false); cbNumbSubtitle[nSubtitle].setBounds(16, 113, 81, 23); if (!isWindows()) cbNumbSubtitle[nSubtitle].setBounds(16, 113, 104, 23); subPnlSubtitle[nSubtitle].add(cbNumbSubtitle[nSubtitle]); lblNumbStartSubtitle[nSubtitle] = new JLabel("Start"); lblNumbStartSubtitle[nSubtitle].setEnabled(false); lblNumbStartSubtitle[nSubtitle].setBounds(191, 115, 31, 14); if (!isWindows()) lblNumbStartSubtitle[nSubtitle].setBounds(191, 115, 45, 14); subPnlSubtitle[nSubtitle].add(lblNumbStartSubtitle[nSubtitle]); txtNumbStartSubtitle[nSubtitle] = new JTextField(); txtNumbStartSubtitle[nSubtitle].setEnabled(false); txtNumbStartSubtitle[nSubtitle].setText("1"); txtNumbStartSubtitle[nSubtitle].setBounds(220, 113, 70, 20); if (!isWindows()) txtNumbStartSubtitle[nSubtitle].setBounds(232, 113, 70, 20); subPnlSubtitle[nSubtitle].add(txtNumbStartSubtitle[nSubtitle]); txtNumbStartSubtitle[nSubtitle].setColumns(10); lblNumbPadSubtitle[nSubtitle] = new JLabel("Padding"); lblNumbPadSubtitle[nSubtitle].setEnabled(false); lblNumbPadSubtitle[nSubtitle].setBounds(322, 115, 45, 14); if (!isWindows()) lblNumbPadSubtitle[nSubtitle].setBounds(337, 115, 64, 14); subPnlSubtitle[nSubtitle].add(lblNumbPadSubtitle[nSubtitle]); txtNumbPadSubtitle[nSubtitle] = new JTextField(); txtNumbPadSubtitle[nSubtitle].setEnabled(false); txtNumbPadSubtitle[nSubtitle].setText("1"); txtNumbPadSubtitle[nSubtitle].setBounds(366, 113, 70, 20); if (!isWindows()) txtNumbPadSubtitle[nSubtitle].setBounds(402, 113, 70, 20); subPnlSubtitle[nSubtitle].add(txtNumbPadSubtitle[nSubtitle]); txtNumbPadSubtitle[nSubtitle].setColumns(10); lblNumbExplainSubtitle[nSubtitle] = new JLabel("To use it, add {num} to track name (e.g. \"My Subtitle {num}\")"); lblNumbExplainSubtitle[nSubtitle].setEnabled(false); lblNumbExplainSubtitle[nSubtitle].setBounds(33, 143, 473, 14); if (!isWindows()) lblNumbExplainSubtitle[nSubtitle].setBounds(33, 143, 473, 14); subPnlSubtitle[nSubtitle].add(lblNumbExplainSubtitle[nSubtitle]); chbLangSubtitle[nSubtitle] = new JCheckBox("Language"); chbLangSubtitle[nSubtitle].setEnabled(false); chbLangSubtitle[nSubtitle].setBounds(6, 164, 73, 23); if (!isWindows()) chbLangSubtitle[nSubtitle].setBounds(6, 164, 104, 23); subPnlSubtitle[nSubtitle].add(chbLangSubtitle[nSubtitle]); cbLangSubtitle[nSubtitle] = new JComboBox(); cbLangSubtitle[nSubtitle].setEnabled(false); cbLangSubtitle[nSubtitle].setBounds(93, 164, 430, 20); if (!isWindows()) cbLangSubtitle[nSubtitle].setBounds(123, 164, 595, 20); cbLangSubtitle[nSubtitle].setModel(new DefaultComboBoxModel(mkvLang.getLangName())); subPnlSubtitle[nSubtitle].add(cbLangSubtitle[nSubtitle]); int pos = mkvLang.getAsLangCode().indexOf("und"); cbLangSubtitle[nSubtitle].setSelectedIndex(pos); chbExtraCmdSubtitle[nSubtitle] = new JCheckBox("Extra parameters"); chbExtraCmdSubtitle[nSubtitle].setEnabled(false); chbExtraCmdSubtitle[nSubtitle].setBounds(6, 190, 109, 23); if (!isWindows()) chbExtraCmdSubtitle[nSubtitle].setBounds(6, 190, 153, 23); subPnlSubtitle[nSubtitle].add(chbExtraCmdSubtitle[nSubtitle]); txtExtraCmdSubtitle[nSubtitle] = new JTextField(); txtExtraCmdSubtitle[nSubtitle].setEnabled(false); txtExtraCmdSubtitle[nSubtitle].setBounds(126, 191, 592, 20); if (!isWindows()) txtExtraCmdSubtitle[nSubtitle].setBounds(165, 191, 553, 20); subPnlSubtitle[nSubtitle].add(txtExtraCmdSubtitle[nSubtitle]); txtExtraCmdSubtitle[nSubtitle].setColumns(10); chbEditSubtitle[nSubtitle].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); boolean state = chbDefaultSubtitle[curCbSubtitle].isEnabled(); chbDefaultSubtitle[curCbSubtitle].setEnabled(!state); chbForcedSubtitle[curCbSubtitle].setEnabled(!state); chbNameSubtitle[curCbSubtitle].setEnabled(!state); chbLangSubtitle[curCbSubtitle].setEnabled(!state); chbExtraCmdSubtitle[curCbSubtitle].setEnabled(!state); if (txtNameSubtitle[curCbSubtitle].isEnabled() || chbNameSubtitle[curCbSubtitle].isSelected()) { txtNameSubtitle[curCbSubtitle].setEnabled(!state); cbNumbSubtitle[curCbSubtitle].setEnabled(!state); if (cbNumbSubtitle[curCbSubtitle].isSelected()) { lblNumbStartSubtitle[curCbSubtitle].setEnabled(!state); txtNumbStartSubtitle[curCbSubtitle].setEnabled(!state); lblNumbPadSubtitle[curCbSubtitle].setEnabled(!state); txtNumbPadSubtitle[curCbSubtitle].setEnabled(!state); lblNumbExplainSubtitle[curCbSubtitle].setEnabled(!state); } } if (rbNoDefSubtitle[curCbSubtitle].isEnabled() || chbDefaultSubtitle[curCbSubtitle].isSelected()) { rbNoDefSubtitle[curCbSubtitle].setEnabled(!state); rbYesDefSubtitle[curCbSubtitle].setEnabled(!state); } if (rbNoForcedSubtitle[curCbSubtitle].isEnabled() || chbForcedSubtitle[curCbSubtitle].isSelected()) { rbNoForcedSubtitle[curCbSubtitle].setEnabled(!state); rbYesForcedSubtitle[curCbSubtitle].setEnabled(!state); } if (cbLangSubtitle[curCbSubtitle].isEnabled() || chbLangSubtitle[curCbSubtitle].isSelected()) { cbLangSubtitle[curCbSubtitle].setEnabled(!state); } if (txtExtraCmdSubtitle[curCbSubtitle].isEnabled() || chbExtraCmdSubtitle[curCbSubtitle].isSelected()) { chbExtraCmdSubtitle[curCbSubtitle].setEnabled(!state); txtExtraCmdSubtitle[curCbSubtitle].setEnabled(!state); } } }); chbNameSubtitle[nSubtitle].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); boolean state = cbNumbSubtitle[curCbSubtitle].isEnabled(); cbNumbSubtitle[curCbSubtitle].setEnabled(!state); txtNameSubtitle[curCbSubtitle].setEnabled(!state); if (cbNumbSubtitle[curCbSubtitle].isSelected()) { lblNumbStartSubtitle[curCbSubtitle].setEnabled(!state); txtNumbStartSubtitle[curCbSubtitle].setEnabled(!state); lblNumbPadSubtitle[curCbSubtitle].setEnabled(!state); txtNumbPadSubtitle[curCbSubtitle].setEnabled(!state); lblNumbExplainSubtitle[curCbSubtitle].setEnabled(!state); } } }); chbDefaultSubtitle[nSubtitle].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); boolean state = rbNoDefSubtitle[curCbSubtitle].isEnabled(); rbNoDefSubtitle[curCbSubtitle].setEnabled(!state); rbYesDefSubtitle[curCbSubtitle].setEnabled(!state); } }); chbForcedSubtitle[nSubtitle].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); boolean state = rbNoForcedSubtitle[curCbSubtitle].isEnabled(); rbNoForcedSubtitle[curCbSubtitle].setEnabled(!state); rbYesForcedSubtitle[curCbSubtitle].setEnabled(!state); } }); cbNumbSubtitle[nSubtitle].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); boolean state = txtNumbStartSubtitle[curCbSubtitle].isEnabled(); lblNumbStartSubtitle[curCbSubtitle].setEnabled(!state); txtNumbStartSubtitle[curCbSubtitle].setEnabled(!state); lblNumbPadSubtitle[curCbSubtitle].setEnabled(!state); txtNumbPadSubtitle[curCbSubtitle].setEnabled(!state); lblNumbExplainSubtitle[curCbSubtitle].setEnabled(!state); } }); chbLangSubtitle[nSubtitle].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); boolean state = cbLangSubtitle[curCbSubtitle].isEnabled(); cbLangSubtitle[curCbSubtitle].setEnabled(!state); } }); txtNumbStartSubtitle[nSubtitle].addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); try { if (Integer.parseInt(txtNumbStartSubtitle[curCbSubtitle].getText()) < 0) txtNumbStartSubtitle[curCbSubtitle].setText("1"); } catch (NumberFormatException e1) { txtNumbStartSubtitle[curCbSubtitle].setText("1"); } } }); txtNumbPadSubtitle[nSubtitle].addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); try { if (Integer.parseInt(txtNumbPadSubtitle[curCbSubtitle].getText()) < 0) txtNumbPadSubtitle[curCbSubtitle].setText("1"); } catch (NumberFormatException e1) { txtNumbPadSubtitle[curCbSubtitle].setText("1"); } } }); chbExtraCmdSubtitle[nSubtitle].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); boolean state = txtExtraCmdSubtitle[curCbSubtitle].isEnabled(); txtExtraCmdSubtitle[curCbSubtitle].setEnabled(!state); } }); cbSubtitle.addItem("Subtitle Track " + (nSubtitle+1)); } nSubtitle++; } /* End of track addition operations */ /* Start of command line operations */ private void setCmdLineGeneral() { cmdLineGeneral = new String[modelFiles.size()]; cmdLineGeneralOpt = new String[modelFiles.size()]; int start = Integer.parseInt(txtNumbStartGeneral.getText()); for (int i = 0; i < modelFiles.size(); i++) { cmdLineGeneral[i] = ""; cmdLineGeneralOpt[i] = ""; if (chbRemoveTags.isSelected()) { cmdLineGeneral[i] += " --tags all:"; cmdLineGeneralOpt[i] += " --tags all:"; } if (chbRemoveChapters.isSelected()) { cmdLineGeneral[i] += " --chapters \"\""; cmdLineGeneralOpt[i] += " --chapters #EMPTY#"; } if (chbTitleGeneral.isSelected()) { cmdLineGeneral[i] += " --edit info"; cmdLineGeneralOpt[i] += " --edit info"; if (cbNumbGeneral.isSelected()) { int pad = 0; pad = Integer.parseInt(txtNumbPadGeneral.getText()); String newTitle = txtTitleGeneral.getText(); newTitle = newTitle.replace("{num}", padNumber(pad).format(start)); start++; cmdLineGeneral[i] += " --set title=\"" + escapeNameCmdLine(newTitle) + "\""; cmdLineGeneralOpt[i] += " --set title=\"" + escapeName(newTitle) + "\""; } else { cmdLineGeneral[i] += " --set title=\"" + escapeNameCmdLine(txtTitleGeneral.getText()) + "\""; cmdLineGeneralOpt[i] += " --set title=\"" + escapeName(txtTitleGeneral.getText()) + "\""; } } if (chbExtraCmdGeneral.isSelected() && !txtExtraCmdGeneral.getText().trim().isEmpty()) { cmdLineGeneral[i] += " " + txtExtraCmdGeneral.getText(); cmdLineGeneralOpt[i] += " " + txtExtraCmdGeneral.getText(); } } } private void setCmdLineVideo() { cmdLineVideo = new String[modelFiles.size()]; cmdLineVideoOpt = new String[modelFiles.size()]; String[] tmpCmdLineVideo = new String[nVideo]; String[] tmpCmdLineVideoOpt = new String[nVideo]; int[] numStartVideo = new int[nVideo]; int[] numPadVideo = new int[nVideo]; for (int i = 0; i < modelFiles.size(); i++) { int editCount = 0; cmdLineVideo[i] = ""; cmdLineVideoOpt[i] = ""; for (int j = 0; j < nVideo; j++) { if (chbEditVideo[j].isSelected()) { numStartVideo[j] = Integer.parseInt(txtNumbStartVideo[j].getText()); numPadVideo[j] = Integer.parseInt(txtNumbPadVideo[j].getText()); tmpCmdLineVideo[j] = ""; tmpCmdLineVideoOpt[j] = ""; if (chbEditVideo[j].isSelected()) { tmpCmdLineVideo[j] += " --edit track:v" + (j+1); tmpCmdLineVideoOpt[j] += " --edit track:v" + (j+1); } if (chbDefaultVideo[j].isSelected()) { tmpCmdLineVideo[j] += " --set flag-default="; tmpCmdLineVideoOpt[j] += " --set flag-default="; if (rbYesDefVideo[j].isSelected()) { tmpCmdLineVideo[j] += "1"; tmpCmdLineVideoOpt[j] += "1"; } else { tmpCmdLineVideo[j] += "0"; tmpCmdLineVideoOpt[j] += "0"; } editCount++; } if (chbForcedVideo[j].isSelected()) { tmpCmdLineVideo[j] += " --set flag-forced="; tmpCmdLineVideoOpt[j] += " --set flag-forced="; if (rbYesForcedVideo[j].isSelected()) { tmpCmdLineVideo[j] += "1"; tmpCmdLineVideoOpt[j] += "1"; } else { tmpCmdLineVideo[j] += "0"; tmpCmdLineVideoOpt[j] += "0"; } editCount++; } if (chbNameVideo[j].isSelected()) { tmpCmdLineVideo[j] += " --set name=\"" + escapeNameCmdLine(txtNameVideo[j].getText()) + "\""; tmpCmdLineVideoOpt[j] += " --set name=\"" + escapeName(txtNameVideo[j].getText()) + "\""; editCount++; } if (chbLangVideo[j].isSelected()) { String curLangCode = mkvLang.getAsLangCode().get(cbLangVideo[j].getSelectedIndex()); tmpCmdLineVideo[j] += " --set language=\"" + curLangCode + "\""; tmpCmdLineVideoOpt[j] += " --set language=\"" + curLangCode + "\""; editCount++; } if (chbExtraCmdVideo[j].isSelected() && !txtExtraCmdVideo[j].getText().trim().isEmpty()) { tmpCmdLineVideo[j] += " " + txtExtraCmdVideo[j].getText(); tmpCmdLineVideoOpt[j] += " " + txtExtraCmdVideo[j].getText(); editCount++; } if (editCount == 0) { tmpCmdLineVideo[j] = ""; tmpCmdLineVideoOpt[j] = ""; } } else { tmpCmdLineVideo[j] = ""; tmpCmdLineVideoOpt[j] = ""; } } } for (int i = 0; i < nVideo; i++) { for (int j = 0; j < modelFiles.size(); j++) { String tmpText = tmpCmdLineVideo[i]; String tmpText2 = tmpCmdLineVideoOpt[i]; if (cbNumbVideo[i].isSelected() && chbEditVideo[i].isSelected()) { tmpText = tmpText.replace("{num}", padNumber(numPadVideo[i]).format(numStartVideo[i])); tmpText2 = tmpText.replace("{num}", padNumber(numPadVideo[i]).format(numStartVideo[i])); numStartVideo[i]++; } cmdLineVideo[j] += tmpText; cmdLineVideoOpt[j] += tmpText2; } } } private void setCmdLineAudio() { cmdLineAudio = new String[modelFiles.size()]; cmdLineAudioOpt = new String[modelFiles.size()]; String[] tmpCmdLineAudio = new String[nAudio]; String[] tmpCmdLineAudioOpt = new String[nAudio]; int[] numStartAudio = new int[nAudio]; int[] numPadAudio = new int[nAudio]; for (int i = 0; i < modelFiles.size(); i++) { int editCount = 0; cmdLineAudio[i] = ""; cmdLineAudioOpt[i] = ""; for (int j = 0; j < nAudio; j++) { if (chbEditAudio[j].isSelected()) { numStartAudio[j] = Integer.parseInt(txtNumbStartAudio[j].getText()); numPadAudio[j] = Integer.parseInt(txtNumbPadAudio[j].getText()); tmpCmdLineAudio[j] = ""; tmpCmdLineAudioOpt[j] = ""; if (chbEditAudio[j].isSelected()) { tmpCmdLineAudio[j] += " --edit track:a" + (j+1); tmpCmdLineAudioOpt[j] += " --edit track:a" + (j+1); } if (chbDefaultAudio[j].isSelected()) { tmpCmdLineAudio[j] += " --set flag-default="; tmpCmdLineAudioOpt[j] += " --set flag-default="; if (rbYesDefAudio[j].isSelected()) { tmpCmdLineAudio[j] += "1"; tmpCmdLineAudioOpt[j] += "1"; } else { tmpCmdLineAudio[j] += "0"; tmpCmdLineAudioOpt[j] += "0"; } editCount++; } if (chbForcedAudio[j].isSelected()) { tmpCmdLineAudio[j] += " --set flag-forced="; tmpCmdLineAudioOpt[j] += " --set flag-forced="; if (rbYesForcedAudio[j].isSelected()) { tmpCmdLineAudio[j] += "1"; tmpCmdLineAudioOpt[j] += "1"; } else { tmpCmdLineAudio[j] += "0"; tmpCmdLineAudioOpt[j] += "0"; } editCount++; } if (chbNameAudio[j].isSelected()) { tmpCmdLineAudio[j] += " --set name=\"" + escapeNameCmdLine(txtNameAudio[j].getText()) + "\""; tmpCmdLineAudioOpt[j] += " --set name=\"" + escapeName(txtNameAudio[j].getText()) + "\""; editCount++; } if (chbLangAudio[j].isSelected()) { String curLangCode = mkvLang.getAsLangCode().get(cbLangAudio[j].getSelectedIndex()); tmpCmdLineAudio[j] += " --set language=\"" + curLangCode + "\""; tmpCmdLineAudioOpt[j] += " --set language=\"" + curLangCode + "\""; editCount++; } if (chbExtraCmdAudio[j].isSelected() && !txtExtraCmdAudio[j].getText().trim().isEmpty()) { tmpCmdLineAudio[j] += " " + txtExtraCmdAudio[j].getText(); tmpCmdLineAudioOpt[j] += " " + txtExtraCmdAudio[j].getText(); editCount++; } if (editCount == 0) { tmpCmdLineAudio[j] = ""; tmpCmdLineAudioOpt[j] = ""; } } else { tmpCmdLineAudio[j] = ""; tmpCmdLineAudioOpt[j] = ""; } } } for (int i = 0; i < nAudio; i++) { for (int j = 0; j < modelFiles.size(); j++) { String tmpText = tmpCmdLineAudio[i]; String tmpText2 = tmpCmdLineAudioOpt[i]; if (cbNumbAudio[i].isSelected() && chbEditAudio[i].isSelected()) { tmpText = tmpText.replace("{num}", padNumber(numPadAudio[i]).format(numStartAudio[i])); tmpText2 = tmpText.replace("{num}", padNumber(numPadAudio[i]).format(numStartAudio[i])); numStartAudio[i]++; } cmdLineAudio[j] += tmpText; cmdLineAudioOpt[j] += tmpText2; } } } private void setCmdLineSubtitle() { cmdLineSubtitle = new String[modelFiles.size()]; cmdLineSubtitleOpt = new String[modelFiles.size()]; String[] tmpCmdLineSubtitle = new String[nSubtitle]; String[] tmpCmdLineSubtitleOpt = new String[nSubtitle]; int[] numStartSubtitle = new int[nSubtitle]; int[] numPadSubtitle = new int[nSubtitle]; for (int i = 0; i < modelFiles.size(); i++) { int editCount = 0; cmdLineSubtitle[i] = ""; cmdLineSubtitleOpt[i] = ""; for (int j = 0; j < nSubtitle; j++) { if (chbEditSubtitle[j].isSelected()) { numStartSubtitle[j] = Integer.parseInt(txtNumbStartSubtitle[j].getText()); numPadSubtitle[j] = Integer.parseInt(txtNumbPadSubtitle[j].getText()); tmpCmdLineSubtitle[j] = ""; tmpCmdLineSubtitleOpt[j] = ""; if (chbEditSubtitle[j].isSelected()) { tmpCmdLineSubtitle[j] += " --edit track:s" + (j+1); tmpCmdLineSubtitleOpt[j] += " --edit track:s" + (j+1); } if (chbDefaultSubtitle[j].isSelected()) { tmpCmdLineSubtitle[j] += " --set flag-default="; tmpCmdLineSubtitleOpt[j] += " --set flag-default="; if (rbYesDefSubtitle[j].isSelected()) { tmpCmdLineSubtitle[j] += "1"; tmpCmdLineSubtitleOpt[j] += "1"; } else { tmpCmdLineSubtitle[j] += "0"; tmpCmdLineSubtitleOpt[j] += "0"; } editCount++; } if (chbForcedSubtitle[j].isSelected()) { tmpCmdLineSubtitle[j] += " --set flag-forced="; tmpCmdLineSubtitleOpt[j] += " --set flag-forced="; if (rbYesForcedSubtitle[j].isSelected()) { tmpCmdLineSubtitle[j] += "1"; tmpCmdLineSubtitleOpt[j] += "1"; } else { tmpCmdLineSubtitle[j] += "0"; tmpCmdLineSubtitleOpt[j] += "0"; } editCount++; } if (chbNameSubtitle[j].isSelected()) { tmpCmdLineSubtitle[j] += " --set name=\"" + escapeNameCmdLine(txtNameSubtitle[j].getText()) + "\""; tmpCmdLineSubtitleOpt[j] += " --set name=\"" + escapeName(txtNameSubtitle[j].getText()) + "\""; editCount++; } if (chbLangSubtitle[j].isSelected()) { String curLangCode = mkvLang.getAsLangCode().get(cbLangSubtitle[j].getSelectedIndex()); tmpCmdLineSubtitle[j] += " --set language=\"" + curLangCode + "\""; tmpCmdLineSubtitleOpt[j] += " --set language=\"" + curLangCode + "\""; editCount++; } if (chbExtraCmdSubtitle[j].isSelected() && !txtExtraCmdSubtitle[j].getText().trim().isEmpty()) { tmpCmdLineSubtitle[j] += " " + txtExtraCmdSubtitle[j].getText(); tmpCmdLineSubtitleOpt[j] += " " + txtExtraCmdSubtitle[j].getText(); editCount++; } if (editCount == 0) { tmpCmdLineSubtitle[j] = ""; tmpCmdLineSubtitleOpt[j] = ""; } } else { tmpCmdLineSubtitle[j] = ""; tmpCmdLineSubtitleOpt[j] = ""; } } } for (int i = 0; i < nSubtitle; i++) { for (int j = 0; j < modelFiles.size(); j++) { String tmpText = tmpCmdLineSubtitle[i]; String tmpText2 = tmpCmdLineSubtitleOpt[i]; if (cbNumbSubtitle[i].isSelected() && chbEditSubtitle[i].isSelected()) { tmpText = tmpText.replace("{num}", padNumber(numPadSubtitle[i]).format(numStartSubtitle[i])); tmpText2 = tmpText.replace("{num}", padNumber(numPadSubtitle[i]).format(numStartSubtitle[i])); numStartSubtitle[i]++; } cmdLineSubtitle[j] += tmpText; cmdLineSubtitleOpt[j] += tmpText2; } } } private void setCmdLine() { setCmdLineGeneral(); setCmdLineVideo(); setCmdLineAudio(); setCmdLineSubtitle(); cmdLineBatch = new ArrayList<String>(); cmdLineBatchOpt = new ArrayList<String>(); String cmdTemp = cmdLineGeneral[0] + cmdLineVideo[0] + cmdLineAudio[0] + cmdLineSubtitle[0]; if (!cmdTemp.isEmpty()) { for (int i = 0; i < modelFiles.getSize(); i++) { String cmdLineAll = cmdLineGeneral[i] + cmdLineVideo[i] + cmdLineAudio[i] + cmdLineSubtitle[i]; String cmdLineAllOpt = cmdLineGeneralOpt[i] + cmdLineVideoOpt[i] + cmdLineAudioOpt[i] + cmdLineSubtitleOpt[i]; if (isWindows()) { cmdLineBatch.add("\"" + txtMkvPropExe.getText() + "\" \"" + modelFiles.get(i) + "\"" + cmdLineAll); cmdLineBatchOpt.add("\"" + escapePath((String) modelFiles.get(i)) + "\"" + cmdLineAllOpt); } else { cmdLineBatch.add(escapePath(txtMkvPropExe.getText()) + " " + escapePath((String) modelFiles.get(i)) + cmdLineAll); cmdLineBatchOpt.add("\"" + (String) modelFiles.get(i) + "\"" + cmdLineAllOpt); } } } } private void executeBatch() { worker = new SwingWorker<Void, Void>() { @Override public Void doInBackground() { try { txtOutput.setText(""); tabbedPane.setSelectedIndex(tabbedPane.getTabCount()-1); tabbedPane.setEnabled(false); btnProcessFiles.setEnabled(false); btnGenerateCmdLine.setEnabled(false); for (int i = 0; i < cmdLineBatch.size(); i++) { File optFile = new File("options.txt"); PrintWriter optFilePW = new PrintWriter(new BufferedWriter(new FileWriter(optFile))); String[] optFileContents = Commandline.translateCommandline(cmdLineBatchOpt.get(i)); if (!optFile.exists()) { optFile.createNewFile(); } for (String content:optFileContents) { optFilePW.println(content); } optFilePW.flush(); optFilePW.close(); if (isWindows()) { proc = rt.exec("\"" + txtMkvPropExe.getText() + "\" @options.txt"); } else { proc = rt.exec(escapePath(txtMkvPropExe.getText()) + " @options.txt"); } txtOutput.append("File: " + modelFiles.get(i) + "\n"); txtOutput.append("Command line: " + cmdLineBatch.get(i) + "\n\n"); StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), txtOutput); StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), txtOutput); outputGobbler.start(); errorGobbler.start(); proc.waitFor(); optFile.delete(); if (i < cmdLineBatch.size()-1) txtOutput.append("--------------\n\n"); } } catch (IOException e) { } catch (InterruptedException e) { } return null; } @Override protected void done() { tabbedPane.setEnabled(true); btnProcessFiles.setEnabled(true); btnGenerateCmdLine.setEnabled(true); } }; worker.execute(); } /* End of command line operations */ /* Start of INI configuration file operations */ private void readIniFile() { Ini ini = null; if (iniFile.exists()) { try { ini = new Ini(iniFile); String exePath = ini.get("General", "mkvpropedit"); if (exePath != null) { File exeFile = new File(exePath); if (exeFile.exists()) { if (exeFile.toString().equals("mkvpropedit.exe") && isWindows()) { cbMkvPropExeDef.setSelected(true); cbMkvPropExeDef.setEnabled(false); } else if (exeFile.toString().equals("/usr/bin/mkvpropedit") && !isWindows()) { cbMkvPropExeDef.setSelected(true); cbMkvPropExeDef.setEnabled(false); } else { txtMkvPropExe.setText(exePath); cbMkvPropExeDef.setSelected(false); cbMkvPropExeDef.setEnabled(true); } } else { if (isWindows()) txtMkvPropExe.setText("mvkpropedit.exe"); else txtMkvPropExe.setText("/usr/bin/mkvpropedit"); cbMkvPropExeDef.setSelected(true); cbMkvPropExeDef.setEnabled(false); } } } catch (InvalidFileFormatException e) { } catch (IOException e) { } } else if (isWindows()) { String exePath = getMkvPropExeFromReg(); if (exePath != null) { txtMkvPropExe.setText(exePath); cbMkvPropExeDef.setSelected(false); cbMkvPropExeDef.setEnabled(true); saveIniFile(new File(exePath)); } } } private void saveIniFile(File exeFile) { if (exeFile.exists()) { Ini ini = null; if (!iniFile.exists()) { try { iniFile.createNewFile(); } catch (IOException e1) { } } txtMkvPropExe.setText(exeFile.toString()); cbMkvPropExeDef.setSelected(false); cbMkvPropExeDef.setEnabled(true); try { ini = new Ini(iniFile); ini.put("General", "mkvpropedit", exeFile.toString()); ini.store(); } catch (InvalidFileFormatException e1) { } catch (IOException e1) { } } } private void defaultIniFile() { Ini ini = null; if (!iniFile.exists()) { try { iniFile.createNewFile(); } catch (IOException e1) { } } try { ini = new Ini(iniFile); if (isWindows()) ini.put("General", "mkvpropedit", "mkvpropedit.exe"); else ini.put("General", "mkvpropedit", "/usr/bin/mkvpropedit"); ini.store(); } catch (InvalidFileFormatException e1) { } catch (IOException e1) { } } private String getMkvPropExeFromReg() { String exePath = null; try { exePath = WinRegistry.readString(WinRegistry.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\MKVtoolnix", "UninstallString"); if (exePath == null) exePath = WinRegistry.readString(WinRegistry.HKEY_LOCAL_MACHINE, "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\MKVtoolnix", "UninstallString"); } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } if (exePath != null) { File tmpExe = new File(exePath); tmpExe = new File(tmpExe.getParent()+"\\mkvpropedit.exe"); if (tmpExe.exists()) { exePath = tmpExe.toString(); } } return exePath; } /* End of INI configuration file operations */ /* Start of escaping functions */ private String escapeName (String name) { if (!name.isEmpty()) { name = name.replace("\\","\\\\"); name = name.replace(" ", "\\s"); name = name.replace("\"","\\2"); name = name.replace(":","\\c"); name = name.replace("#","\\h"); } return name; } private String escapeNameCmdLine (String name) { name = name.replace("\"", "\\\""); return name; } private String escapePath (String path) { if (isWindows()) { path = path.replace("\\", "\\\\"); } else { path = path.replace("\\", "\\\\"); path = path.replace(" ", "\\ "); path = path.replace("[", "\\["); path = path.replace("]", "\\]"); path = path.replace("{", "\\{"); path = path.replace("}", "\\}"); path = path.replace("<", "\\<"); path = path.replace(">", "\\>"); path = path.replace("\'", "\\\'"); path = path.replace("\"", "\\\""); path = path.replace("&", "\\&"); path = path.replace("*", "\\*"); path = path.replace("?", "\\?"); path = path.replace("|", "\\|"); path = path.replace(":", "\\:"); path = path.replace(";", "\\;"); } return path; } /* End of escaping functions */ private NumberFormat padNumber(int pad) { NumberFormat formatter = new DecimalFormat("0"); if (pad > 0) { String n = ""; for (int i = 0; i < pad; i++) { n += 0; } formatter = new DecimalFormat(n); } return formatter; } private boolean isWindows() { String OS = System.getProperty("os.name"); if (OS.startsWith("Windows")) return true; else return false; } }
trunk/src/com/googlecode/jmkvpropedit/JMkvpropedit.java
/* * Copyright (c) 2012 Bruno Barbieri * 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. * * 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 HOLDER 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.googlecode.jmkvpropedit; import java.awt.*; import java.awt.event.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.*; import javax.swing.*; import javax.swing.filechooser.*; import org.ini4j.*; public class JMkvpropedit { private JFrame frmJMkvpropedit; private int maxStreams = 30; // Track number limit for batch mode Runtime rt = Runtime.getRuntime(); private Process proc = null; private SwingWorker<Void, Void> worker = null; private JPanel[] subPnlVideo = new JPanel[maxStreams]; private JCheckBox[] chbEditVideo = new JCheckBox[maxStreams]; private JCheckBox[] chbDefaultVideo = new JCheckBox[maxStreams]; private JRadioButton[] rbYesDefVideo = new JRadioButton[maxStreams]; private JRadioButton[] rbNoDefVideo = new JRadioButton[maxStreams]; private ButtonGroup[] bgRbDefVideo = new ButtonGroup[maxStreams]; private JCheckBox[] chbForcedVideo = new JCheckBox[maxStreams]; private JRadioButton[] rbYesForcedVideo = new JRadioButton[maxStreams]; private JRadioButton[] rbNoForcedVideo = new JRadioButton[maxStreams]; private ButtonGroup[] bgRbForcedVideo = new ButtonGroup[maxStreams]; private JCheckBox[] chbNameVideo = new JCheckBox[maxStreams]; private JTextField[] txtNameVideo = new JTextField[maxStreams]; private JCheckBox[] cbNumbVideo = new JCheckBox[maxStreams]; private JTextField[] txtNumbStartVideo = new JTextField[maxStreams]; private JLabel[] lblNumbStartVideo = new JLabel[maxStreams]; private JLabel[] lblNumbExplainVideo = new JLabel[maxStreams]; private JLabel[] lblNumbPadVideo = new JLabel[maxStreams]; private JTextField[] txtNumbPadVideo = new JTextField[maxStreams]; private JCheckBox[] chbLangVideo = new JCheckBox[maxStreams]; private JComboBox[] cbLangVideo = new JComboBox[maxStreams]; private JCheckBox[] chbExtraCmdVideo = new JCheckBox[maxStreams]; private JTextField[] txtExtraCmdVideo = new JTextField[maxStreams]; private JPanel[] subPnlAudio = new JPanel[maxStreams]; private JCheckBox[] chbEditAudio = new JCheckBox[maxStreams]; private JCheckBox[] chbDefaultAudio = new JCheckBox[maxStreams]; private JRadioButton[] rbYesDefAudio = new JRadioButton[maxStreams]; private JRadioButton[] rbNoDefAudio = new JRadioButton[maxStreams]; private ButtonGroup[] bgRbDefAudio = new ButtonGroup[maxStreams]; private JCheckBox[] chbForcedAudio = new JCheckBox[maxStreams]; private JRadioButton[] rbYesForcedAudio = new JRadioButton[maxStreams]; private JRadioButton[] rbNoForcedAudio = new JRadioButton[maxStreams]; private ButtonGroup[] bgRbForcedAudio = new ButtonGroup[maxStreams]; private JCheckBox[] chbNameAudio = new JCheckBox[maxStreams]; private JTextField[] txtNameAudio = new JTextField[maxStreams]; private JCheckBox[] cbNumbAudio = new JCheckBox[maxStreams]; private JTextField[] txtNumbStartAudio = new JTextField[maxStreams]; private JLabel[] lblNumbStartAudio = new JLabel[maxStreams]; private JLabel[] lblNumbExplainAudio = new JLabel[maxStreams]; private JLabel[] lblNumbPadAudio = new JLabel[maxStreams]; private JTextField[] txtNumbPadAudio = new JTextField[maxStreams]; private JCheckBox[] chbLangAudio = new JCheckBox[maxStreams]; private JComboBox[] cbLangAudio = new JComboBox[maxStreams]; private JCheckBox[] chbExtraCmdAudio = new JCheckBox[maxStreams]; private JTextField[] txtExtraCmdAudio = new JTextField[maxStreams]; private JPanel[] subPnlSubtitle = new JPanel[maxStreams]; private JCheckBox[] chbEditSubtitle = new JCheckBox[maxStreams]; private JCheckBox[] chbDefaultSubtitle = new JCheckBox[maxStreams]; private JRadioButton[] rbYesDefSubtitle = new JRadioButton[maxStreams]; private JRadioButton[] rbNoDefSubtitle = new JRadioButton[maxStreams]; private ButtonGroup[] bgRbDefSubtitle = new ButtonGroup[maxStreams]; private JCheckBox[] chbForcedSubtitle = new JCheckBox[maxStreams]; private JRadioButton[] rbYesForcedSubtitle = new JRadioButton[maxStreams]; private JRadioButton[] rbNoForcedSubtitle = new JRadioButton[maxStreams]; private ButtonGroup[] bgRbForcedSubtitle = new ButtonGroup[maxStreams]; private JCheckBox[] chbNameSubtitle = new JCheckBox[maxStreams]; private JTextField[] txtNameSubtitle = new JTextField[maxStreams]; private JCheckBox[] cbNumbSubtitle = new JCheckBox[maxStreams]; private JTextField[] txtNumbStartSubtitle = new JTextField[maxStreams]; private JLabel[] lblNumbStartSubtitle = new JLabel[maxStreams]; private JLabel[] lblNumbExplainSubtitle = new JLabel[maxStreams]; private JLabel[] lblNumbPadSubtitle = new JLabel[maxStreams]; private JTextField[] txtNumbPadSubtitle = new JTextField[maxStreams]; private JCheckBox[] chbLangSubtitle = new JCheckBox[maxStreams]; private JComboBox[] cbLangSubtitle = new JComboBox[maxStreams]; private JCheckBox[] chbExtraCmdSubtitle = new JCheckBox[maxStreams]; private JTextField[] txtExtraCmdSubtitle = new JTextField[maxStreams]; private JCheckBox chbTitleGeneral; private JTextField txtTitleGeneral; private JCheckBox cbNumbGeneral; private JTextField txtNumbStartGeneral; private JTextField txtNumbPadGeneral; private JCheckBox chbRemoveChapters; private JCheckBox chbRemoveTags; private JCheckBox chbExtraCmdGeneral; private JTextField txtExtraCmdGeneral; private JTextField txtMkvPropExe; private JCheckBox cbMkvPropExeDef; private JTabbedPane tabbedPane; private DefaultListModel modelFiles; private JList listFiles; private JComboBox cbVideo; private JComboBox cbAudio; private JComboBox cbSubtitle; private JLayeredPane lyrdPnlVideo; private JLayeredPane lyrdPnlAudio; private JLayeredPane lyrdPnlSubtitle; private JButton btnProcessFiles; private JButton btnGenerateCmdLine; private JTextArea txtOutput; private int nVideo = 0; private int nAudio = 0; private int nSubtitle = 0; MkvLanguage mkvLang = new MkvLanguage(); URL imgRes = null; JFileChooser chooser = null; private File iniFile = new File("JMkvpropedit.ini"); private String[] cmdLineGeneral = null; private String[] cmdLineGeneralOpt = null; private String[] cmdLineVideo = null; private String[] cmdLineVideoOpt = null; private String[] cmdLineAudio = null; private String[] cmdLineAudioOpt = null; private String[] cmdLineSubtitle = null; private String[] cmdLineSubtitleOpt = null; private ArrayList<String> cmdLineBatch = null; private ArrayList<String> cmdLineBatchOpt = null; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // Use native theme for GUI JMkvpropedit window = new JMkvpropedit(); window.frmJMkvpropedit.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public JMkvpropedit() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frmJMkvpropedit = new JFrame(); frmJMkvpropedit.setTitle("JMkvpropedit 1.0.3"); /* Version */ frmJMkvpropedit.setResizable(false); frmJMkvpropedit.setBounds(100, 100, 759, 444); frmJMkvpropedit.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frmJMkvpropedit.getContentPane().setLayout(null); tabbedPane = new JTabbedPane(JTabbedPane.TOP); tabbedPane.setBounds(10, 11, 733, 360); frmJMkvpropedit.getContentPane().add(tabbedPane); JPanel pnlInput = new JPanel(); tabbedPane.addTab("Input", null, pnlInput, null); pnlInput.setLayout(null); JScrollPane scrollFiles = new JScrollPane(); scrollFiles.setBounds(10, 11, 676, 310); pnlInput.add(scrollFiles); modelFiles = new DefaultListModel(); listFiles = new JList(modelFiles); scrollFiles.setViewportView(listFiles); imgRes = ClassLoader.getSystemResource("res/list-add.png"); JButton btnAddFiles = new JButton(""); btnAddFiles.setIcon(new ImageIcon(imgRes)); btnAddFiles.setBounds(696, 21, 22, 23); pnlInput.add(btnAddFiles); imgRes = ClassLoader.getSystemResource("res/list-remove.png"); JButton btnRemoveFiles = new JButton(""); btnRemoveFiles.setIcon(new ImageIcon(imgRes)); btnRemoveFiles.setBounds(696, 65, 22, 23); pnlInput.add(btnRemoveFiles); imgRes = ClassLoader.getSystemResource("res/edit-clear.png"); JButton btnClearFiles = new JButton(""); btnClearFiles.setIcon(new ImageIcon(imgRes)); btnClearFiles.setBounds(696, 109, 22, 23); pnlInput.add(btnClearFiles); imgRes = ClassLoader.getSystemResource("res/go-top.png"); JButton btnTopFiles = new JButton(""); btnTopFiles.setIcon(new ImageIcon(imgRes)); btnTopFiles.setBounds(696, 153, 22, 23); pnlInput.add(btnTopFiles); imgRes = ClassLoader.getSystemResource("res/go-up.png"); JButton btnUpFiles = new JButton(""); btnUpFiles.setIcon(new ImageIcon(imgRes)); btnUpFiles.setBounds(696, 197, 22, 23); pnlInput.add(btnUpFiles); imgRes = ClassLoader.getSystemResource("res/go-down.png"); JButton btnDownFiles = new JButton(""); btnDownFiles.setIcon(new ImageIcon(imgRes)); btnDownFiles.setBounds(696, 241, 22, 23); pnlInput.add(btnDownFiles); imgRes = ClassLoader.getSystemResource("res/go-bottom.png"); JButton btnBottomFiles = new JButton(""); btnBottomFiles.setIcon(new ImageIcon(imgRes)); btnBottomFiles.setBounds(696, 285, 22, 23); pnlInput.add(btnBottomFiles); chooser = new JFileChooser(); chooser.setDialogType(JFileChooser.OPEN_DIALOG); chooser.setFileHidingEnabled(true); chooser.setAcceptAllFileFilterUsed(false); JPanel pnlGeneral = new JPanel(); tabbedPane.addTab("General", null, pnlGeneral, null); pnlGeneral.setLayout(null); chbTitleGeneral = new JCheckBox("Title"); chbTitleGeneral.setBounds(6, 7, 45, 23); if (!isWindows()) chbTitleGeneral.setBounds(6, 7, 66, 23); pnlGeneral.add(chbTitleGeneral); txtTitleGeneral = new JTextField(); txtTitleGeneral.setEnabled(false); txtTitleGeneral.setBounds(57, 8, 661, 20); if (!isWindows()) txtTitleGeneral.setBounds(78, 8, 640, 20); pnlGeneral.add(txtTitleGeneral); txtTitleGeneral.setColumns(10); cbNumbGeneral = new JCheckBox("Numbering"); cbNumbGeneral.setEnabled(false); cbNumbGeneral.setBounds(16, 37, 104, 23); pnlGeneral.add(cbNumbGeneral); final JLabel lblNumbStartGeneral = new JLabel("Start"); lblNumbStartGeneral.setEnabled(false); lblNumbStartGeneral.setBounds(191, 40, 31, 14); if (!isWindows()) lblNumbStartGeneral.setBounds(191, 40, 45, 14); pnlGeneral.add(lblNumbStartGeneral); txtNumbStartGeneral = new JTextField(); txtNumbStartGeneral.setEnabled(false); txtNumbStartGeneral.setText("1"); txtNumbStartGeneral.setBounds(220, 38, 70, 20); if (!isWindows()) txtNumbStartGeneral.setBounds(232, 38, 70, 20); pnlGeneral.add(txtNumbStartGeneral); txtNumbStartGeneral.setColumns(10); final JLabel lblNumbPadGeneral = new JLabel("Padding"); lblNumbPadGeneral.setEnabled(false); lblNumbPadGeneral.setBounds(322, 40, 45, 14); if (!isWindows()) lblNumbPadGeneral.setBounds(337, 40, 64, 14); pnlGeneral.add(lblNumbPadGeneral); txtNumbPadGeneral = new JTextField(); txtNumbPadGeneral.setEnabled(false); txtNumbPadGeneral.setText("1"); txtNumbPadGeneral.setBounds(366, 38, 70, 20); if (!isWindows()) txtNumbPadGeneral.setBounds(402, 38, 70, 20); pnlGeneral.add(txtNumbPadGeneral); txtNumbPadGeneral.setColumns(10); final JLabel lblNumbExplainGeneral = new JLabel("To use it, add {num} to tittle (e.g. \"My Title {num}\")"); lblNumbExplainGeneral.setEnabled(false); lblNumbExplainGeneral.setBounds(33, 67, 473, 14); pnlGeneral.add(lblNumbExplainGeneral); chbRemoveChapters = new JCheckBox("Remove chapters"); chbRemoveChapters.setBounds(6, 88, 150, 23); pnlGeneral.add(chbRemoveChapters); chbRemoveTags = new JCheckBox("Remove tags"); chbRemoveTags.setBounds(6, 114, 150, 23); pnlGeneral.add(chbRemoveTags); chbExtraCmdGeneral = new JCheckBox("Extra parameters"); chbExtraCmdGeneral.setBounds(6, 140, 114, 23); if (!isWindows()) chbExtraCmdGeneral.setBounds(6, 140, 150, 23); pnlGeneral.add(chbExtraCmdGeneral); txtExtraCmdGeneral = new JTextField(); txtExtraCmdGeneral.setEnabled(false); txtExtraCmdGeneral.setBounds(126, 141, 592, 20); if (!isWindows()) txtExtraCmdGeneral.setBounds(166, 141, 552, 20); pnlGeneral.add(txtExtraCmdGeneral); txtExtraCmdGeneral.setColumns(10); txtMkvPropExe = new JTextField(); txtMkvPropExe.setText("mkvpropedit.exe"); if (!isWindows()) txtMkvPropExe.setText("/usr/bin/mkvpropedit"); txtMkvPropExe.setEditable(false); txtMkvPropExe.setBounds(10, 272, 708, 20); pnlGeneral.add(txtMkvPropExe); txtMkvPropExe.setColumns(10); JLabel lblMkvPropExe = new JLabel("Mkvpropedit executable"); lblMkvPropExe.setBounds(10, 255, 209, 14); pnlGeneral.add(lblMkvPropExe); cbMkvPropExeDef = new JCheckBox("Use default"); cbMkvPropExeDef.setEnabled(false); cbMkvPropExeDef.setSelected(true); cbMkvPropExeDef.setBounds(6, 292, 120, 23); pnlGeneral.add(cbMkvPropExeDef); JButton btnBrowseMkvPropExe = new JButton("Browse..."); btnBrowseMkvPropExe.setBounds(618, 295, 100, 23); if (!isWindows()) btnBrowseMkvPropExe.setBounds(583, 295, 135, 23); pnlGeneral.add(btnBrowseMkvPropExe); final JPanel pnlVideo = new JPanel(); tabbedPane.addTab("Video", null, pnlVideo, null); pnlVideo.setLayout(null); cbVideo = new JComboBox(); cbVideo.setBounds(10, 10, 146, 20); pnlVideo.add(cbVideo); imgRes = ClassLoader.getSystemResource("res/list-add.png"); final JButton btnAddVideo = new JButton(""); btnAddVideo.setIcon(new ImageIcon(imgRes)); btnAddVideo.setBounds(166, 10, 22, 20); pnlVideo.add(btnAddVideo); lyrdPnlVideo = new JLayeredPane(); lyrdPnlVideo.setBounds(0, 38, 728, 294); pnlVideo.add(lyrdPnlVideo); final JPanel pnlAudio = new JPanel(); tabbedPane.addTab("Audio", null, pnlAudio, null); pnlAudio.setLayout(null); cbAudio = new JComboBox(); cbAudio.setBounds(10, 10, 146, 20); pnlAudio.add(cbAudio); final JButton btnAddAudio = new JButton(""); btnAddAudio.setIcon(new ImageIcon(imgRes)); btnAddAudio.setBounds(166, 10, 22, 20); pnlAudio.add(btnAddAudio); lyrdPnlAudio = new JLayeredPane(); lyrdPnlAudio.setBounds(0, 38, 728, 294); pnlAudio.add(lyrdPnlAudio); final JPanel pnlSubtitle = new JPanel(); tabbedPane.addTab("Subtitle", null, pnlSubtitle, null); pnlSubtitle.setLayout(null); cbSubtitle = new JComboBox(); cbSubtitle.setBounds(10, 10, 146, 20); pnlSubtitle.add(cbSubtitle); final JButton btnAddSubtitle = new JButton(""); btnAddSubtitle.setIcon(new ImageIcon(imgRes)); btnAddSubtitle.setBounds(166, 10, 22, 20); pnlSubtitle.add(btnAddSubtitle); lyrdPnlSubtitle = new JLayeredPane(); lyrdPnlSubtitle.setBounds(0, 38, 728, 294); pnlSubtitle.add(lyrdPnlSubtitle); JPanel pnlOutput = new JPanel(); tabbedPane.addTab("Output", null, pnlOutput, null); pnlOutput.setLayout(new BorderLayout(0, 0)); txtOutput = new JTextArea(); txtOutput.setLineWrap(true); txtOutput.setEditable(false); JScrollPane scrollOutput = new JScrollPane(txtOutput); pnlOutput.add(scrollOutput); btnProcessFiles = new JButton("Process files"); btnProcessFiles.setBounds(151, 382, 150, 23); if (!isWindows()) btnProcessFiles.setBounds(94, 382, 235, 23); frmJMkvpropedit.getContentPane().add(btnProcessFiles); btnGenerateCmdLine = new JButton("Generate command line"); btnGenerateCmdLine.setBounds(452, 382, 150, 23); if (!isWindows()) btnGenerateCmdLine.setBounds(423, 382, 235, 23); frmJMkvpropedit.getContentPane().add(btnGenerateCmdLine); frmJMkvpropedit.addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent arg0) { readIniFile(); addVideoTrack(); addAudioTrack(); addSubtitleTrack(); } @Override public void windowClosing(WindowEvent e) { boolean wRunning; try { wRunning = !worker.isDone(); } catch (Exception e1) { wRunning = false; } if (wRunning) { int choice = JOptionPane.showConfirmDialog(frmJMkvpropedit, "Do you really wanna exit?", "", JOptionPane.YES_NO_OPTION); if (choice == JOptionPane.YES_OPTION) { worker.cancel(true); frmJMkvpropedit.dispose(); System.exit(0); } } else { frmJMkvpropedit.dispose(); System.exit(0); } } }); /* Button "Process files" */ btnProcessFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File mkvPropExe = new File(txtMkvPropExe.getText()); if (modelFiles.getSize() == 0) { JOptionPane.showMessageDialog(frmJMkvpropedit, "The file list is empty!", "Empty list", JOptionPane.ERROR_MESSAGE); } else if (!mkvPropExe.exists()) { JOptionPane.showMessageDialog(frmJMkvpropedit, "Mkvpropedit executable not found!" + "\nPlease set the right path for it or copy it to the working folder (default setting).", "Mkvpropedit not found", JOptionPane.ERROR_MESSAGE); } else { setCmdLine(); if (cmdLineBatchOpt.size() == 0) { JOptionPane.showMessageDialog(frmJMkvpropedit, "Nothing to do!", "", JOptionPane.INFORMATION_MESSAGE); } else { executeBatch(); } } } }); /* Button "Generate command line" */ btnGenerateCmdLine.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (modelFiles.getSize() == 0) { JOptionPane.showMessageDialog(frmJMkvpropedit, "The file list is empty!", "Empty list", JOptionPane.ERROR_MESSAGE); } else { setCmdLine(); if (cmdLineBatch.size() == 0) { JOptionPane.showMessageDialog(frmJMkvpropedit, "Nothing to do!", "", JOptionPane.INFORMATION_MESSAGE); } else { txtOutput.setText(""); if (cmdLineBatch.size() > 0) { for (int i = 0; i < modelFiles.size(); i++) { txtOutput.append(cmdLineBatch.get(i) + "\n"); } tabbedPane.setSelectedIndex(tabbedPane.getTabCount()-1); } } } } }); new FileDrop(listFiles, new FileDrop.Listener() { public void filesDropped(java.io.File[] files) { for (int i = 0; i < files.length; i++) { try { FileFilter filter = new FileNameExtensionFilter("Matroska files (*.mkv; *.mka; *.mk3d) ", "mkv", "mka", "mk3d"); if (!modelFiles.contains(files[i].getCanonicalPath()) && filter.accept(files[i]) && !files[i].isDirectory()) modelFiles.add(modelFiles.getSize(), files[i].getCanonicalPath()); } catch(java.io.IOException e) { } } } }); btnAddFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File[] files = null; chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setDialogTitle("Select Matroska file to edit"); chooser.setMultiSelectionEnabled(true); FileFilter filter = new FileNameExtensionFilter("Matroska files (*.mkv; *.mka; *.mk3d) ", "mkv", "mka", "mk3d"); chooser.resetChoosableFileFilters(); chooser.setFileFilter(filter); int open = chooser.showOpenDialog(frmJMkvpropedit); if (open == JFileChooser.APPROVE_OPTION) { files = chooser.getSelectedFiles(); for (int i = 0; i < files.length; i++) { try { if (!modelFiles.contains(files[i].getCanonicalPath())) modelFiles.add(modelFiles.getSize(), files[i].getCanonicalPath()); } catch (IOException e1) { } } } } }); btnRemoveFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (modelFiles.getSize() > 0) { while (listFiles.getSelectedIndex() != -1) { int[] idx = listFiles.getSelectedIndices(); modelFiles.remove(idx[0]); } } } }); btnClearFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { modelFiles.removeAllElements(); } }); btnTopFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] idx = listFiles.getSelectedIndices(); for (int i = 0; i < idx.length; i++) { int pos = idx[i]; if (pos > 0) { String temp = (String)modelFiles.remove(pos); modelFiles.add(i, temp); listFiles.ensureIndexIsVisible(0); idx[i] = i; } } listFiles.setSelectedIndices(idx); } }); btnUpFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] idx = listFiles.getSelectedIndices(); for (int i = 0; i < idx.length; i++) { int pos = idx[i]; if (pos > 0 && listFiles.getMinSelectionIndex() != 0) { String temp = (String)modelFiles.remove(pos); modelFiles.add(pos-1, temp); listFiles.ensureIndexIsVisible(pos-1); idx[i]--; } } listFiles.setSelectedIndices(idx); } }); btnDownFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] idx = listFiles.getSelectedIndices(); for (int i = idx.length-1; i > -1; i--) { int pos = idx[i]; if (pos < modelFiles.getSize()-1 && listFiles.getMaxSelectionIndex() != modelFiles.getSize()-1) { String temp = (String)modelFiles.remove(pos); modelFiles.add(pos+1, temp); listFiles.ensureIndexIsVisible(pos+1); idx[i]++; } } listFiles.setSelectedIndices(idx); } }); btnBottomFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] idx = listFiles.getSelectedIndices(); int j = 0; for (int i = idx.length-1; i > -1; i--) { int pos = idx[i]; if (pos < modelFiles.getSize()-1 && listFiles.getMaxSelectionIndex() != modelFiles.getSize()-1) { String temp = (String)modelFiles.remove(pos); modelFiles.add(modelFiles.getSize()-j, temp); j++; listFiles.ensureIndexIsVisible(modelFiles.getSize()-1); idx[i] = modelFiles.getSize()-j; } } listFiles.setSelectedIndices(idx); } }); chbTitleGeneral.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean state = txtTitleGeneral.isEnabled(); if (txtTitleGeneral.isEnabled() || chbTitleGeneral.isSelected()) { txtTitleGeneral.setEnabled(!state); cbNumbGeneral.setEnabled(!state); if (cbNumbGeneral.isSelected()) { lblNumbStartGeneral.setEnabled(!state); txtNumbStartGeneral.setEnabled(!state); lblNumbPadGeneral.setEnabled(!state); txtNumbPadGeneral.setEnabled(!state); lblNumbExplainGeneral.setEnabled(!state); } } } }); cbNumbGeneral.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean state = txtNumbStartGeneral.isEnabled(); lblNumbStartGeneral.setEnabled(!state); txtNumbStartGeneral.setEnabled(!state); lblNumbPadGeneral.setEnabled(!state); txtNumbPadGeneral.setEnabled(!state); lblNumbExplainGeneral.setEnabled(!state); } }); txtNumbStartGeneral.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { try { if (Integer.parseInt(txtNumbStartGeneral.getText()) < 0) txtNumbStartGeneral.setText("1"); } catch (NumberFormatException e1) { txtNumbStartGeneral.setText("1"); } } }); txtNumbPadGeneral.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { try { if (Integer.parseInt(txtNumbPadGeneral.getText()) < 0) txtNumbPadGeneral.setText("1"); } catch (NumberFormatException e1) { txtNumbPadGeneral.setText("1"); } } }); chbExtraCmdGeneral.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean state = txtExtraCmdGeneral.isEnabled(); txtExtraCmdGeneral.setEnabled(!state); } }); btnBrowseMkvPropExe.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setDialogTitle("Select mkvpropedit executable"); chooser.setMultiSelectionEnabled(false); FileFilter filter = new FileNameExtensionFilter("Excecutable files (*.exe)", "exe"); chooser.resetChoosableFileFilters(); chooser.setFileFilter(filter); int open = chooser.showOpenDialog(frmJMkvpropedit); if (open == JFileChooser.APPROVE_OPTION) { saveIniFile(chooser.getSelectedFile()); } } }); cbMkvPropExeDef.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (isWindows()) { txtMkvPropExe.setText("mkvpropedit.exe"); cbMkvPropExeDef.setEnabled(false); defaultIniFile(); } else { txtMkvPropExe.setText("/usr/bin/mkvpropedit"); cbMkvPropExeDef.setEnabled(false); defaultIniFile(); } } }); cbVideo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (cbVideo.getItemCount() != 0) lyrdPnlVideo.moveToFront(subPnlVideo[cbVideo.getSelectedIndex()]); } }); btnAddVideo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addVideoTrack(); cbVideo.setSelectedIndex(cbVideo.getItemCount()-1); if (cbVideo.getItemCount() == maxStreams) { btnAddVideo.setEnabled(false); } } }); cbAudio.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (cbAudio.getItemCount() != 0) lyrdPnlAudio.moveToFront(subPnlAudio[cbAudio.getSelectedIndex()]); } }); btnAddAudio.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addAudioTrack(); cbAudio.setSelectedIndex(cbAudio.getItemCount()-1); if (cbAudio.getItemCount() == maxStreams) { btnAddAudio.setEnabled(false); } } }); cbSubtitle.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (cbSubtitle.getItemCount() != 0) lyrdPnlSubtitle.moveToFront(subPnlSubtitle[cbSubtitle.getSelectedIndex()]); } }); btnAddSubtitle.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addSubtitleTrack(); cbSubtitle.setSelectedIndex(cbSubtitle.getItemCount()-1); if (cbSubtitle.getItemCount() == maxStreams) { btnAddSubtitle.setEnabled(false); } } }); } /* Start of track addition operations */ private void addVideoTrack() { if (nVideo < maxStreams) { subPnlVideo[nVideo] = new JPanel(); subPnlVideo[nVideo].setBounds(0, 0, 728, 294); lyrdPnlVideo.add(subPnlVideo[nVideo]); subPnlVideo[nVideo].setLayout(null); chbEditVideo[nVideo] = new JCheckBox("Edit this track"); chbEditVideo[nVideo].setBounds(6, 7, 139, 23); subPnlVideo[nVideo].add(chbEditVideo[nVideo]); chbDefaultVideo[nVideo] = new JCheckBox("Default track"); chbDefaultVideo[nVideo].setEnabled(false); chbDefaultVideo[nVideo].setBounds(6, 32, 91, 23); if (!isWindows()) chbDefaultVideo[nVideo].setBounds(6, 32, 120, 23); subPnlVideo[nVideo].add(chbDefaultVideo[nVideo]); rbYesDefVideo[nVideo] = new JRadioButton("Yes"); rbYesDefVideo[nVideo].setSelected(true); rbYesDefVideo[nVideo].setBounds(99, 32, 46, 23); if (!isWindows()) rbYesDefVideo[nVideo].setBounds(131, 32, 55, 23); rbYesDefVideo[nVideo].setEnabled(false); subPnlVideo[nVideo].add(rbYesDefVideo[nVideo]); rbNoDefVideo[nVideo] = new JRadioButton("No"); rbNoDefVideo[nVideo].setBounds(143, 32, 46, 23); if (!isWindows()) rbNoDefVideo[nVideo].setBounds(194, 32, 46, 23); rbNoDefVideo[nVideo].setEnabled(false); subPnlVideo[nVideo].add(rbNoDefVideo[nVideo]); bgRbDefVideo[nVideo] = new ButtonGroup(); bgRbDefVideo[nVideo].add(rbYesDefVideo[nVideo]); bgRbDefVideo[nVideo].add(rbNoDefVideo[nVideo]); chbForcedVideo[nVideo] = new JCheckBox("Forced track"); chbForcedVideo[nVideo].setEnabled(false); chbForcedVideo[nVideo].setBounds(6, 57, 85, 23); if (!isWindows()) chbForcedVideo[nVideo].setBounds(6, 57, 120, 23); subPnlVideo[nVideo].add(chbForcedVideo[nVideo]); rbYesForcedVideo[nVideo] = new JRadioButton("Yes"); rbYesForcedVideo[nVideo].setSelected(true); rbYesForcedVideo[nVideo].setBounds(99, 57, 46, 23); if (!isWindows()) rbYesForcedVideo[nVideo].setBounds(131, 57, 55, 23); rbYesForcedVideo[nVideo].setEnabled(false); subPnlVideo[nVideo].add(rbYesForcedVideo[nVideo]); rbNoForcedVideo[nVideo] = new JRadioButton("No"); rbNoForcedVideo[nVideo].setBounds(143, 57, 46, 23); if (!isWindows()) rbNoForcedVideo[nVideo].setBounds(194, 57, 46, 23); rbNoForcedVideo[nVideo].setEnabled(false); subPnlVideo[nVideo].add(rbNoForcedVideo[nVideo]); bgRbForcedVideo[nVideo] = new ButtonGroup(); bgRbForcedVideo[nVideo].add(rbYesForcedVideo[nVideo]); bgRbForcedVideo[nVideo].add(rbNoForcedVideo[nVideo]); chbNameVideo[nVideo] = new JCheckBox("Track name"); chbNameVideo[nVideo].setEnabled(false); chbNameVideo[nVideo].setBounds(6, 82, 81, 23); if (!isWindows()) chbNameVideo[nVideo].setBounds(6, 82, 114, 23); subPnlVideo[nVideo].add(chbNameVideo[nVideo]); txtNameVideo[nVideo] = new JTextField(); txtNameVideo[nVideo].setEnabled(false); txtNameVideo[nVideo].setBounds(93, 83, 625, 20); if (!isWindows()) txtNameVideo[nVideo].setBounds(123, 83, 595, 20); subPnlVideo[nVideo].add(txtNameVideo[nVideo]); txtNameVideo[nVideo].setColumns(10); cbNumbVideo[nVideo] = new JCheckBox("Numbering"); cbNumbVideo[nVideo].setEnabled(false); cbNumbVideo[nVideo].setBounds(16, 113, 81, 23); if (!isWindows()) cbNumbVideo[nVideo].setBounds(16, 113, 104, 23); subPnlVideo[nVideo].add(cbNumbVideo[nVideo]); lblNumbStartVideo[nVideo] = new JLabel("Start"); lblNumbStartVideo[nVideo].setEnabled(false); lblNumbStartVideo[nVideo].setBounds(191, 115, 31, 14); if (!isWindows()) lblNumbStartVideo[nVideo].setBounds(191, 115, 45, 14); subPnlVideo[nVideo].add(lblNumbStartVideo[nVideo]); txtNumbStartVideo[nVideo] = new JTextField(); txtNumbStartVideo[nVideo].setEnabled(false); txtNumbStartVideo[nVideo].setText("1"); txtNumbStartVideo[nVideo].setBounds(220, 113, 70, 20); if (!isWindows()) txtNumbStartVideo[nVideo].setBounds(232, 113, 70, 20); subPnlVideo[nVideo].add(txtNumbStartVideo[nVideo]); txtNumbStartVideo[nVideo].setColumns(10); lblNumbPadVideo[nVideo] = new JLabel("Padding"); lblNumbPadVideo[nVideo].setEnabled(false); lblNumbPadVideo[nVideo].setBounds(322, 115, 45, 14); if (!isWindows()) lblNumbPadVideo[nVideo].setBounds(337, 115, 64, 14); subPnlVideo[nVideo].add(lblNumbPadVideo[nVideo]); txtNumbPadVideo[nVideo] = new JTextField(); txtNumbPadVideo[nVideo].setEnabled(false); txtNumbPadVideo[nVideo].setText("1"); txtNumbPadVideo[nVideo].setBounds(366, 113, 70, 20); if (!isWindows()) txtNumbPadVideo[nVideo].setBounds(402, 113, 70, 20); subPnlVideo[nVideo].add(txtNumbPadVideo[nVideo]); txtNumbPadVideo[nVideo].setColumns(10); lblNumbExplainVideo[nVideo] = new JLabel("To use it, add {num} to track name (e.g. \"My Video {num}\")"); lblNumbExplainVideo[nVideo].setEnabled(false); lblNumbExplainVideo[nVideo].setBounds(33, 143, 473, 14); if (!isWindows()) lblNumbExplainVideo[nVideo].setBounds(33, 143, 473, 14); subPnlVideo[nVideo].add(lblNumbExplainVideo[nVideo]); chbLangVideo[nVideo] = new JCheckBox("Language"); chbLangVideo[nVideo].setEnabled(false); chbLangVideo[nVideo].setBounds(6, 164, 73, 23); if (!isWindows()) chbLangVideo[nVideo].setBounds(6, 164, 104, 23); subPnlVideo[nVideo].add(chbLangVideo[nVideo]); cbLangVideo[nVideo] = new JComboBox(); cbLangVideo[nVideo].setEnabled(false); cbLangVideo[nVideo].setBounds(93, 164, 430, 20); if (!isWindows()) cbLangVideo[nVideo].setBounds(123, 164, 595, 20); cbLangVideo[nVideo].setModel(new DefaultComboBoxModel(mkvLang.getLangName())); subPnlVideo[nVideo].add(cbLangVideo[nVideo]); int pos = mkvLang.getAsLangCode().indexOf("und"); cbLangVideo[nVideo].setSelectedIndex(pos); chbExtraCmdVideo[nVideo] = new JCheckBox("Extra parameters"); chbExtraCmdVideo[nVideo].setEnabled(false); chbExtraCmdVideo[nVideo].setBounds(6, 190, 109, 23); if (!isWindows()) chbExtraCmdVideo[nVideo].setBounds(6, 190, 153, 23); subPnlVideo[nVideo].add(chbExtraCmdVideo[nVideo]); txtExtraCmdVideo[nVideo] = new JTextField(); txtExtraCmdVideo[nVideo].setEnabled(false); txtExtraCmdVideo[nVideo].setBounds(126, 191, 592, 20); if (!isWindows()) txtExtraCmdVideo[nVideo].setBounds(165, 191, 553, 20); subPnlVideo[nVideo].add(txtExtraCmdVideo[nVideo]); txtExtraCmdVideo[nVideo].setColumns(10); chbEditVideo[nVideo].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); boolean state = chbDefaultVideo[curCbVideo].isEnabled(); chbDefaultVideo[curCbVideo].setEnabled(!state); chbForcedVideo[curCbVideo].setEnabled(!state); chbNameVideo[curCbVideo].setEnabled(!state); chbLangVideo[curCbVideo].setEnabled(!state); chbExtraCmdVideo[curCbVideo].setEnabled(!state); if (txtNameVideo[curCbVideo].isEnabled() || chbNameVideo[curCbVideo].isSelected()) { txtNameVideo[curCbVideo].setEnabled(!state); cbNumbVideo[curCbVideo].setEnabled(!state); if (cbNumbVideo[curCbVideo].isSelected()) { lblNumbStartVideo[curCbVideo].setEnabled(!state); txtNumbStartVideo[curCbVideo].setEnabled(!state); lblNumbPadVideo[curCbVideo].setEnabled(!state); txtNumbPadVideo[curCbVideo].setEnabled(!state); lblNumbExplainVideo[curCbVideo].setEnabled(!state); } } if (rbNoDefVideo[curCbVideo].isEnabled() || chbDefaultVideo[curCbVideo].isSelected()) { rbNoDefVideo[curCbVideo].setEnabled(!state); rbYesDefVideo[curCbVideo].setEnabled(!state); } if (rbNoForcedVideo[curCbVideo].isEnabled() || chbForcedVideo[curCbVideo].isSelected()) { rbNoForcedVideo[curCbVideo].setEnabled(!state); rbYesForcedVideo[curCbVideo].setEnabled(!state); } if (cbLangVideo[curCbVideo].isEnabled() || chbLangVideo[curCbVideo].isSelected()) { cbLangVideo[curCbVideo].setEnabled(!state); } if (txtExtraCmdVideo[curCbVideo].isEnabled() || chbExtraCmdVideo[curCbVideo].isSelected()) { chbExtraCmdVideo[curCbVideo].setEnabled(!state); txtExtraCmdVideo[curCbVideo].setEnabled(!state); } } }); chbNameVideo[nVideo].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); boolean state = cbNumbVideo[curCbVideo].isEnabled(); cbNumbVideo[curCbVideo].setEnabled(!state); txtNameVideo[curCbVideo].setEnabled(!state); if (cbNumbVideo[curCbVideo].isSelected()) { lblNumbStartVideo[curCbVideo].setEnabled(!state); txtNumbStartVideo[curCbVideo].setEnabled(!state); lblNumbPadVideo[curCbVideo].setEnabled(!state); txtNumbPadVideo[curCbVideo].setEnabled(!state); lblNumbExplainVideo[curCbVideo].setEnabled(!state); } } }); chbDefaultVideo[nVideo].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); boolean state = rbNoDefVideo[curCbVideo].isEnabled(); rbNoDefVideo[curCbVideo].setEnabled(!state); rbYesDefVideo[curCbVideo].setEnabled(!state); } }); chbForcedVideo[nVideo].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); boolean state = rbNoForcedVideo[curCbVideo].isEnabled(); rbNoForcedVideo[curCbVideo].setEnabled(!state); rbYesForcedVideo[curCbVideo].setEnabled(!state); } }); cbNumbVideo[nVideo].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); boolean state = txtNumbStartVideo[curCbVideo].isEnabled(); lblNumbStartVideo[curCbVideo].setEnabled(!state); txtNumbStartVideo[curCbVideo].setEnabled(!state); lblNumbPadVideo[curCbVideo].setEnabled(!state); txtNumbPadVideo[curCbVideo].setEnabled(!state); lblNumbExplainVideo[curCbVideo].setEnabled(!state); } }); chbLangVideo[nVideo].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); boolean state = cbLangVideo[curCbVideo].isEnabled(); cbLangVideo[curCbVideo].setEnabled(!state); } }); txtNumbStartVideo[nVideo].addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); try { if (Integer.parseInt(txtNumbStartVideo[curCbVideo].getText()) < 0) txtNumbStartVideo[curCbVideo].setText("1"); } catch (NumberFormatException e1) { txtNumbStartVideo[curCbVideo].setText("1"); } } }); txtNumbPadVideo[nVideo].addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); try { if (Integer.parseInt(txtNumbPadVideo[curCbVideo].getText()) < 0) txtNumbPadVideo[curCbVideo].setText("1"); } catch (NumberFormatException e1) { txtNumbPadVideo[curCbVideo].setText("1"); } } }); chbExtraCmdVideo[nVideo].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbVideo = cbVideo.getSelectedIndex(); boolean state = txtExtraCmdVideo[curCbVideo].isEnabled(); txtExtraCmdVideo[curCbVideo].setEnabled(!state); } }); cbVideo.addItem("Video Track " + (nVideo+1)); } nVideo++; } private void addAudioTrack() { if (nAudio < maxStreams) { subPnlAudio[nAudio] = new JPanel(); subPnlAudio[nAudio].setBounds(0, 0, 728, 294); lyrdPnlAudio.add(subPnlAudio[nAudio]); subPnlAudio[nAudio].setLayout(null); chbEditAudio[nAudio] = new JCheckBox("Edit this track"); chbEditAudio[nAudio].setBounds(6, 7, 139, 23); subPnlAudio[nAudio].add(chbEditAudio[nAudio]); chbDefaultAudio[nAudio] = new JCheckBox("Default track"); chbDefaultAudio[nAudio].setEnabled(false); chbDefaultAudio[nAudio].setBounds(6, 32, 91, 23); if (!isWindows()) chbDefaultAudio[nAudio].setBounds(6, 32, 120, 23); subPnlAudio[nAudio].add(chbDefaultAudio[nAudio]); rbYesDefAudio[nAudio] = new JRadioButton("Yes"); rbYesDefAudio[nAudio].setSelected(true); rbYesDefAudio[nAudio].setBounds(99, 32, 46, 23); if (!isWindows()) rbYesDefAudio[nAudio].setBounds(131, 32, 55, 23); rbYesDefAudio[nAudio].setEnabled(false); subPnlAudio[nAudio].add(rbYesDefAudio[nAudio]); rbNoDefAudio[nAudio] = new JRadioButton("No"); rbNoDefAudio[nAudio].setBounds(143, 32, 46, 23); if (!isWindows()) rbNoDefAudio[nAudio].setBounds(194, 32, 46, 23); rbNoDefAudio[nAudio].setEnabled(false); subPnlAudio[nAudio].add(rbNoDefAudio[nAudio]); bgRbDefAudio[nAudio] = new ButtonGroup(); bgRbDefAudio[nAudio].add(rbYesDefAudio[nAudio]); bgRbDefAudio[nAudio].add(rbNoDefAudio[nAudio]); chbForcedAudio[nAudio] = new JCheckBox("Forced track"); chbForcedAudio[nAudio].setEnabled(false); chbForcedAudio[nAudio].setBounds(6, 57, 85, 23); if (!isWindows()) chbForcedAudio[nAudio].setBounds(6, 57, 120, 23); subPnlAudio[nAudio].add(chbForcedAudio[nAudio]); rbYesForcedAudio[nAudio] = new JRadioButton("Yes"); rbYesForcedAudio[nAudio].setSelected(true); rbYesForcedAudio[nAudio].setBounds(99, 57, 46, 23); if (!isWindows()) rbYesForcedAudio[nAudio].setBounds(131, 57, 55, 23); rbYesForcedAudio[nAudio].setEnabled(false); subPnlAudio[nAudio].add(rbYesForcedAudio[nAudio]); rbNoForcedAudio[nAudio] = new JRadioButton("No"); rbNoForcedAudio[nAudio].setBounds(143, 57, 46, 23); if (!isWindows()) rbNoForcedAudio[nAudio].setBounds(194, 57, 46, 23); rbNoForcedAudio[nAudio].setEnabled(false); subPnlAudio[nAudio].add(rbNoForcedAudio[nAudio]); bgRbForcedAudio[nAudio] = new ButtonGroup(); bgRbForcedAudio[nAudio].add(rbYesForcedAudio[nAudio]); bgRbForcedAudio[nAudio].add(rbNoForcedAudio[nAudio]); chbNameAudio[nAudio] = new JCheckBox("Track name"); chbNameAudio[nAudio].setEnabled(false); chbNameAudio[nAudio].setBounds(6, 82, 81, 23); if (!isWindows()) chbNameAudio[nAudio].setBounds(6, 82, 114, 23); subPnlAudio[nAudio].add(chbNameAudio[nAudio]); txtNameAudio[nAudio] = new JTextField(); txtNameAudio[nAudio].setEnabled(false); txtNameAudio[nAudio].setBounds(93, 83, 625, 20); if (!isWindows()) txtNameAudio[nAudio].setBounds(123, 83, 595, 20); subPnlAudio[nAudio].add(txtNameAudio[nAudio]); txtNameAudio[nAudio].setColumns(10); cbNumbAudio[nAudio] = new JCheckBox("Numbering"); cbNumbAudio[nAudio].setEnabled(false); cbNumbAudio[nAudio].setBounds(16, 113, 81, 23); if (!isWindows()) cbNumbAudio[nAudio].setBounds(16, 113, 104, 23); subPnlAudio[nAudio].add(cbNumbAudio[nAudio]); lblNumbStartAudio[nAudio] = new JLabel("Start"); lblNumbStartAudio[nAudio].setEnabled(false); lblNumbStartAudio[nAudio].setBounds(191, 115, 31, 14); if (!isWindows()) lblNumbStartAudio[nAudio].setBounds(191, 115, 45, 14); subPnlAudio[nAudio].add(lblNumbStartAudio[nAudio]); txtNumbStartAudio[nAudio] = new JTextField(); txtNumbStartAudio[nAudio].setEnabled(false); txtNumbStartAudio[nAudio].setText("1"); txtNumbStartAudio[nAudio].setBounds(220, 113, 70, 20); if (!isWindows()) txtNumbStartAudio[nAudio].setBounds(232, 113, 70, 20); subPnlAudio[nAudio].add(txtNumbStartAudio[nAudio]); txtNumbStartAudio[nAudio].setColumns(10); lblNumbPadAudio[nAudio] = new JLabel("Padding"); lblNumbPadAudio[nAudio].setEnabled(false); lblNumbPadAudio[nAudio].setBounds(322, 115, 45, 14); if (!isWindows()) lblNumbPadAudio[nAudio].setBounds(337, 115, 64, 14); subPnlAudio[nAudio].add(lblNumbPadAudio[nAudio]); txtNumbPadAudio[nAudio] = new JTextField(); txtNumbPadAudio[nAudio].setEnabled(false); txtNumbPadAudio[nAudio].setText("1"); txtNumbPadAudio[nAudio].setBounds(366, 113, 70, 20); if (!isWindows()) txtNumbPadAudio[nAudio].setBounds(402, 113, 70, 20); subPnlAudio[nAudio].add(txtNumbPadAudio[nAudio]); txtNumbPadAudio[nAudio].setColumns(10); lblNumbExplainAudio[nAudio] = new JLabel("To use it, add {num} to track name (e.g. \"My Audio {num}\")"); lblNumbExplainAudio[nAudio].setEnabled(false); lblNumbExplainAudio[nAudio].setBounds(33, 143, 473, 14); if (!isWindows()) lblNumbExplainAudio[nAudio].setBounds(33, 143, 473, 14); subPnlAudio[nAudio].add(lblNumbExplainAudio[nAudio]); chbLangAudio[nAudio] = new JCheckBox("Language"); chbLangAudio[nAudio].setEnabled(false); chbLangAudio[nAudio].setBounds(6, 164, 73, 23); if (!isWindows()) chbLangAudio[nAudio].setBounds(6, 164, 104, 23); subPnlAudio[nAudio].add(chbLangAudio[nAudio]); cbLangAudio[nAudio] = new JComboBox(); cbLangAudio[nAudio].setEnabled(false); cbLangAudio[nAudio].setBounds(93, 164, 430, 20); if (!isWindows()) cbLangAudio[nAudio].setBounds(123, 164, 595, 20); cbLangAudio[nAudio].setModel(new DefaultComboBoxModel(mkvLang.getLangName())); subPnlAudio[nAudio].add(cbLangAudio[nAudio]); int pos = mkvLang.getAsLangCode().indexOf("und"); cbLangAudio[nAudio].setSelectedIndex(pos); chbExtraCmdAudio[nAudio] = new JCheckBox("Extra parameters"); chbExtraCmdAudio[nAudio].setEnabled(false); chbExtraCmdAudio[nAudio].setBounds(6, 190, 109, 23); if (!isWindows()) chbExtraCmdAudio[nAudio].setBounds(6, 190, 153, 23); subPnlAudio[nAudio].add(chbExtraCmdAudio[nAudio]); txtExtraCmdAudio[nAudio] = new JTextField(); txtExtraCmdAudio[nAudio].setEnabled(false); txtExtraCmdAudio[nAudio].setBounds(126, 191, 592, 20); if (!isWindows()) txtExtraCmdAudio[nAudio].setBounds(165, 191, 553, 20); subPnlAudio[nAudio].add(txtExtraCmdAudio[nAudio]); txtExtraCmdAudio[nAudio].setColumns(10); chbEditAudio[nAudio].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); boolean state = chbDefaultAudio[curCbAudio].isEnabled(); chbDefaultAudio[curCbAudio].setEnabled(!state); chbForcedAudio[curCbAudio].setEnabled(!state); chbNameAudio[curCbAudio].setEnabled(!state); chbLangAudio[curCbAudio].setEnabled(!state); chbExtraCmdAudio[curCbAudio].setEnabled(!state); if (txtNameAudio[curCbAudio].isEnabled() || chbNameAudio[curCbAudio].isSelected()) { txtNameAudio[curCbAudio].setEnabled(!state); cbNumbAudio[curCbAudio].setEnabled(!state); if (cbNumbAudio[curCbAudio].isSelected()) { lblNumbStartAudio[curCbAudio].setEnabled(!state); txtNumbStartAudio[curCbAudio].setEnabled(!state); lblNumbPadAudio[curCbAudio].setEnabled(!state); txtNumbPadAudio[curCbAudio].setEnabled(!state); lblNumbExplainAudio[curCbAudio].setEnabled(!state); } } if (rbNoDefAudio[curCbAudio].isEnabled() || chbDefaultAudio[curCbAudio].isSelected()) { rbNoDefAudio[curCbAudio].setEnabled(!state); rbYesDefAudio[curCbAudio].setEnabled(!state); } if (rbNoForcedAudio[curCbAudio].isEnabled() || chbForcedAudio[curCbAudio].isSelected()) { rbNoForcedAudio[curCbAudio].setEnabled(!state); rbYesForcedAudio[curCbAudio].setEnabled(!state); } if (cbLangAudio[curCbAudio].isEnabled() || chbLangAudio[curCbAudio].isSelected()) { cbLangAudio[curCbAudio].setEnabled(!state); } if (txtExtraCmdAudio[curCbAudio].isEnabled() || chbExtraCmdAudio[curCbAudio].isSelected()) { chbExtraCmdAudio[curCbAudio].setEnabled(!state); txtExtraCmdAudio[curCbAudio].setEnabled(!state); } } }); chbNameAudio[nAudio].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); boolean state = cbNumbAudio[curCbAudio].isEnabled(); cbNumbAudio[curCbAudio].setEnabled(!state); txtNameAudio[curCbAudio].setEnabled(!state); if (cbNumbAudio[curCbAudio].isSelected()) { lblNumbStartAudio[curCbAudio].setEnabled(!state); txtNumbStartAudio[curCbAudio].setEnabled(!state); lblNumbPadAudio[curCbAudio].setEnabled(!state); txtNumbPadAudio[curCbAudio].setEnabled(!state); lblNumbExplainAudio[curCbAudio].setEnabled(!state); } } }); chbDefaultAudio[nAudio].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); boolean state = rbNoDefAudio[curCbAudio].isEnabled(); rbNoDefAudio[curCbAudio].setEnabled(!state); rbYesDefAudio[curCbAudio].setEnabled(!state); } }); chbForcedAudio[nAudio].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); boolean state = rbNoForcedAudio[curCbAudio].isEnabled(); rbNoForcedAudio[curCbAudio].setEnabled(!state); rbYesForcedAudio[curCbAudio].setEnabled(!state); } }); cbNumbAudio[nAudio].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); boolean state = txtNumbStartAudio[curCbAudio].isEnabled(); lblNumbStartAudio[curCbAudio].setEnabled(!state); txtNumbStartAudio[curCbAudio].setEnabled(!state); lblNumbPadAudio[curCbAudio].setEnabled(!state); txtNumbPadAudio[curCbAudio].setEnabled(!state); lblNumbExplainAudio[curCbAudio].setEnabled(!state); } }); chbLangAudio[nAudio].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); boolean state = cbLangAudio[curCbAudio].isEnabled(); cbLangAudio[curCbAudio].setEnabled(!state); } }); txtNumbStartAudio[nAudio].addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); try { if (Integer.parseInt(txtNumbStartAudio[curCbAudio].getText()) < 0) txtNumbStartAudio[curCbAudio].setText("1"); } catch (NumberFormatException e1) { txtNumbStartAudio[curCbAudio].setText("1"); } } }); txtNumbPadAudio[nAudio].addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); try { if (Integer.parseInt(txtNumbPadAudio[curCbAudio].getText()) < 0) txtNumbPadAudio[curCbAudio].setText("1"); } catch (NumberFormatException e1) { txtNumbPadAudio[curCbAudio].setText("1"); } } }); chbExtraCmdAudio[nAudio].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbAudio = cbAudio.getSelectedIndex(); boolean state = txtExtraCmdAudio[curCbAudio].isEnabled(); txtExtraCmdAudio[curCbAudio].setEnabled(!state); } }); cbAudio.addItem("Audio Track " + (nAudio+1)); } nAudio++; } private void addSubtitleTrack() { if (nSubtitle < maxStreams) { subPnlSubtitle[nSubtitle] = new JPanel(); subPnlSubtitle[nSubtitle].setBounds(0, 0, 728, 294); lyrdPnlSubtitle.add(subPnlSubtitle[nSubtitle]); subPnlSubtitle[nSubtitle].setLayout(null); chbEditSubtitle[nSubtitle] = new JCheckBox("Edit this track"); chbEditSubtitle[nSubtitle].setBounds(6, 7, 139, 23); subPnlSubtitle[nSubtitle].add(chbEditSubtitle[nSubtitle]); chbDefaultSubtitle[nSubtitle] = new JCheckBox("Default track"); chbDefaultSubtitle[nSubtitle].setEnabled(false); chbDefaultSubtitle[nSubtitle].setBounds(6, 32, 91, 23); if (!isWindows()) chbDefaultSubtitle[nSubtitle].setBounds(6, 32, 120, 23); subPnlSubtitle[nSubtitle].add(chbDefaultSubtitle[nSubtitle]); rbYesDefSubtitle[nSubtitle] = new JRadioButton("Yes"); rbYesDefSubtitle[nSubtitle].setSelected(true); rbYesDefSubtitle[nSubtitle].setBounds(99, 32, 46, 23); if (!isWindows()) rbYesDefSubtitle[nSubtitle].setBounds(131, 32, 55, 23); rbYesDefSubtitle[nSubtitle].setEnabled(false); subPnlSubtitle[nSubtitle].add(rbYesDefSubtitle[nSubtitle]); rbNoDefSubtitle[nSubtitle] = new JRadioButton("No"); rbNoDefSubtitle[nSubtitle].setBounds(143, 32, 46, 23); if (!isWindows()) rbNoDefSubtitle[nSubtitle].setBounds(194, 32, 46, 23); rbNoDefSubtitle[nSubtitle].setEnabled(false); subPnlSubtitle[nSubtitle].add(rbNoDefSubtitle[nSubtitle]); bgRbDefSubtitle[nSubtitle] = new ButtonGroup(); bgRbDefSubtitle[nSubtitle].add(rbYesDefSubtitle[nSubtitle]); bgRbDefSubtitle[nSubtitle].add(rbNoDefSubtitle[nSubtitle]); chbForcedSubtitle[nSubtitle] = new JCheckBox("Forced track"); chbForcedSubtitle[nSubtitle].setEnabled(false); chbForcedSubtitle[nSubtitle].setBounds(6, 57, 85, 23); if (!isWindows()) chbForcedSubtitle[nSubtitle].setBounds(6, 57, 120, 23); subPnlSubtitle[nSubtitle].add(chbForcedSubtitle[nSubtitle]); rbYesForcedSubtitle[nSubtitle] = new JRadioButton("Yes"); rbYesForcedSubtitle[nSubtitle].setSelected(true); rbYesForcedSubtitle[nSubtitle].setBounds(99, 57, 46, 23); if (!isWindows()) rbYesForcedSubtitle[nSubtitle].setBounds(131, 57, 55, 23); rbYesForcedSubtitle[nSubtitle].setEnabled(false); subPnlSubtitle[nSubtitle].add(rbYesForcedSubtitle[nSubtitle]); rbNoForcedSubtitle[nSubtitle] = new JRadioButton("No"); rbNoForcedSubtitle[nSubtitle].setBounds(143, 57, 46, 23); if (!isWindows()) rbNoForcedSubtitle[nSubtitle].setBounds(194, 57, 46, 23); rbNoForcedSubtitle[nSubtitle].setEnabled(false); subPnlSubtitle[nSubtitle].add(rbNoForcedSubtitle[nSubtitle]); bgRbForcedSubtitle[nSubtitle] = new ButtonGroup(); bgRbForcedSubtitle[nSubtitle].add(rbYesForcedSubtitle[nSubtitle]); bgRbForcedSubtitle[nSubtitle].add(rbNoForcedSubtitle[nSubtitle]); chbNameSubtitle[nSubtitle] = new JCheckBox("Track name"); chbNameSubtitle[nSubtitle].setEnabled(false); chbNameSubtitle[nSubtitle].setBounds(6, 82, 81, 23); if (!isWindows()) chbNameSubtitle[nSubtitle].setBounds(6, 82, 114, 23); subPnlSubtitle[nSubtitle].add(chbNameSubtitle[nSubtitle]); txtNameSubtitle[nSubtitle] = new JTextField(); txtNameSubtitle[nSubtitle].setEnabled(false); txtNameSubtitle[nSubtitle].setBounds(93, 83, 625, 20); if (!isWindows()) txtNameSubtitle[nSubtitle].setBounds(123, 83, 595, 20); subPnlSubtitle[nSubtitle].add(txtNameSubtitle[nSubtitle]); txtNameSubtitle[nSubtitle].setColumns(10); cbNumbSubtitle[nSubtitle] = new JCheckBox("Numbering"); cbNumbSubtitle[nSubtitle].setEnabled(false); cbNumbSubtitle[nSubtitle].setBounds(16, 113, 81, 23); if (!isWindows()) cbNumbSubtitle[nSubtitle].setBounds(16, 113, 104, 23); subPnlSubtitle[nSubtitle].add(cbNumbSubtitle[nSubtitle]); lblNumbStartSubtitle[nSubtitle] = new JLabel("Start"); lblNumbStartSubtitle[nSubtitle].setEnabled(false); lblNumbStartSubtitle[nSubtitle].setBounds(191, 115, 31, 14); if (!isWindows()) lblNumbStartSubtitle[nSubtitle].setBounds(191, 115, 45, 14); subPnlSubtitle[nSubtitle].add(lblNumbStartSubtitle[nSubtitle]); txtNumbStartSubtitle[nSubtitle] = new JTextField(); txtNumbStartSubtitle[nSubtitle].setEnabled(false); txtNumbStartSubtitle[nSubtitle].setText("1"); txtNumbStartSubtitle[nSubtitle].setBounds(220, 113, 70, 20); if (!isWindows()) txtNumbStartSubtitle[nSubtitle].setBounds(232, 113, 70, 20); subPnlSubtitle[nSubtitle].add(txtNumbStartSubtitle[nSubtitle]); txtNumbStartSubtitle[nSubtitle].setColumns(10); lblNumbPadSubtitle[nSubtitle] = new JLabel("Padding"); lblNumbPadSubtitle[nSubtitle].setEnabled(false); lblNumbPadSubtitle[nSubtitle].setBounds(322, 115, 45, 14); if (!isWindows()) lblNumbPadSubtitle[nSubtitle].setBounds(337, 115, 64, 14); subPnlSubtitle[nSubtitle].add(lblNumbPadSubtitle[nSubtitle]); txtNumbPadSubtitle[nSubtitle] = new JTextField(); txtNumbPadSubtitle[nSubtitle].setEnabled(false); txtNumbPadSubtitle[nSubtitle].setText("1"); txtNumbPadSubtitle[nSubtitle].setBounds(366, 113, 70, 20); if (!isWindows()) txtNumbPadSubtitle[nSubtitle].setBounds(402, 113, 70, 20); subPnlSubtitle[nSubtitle].add(txtNumbPadSubtitle[nSubtitle]); txtNumbPadSubtitle[nSubtitle].setColumns(10); lblNumbExplainSubtitle[nSubtitle] = new JLabel("To use it, add {num} to track name (e.g. \"My Subtitle {num}\")"); lblNumbExplainSubtitle[nSubtitle].setEnabled(false); lblNumbExplainSubtitle[nSubtitle].setBounds(33, 143, 473, 14); if (!isWindows()) lblNumbExplainSubtitle[nSubtitle].setBounds(33, 143, 473, 14); subPnlSubtitle[nSubtitle].add(lblNumbExplainSubtitle[nSubtitle]); chbLangSubtitle[nSubtitle] = new JCheckBox("Language"); chbLangSubtitle[nSubtitle].setEnabled(false); chbLangSubtitle[nSubtitle].setBounds(6, 164, 73, 23); if (!isWindows()) chbLangSubtitle[nSubtitle].setBounds(6, 164, 104, 23); subPnlSubtitle[nSubtitle].add(chbLangSubtitle[nSubtitle]); cbLangSubtitle[nSubtitle] = new JComboBox(); cbLangSubtitle[nSubtitle].setEnabled(false); cbLangSubtitle[nSubtitle].setBounds(93, 164, 430, 20); if (!isWindows()) cbLangSubtitle[nSubtitle].setBounds(123, 164, 595, 20); cbLangSubtitle[nSubtitle].setModel(new DefaultComboBoxModel(mkvLang.getLangName())); subPnlSubtitle[nSubtitle].add(cbLangSubtitle[nSubtitle]); int pos = mkvLang.getAsLangCode().indexOf("und"); cbLangSubtitle[nSubtitle].setSelectedIndex(pos); chbExtraCmdSubtitle[nSubtitle] = new JCheckBox("Extra parameters"); chbExtraCmdSubtitle[nSubtitle].setEnabled(false); chbExtraCmdSubtitle[nSubtitle].setBounds(6, 190, 109, 23); if (!isWindows()) chbExtraCmdSubtitle[nSubtitle].setBounds(6, 190, 153, 23); subPnlSubtitle[nSubtitle].add(chbExtraCmdSubtitle[nSubtitle]); txtExtraCmdSubtitle[nSubtitle] = new JTextField(); txtExtraCmdSubtitle[nSubtitle].setEnabled(false); txtExtraCmdSubtitle[nSubtitle].setBounds(126, 191, 592, 20); if (!isWindows()) txtExtraCmdSubtitle[nSubtitle].setBounds(165, 191, 553, 20); subPnlSubtitle[nSubtitle].add(txtExtraCmdSubtitle[nSubtitle]); txtExtraCmdSubtitle[nSubtitle].setColumns(10); chbEditSubtitle[nSubtitle].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); boolean state = chbDefaultSubtitle[curCbSubtitle].isEnabled(); chbDefaultSubtitle[curCbSubtitle].setEnabled(!state); chbForcedSubtitle[curCbSubtitle].setEnabled(!state); chbNameSubtitle[curCbSubtitle].setEnabled(!state); chbLangSubtitle[curCbSubtitle].setEnabled(!state); chbExtraCmdSubtitle[curCbSubtitle].setEnabled(!state); if (txtNameSubtitle[curCbSubtitle].isEnabled() || chbNameSubtitle[curCbSubtitle].isSelected()) { txtNameSubtitle[curCbSubtitle].setEnabled(!state); cbNumbSubtitle[curCbSubtitle].setEnabled(!state); if (cbNumbSubtitle[curCbSubtitle].isSelected()) { lblNumbStartSubtitle[curCbSubtitle].setEnabled(!state); txtNumbStartSubtitle[curCbSubtitle].setEnabled(!state); lblNumbPadSubtitle[curCbSubtitle].setEnabled(!state); txtNumbPadSubtitle[curCbSubtitle].setEnabled(!state); lblNumbExplainSubtitle[curCbSubtitle].setEnabled(!state); } } if (rbNoDefSubtitle[curCbSubtitle].isEnabled() || chbDefaultSubtitle[curCbSubtitle].isSelected()) { rbNoDefSubtitle[curCbSubtitle].setEnabled(!state); rbYesDefSubtitle[curCbSubtitle].setEnabled(!state); } if (rbNoForcedSubtitle[curCbSubtitle].isEnabled() || chbForcedSubtitle[curCbSubtitle].isSelected()) { rbNoForcedSubtitle[curCbSubtitle].setEnabled(!state); rbYesForcedSubtitle[curCbSubtitle].setEnabled(!state); } if (cbLangSubtitle[curCbSubtitle].isEnabled() || chbLangSubtitle[curCbSubtitle].isSelected()) { cbLangSubtitle[curCbSubtitle].setEnabled(!state); } if (txtExtraCmdSubtitle[curCbSubtitle].isEnabled() || chbExtraCmdSubtitle[curCbSubtitle].isSelected()) { chbExtraCmdSubtitle[curCbSubtitle].setEnabled(!state); txtExtraCmdSubtitle[curCbSubtitle].setEnabled(!state); } } }); chbNameSubtitle[nSubtitle].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); boolean state = cbNumbSubtitle[curCbSubtitle].isEnabled(); cbNumbSubtitle[curCbSubtitle].setEnabled(!state); txtNameSubtitle[curCbSubtitle].setEnabled(!state); if (cbNumbSubtitle[curCbSubtitle].isSelected()) { lblNumbStartSubtitle[curCbSubtitle].setEnabled(!state); txtNumbStartSubtitle[curCbSubtitle].setEnabled(!state); lblNumbPadSubtitle[curCbSubtitle].setEnabled(!state); txtNumbPadSubtitle[curCbSubtitle].setEnabled(!state); lblNumbExplainSubtitle[curCbSubtitle].setEnabled(!state); } } }); chbDefaultSubtitle[nSubtitle].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); boolean state = rbNoDefSubtitle[curCbSubtitle].isEnabled(); rbNoDefSubtitle[curCbSubtitle].setEnabled(!state); rbYesDefSubtitle[curCbSubtitle].setEnabled(!state); } }); chbForcedSubtitle[nSubtitle].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); boolean state = rbNoForcedSubtitle[curCbSubtitle].isEnabled(); rbNoForcedSubtitle[curCbSubtitle].setEnabled(!state); rbYesForcedSubtitle[curCbSubtitle].setEnabled(!state); } }); cbNumbSubtitle[nSubtitle].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); boolean state = txtNumbStartSubtitle[curCbSubtitle].isEnabled(); lblNumbStartSubtitle[curCbSubtitle].setEnabled(!state); txtNumbStartSubtitle[curCbSubtitle].setEnabled(!state); lblNumbPadSubtitle[curCbSubtitle].setEnabled(!state); txtNumbPadSubtitle[curCbSubtitle].setEnabled(!state); lblNumbExplainSubtitle[curCbSubtitle].setEnabled(!state); } }); chbLangSubtitle[nSubtitle].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); boolean state = cbLangSubtitle[curCbSubtitle].isEnabled(); cbLangSubtitle[curCbSubtitle].setEnabled(!state); } }); txtNumbStartSubtitle[nSubtitle].addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); try { if (Integer.parseInt(txtNumbStartSubtitle[curCbSubtitle].getText()) < 0) txtNumbStartSubtitle[curCbSubtitle].setText("1"); } catch (NumberFormatException e1) { txtNumbStartSubtitle[curCbSubtitle].setText("1"); } } }); txtNumbPadSubtitle[nSubtitle].addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); try { if (Integer.parseInt(txtNumbPadSubtitle[curCbSubtitle].getText()) < 0) txtNumbPadSubtitle[curCbSubtitle].setText("1"); } catch (NumberFormatException e1) { txtNumbPadSubtitle[curCbSubtitle].setText("1"); } } }); chbExtraCmdSubtitle[nSubtitle].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int curCbSubtitle = cbSubtitle.getSelectedIndex(); boolean state = txtExtraCmdSubtitle[curCbSubtitle].isEnabled(); txtExtraCmdSubtitle[curCbSubtitle].setEnabled(!state); } }); cbSubtitle.addItem("Subtitle Track " + (nSubtitle+1)); } nSubtitle++; } /* End of track addition operations */ /* Start of command line operations */ private void setCmdLineGeneral() { cmdLineGeneral = new String[modelFiles.size()]; cmdLineGeneralOpt = new String[modelFiles.size()]; int start = Integer.parseInt(txtNumbStartGeneral.getText()); for (int i = 0; i < modelFiles.size(); i++) { cmdLineGeneral[i] = ""; cmdLineGeneralOpt[i] = ""; if (chbRemoveTags.isSelected()) { cmdLineGeneral[i] += " --tags all:"; cmdLineGeneralOpt[i] += " --tags all:"; } if (chbRemoveChapters.isSelected()) { cmdLineGeneral[i] += " --chapters \"\""; cmdLineGeneralOpt[i] += " --chapters #EMPTY#"; } if (chbTitleGeneral.isSelected()) { cmdLineGeneral[i] += " --edit info"; cmdLineGeneralOpt[i] += " --edit info"; if (cbNumbGeneral.isSelected()) { int pad = 0; pad = Integer.parseInt(txtNumbPadGeneral.getText()); String newTitle = txtTitleGeneral.getText(); newTitle = newTitle.replace("{num}", padNumber(pad).format(start)); start++; cmdLineGeneral[i] += " --set title=\"" + escapeNameCmdLine(newTitle) + "\""; cmdLineGeneralOpt[i] += " --set title=\"" + escapeName(newTitle) + "\""; } else { cmdLineGeneral[i] += " --set title=\"" + escapeNameCmdLine(txtTitleGeneral.getText()) + "\""; cmdLineGeneralOpt[i] += " --set title=\"" + escapeName(txtTitleGeneral.getText()) + "\""; } } if (chbExtraCmdGeneral.isSelected() && !txtExtraCmdGeneral.getText().trim().isEmpty()) { cmdLineGeneral[i] += " " + txtExtraCmdGeneral.getText(); cmdLineGeneralOpt[i] += " " + txtExtraCmdGeneral.getText(); } } } private void setCmdLineVideo() { cmdLineVideo = new String[modelFiles.size()]; cmdLineVideoOpt = new String[modelFiles.size()]; String[] tmpCmdLineVideo = new String[nVideo]; String[] tmpCmdLineVideoOpt = new String[nVideo]; int[] numStartVideo = new int[nVideo]; int[] numPadVideo = new int[nVideo]; for (int i = 0; i < modelFiles.size(); i++) { int editCount = 0; cmdLineVideo[i] = ""; cmdLineVideoOpt[i] = ""; for (int j = 0; j < nVideo; j++) { if (chbEditVideo[j].isSelected()) { numStartVideo[j] = Integer.parseInt(txtNumbStartVideo[j].getText()); numPadVideo[j] = Integer.parseInt(txtNumbPadVideo[j].getText()); tmpCmdLineVideo[j] = ""; tmpCmdLineVideoOpt[j] = ""; if (chbEditVideo[j].isSelected()) { tmpCmdLineVideo[j] += " --edit track:v" + (j+1); tmpCmdLineVideoOpt[j] += " --edit track:v" + (j+1); } if (chbDefaultVideo[j].isSelected()) { tmpCmdLineVideo[j] += " --set flag-default="; tmpCmdLineVideoOpt[j] += " --set flag-default="; if (rbYesDefVideo[j].isSelected()) { tmpCmdLineVideo[j] += "1"; tmpCmdLineVideoOpt[j] += "1"; } else { tmpCmdLineVideo[j] += "0"; tmpCmdLineVideoOpt[j] += "0"; } editCount++; } if (chbForcedVideo[j].isSelected()) { tmpCmdLineVideo[j] += " --set flag-forced="; tmpCmdLineVideoOpt[j] += " --set flag-forced="; if (rbYesForcedVideo[j].isSelected()) { tmpCmdLineVideo[j] += "1"; tmpCmdLineVideoOpt[j] += "1"; } else { tmpCmdLineVideo[j] += "0"; tmpCmdLineVideoOpt[j] += "0"; } editCount++; } if (chbNameVideo[j].isSelected()) { tmpCmdLineVideo[j] += " --set name=\"" + escapeNameCmdLine(txtNameVideo[j].getText()) + "\""; tmpCmdLineVideoOpt[j] += " --set name=\"" + escapeName(txtNameVideo[j].getText()) + "\""; editCount++; } if (chbLangVideo[j].isSelected()) { String curLangCode = mkvLang.getAsLangCode().get(cbLangVideo[j].getSelectedIndex()); tmpCmdLineVideo[j] += " --set language=\"" + curLangCode + "\""; tmpCmdLineVideoOpt[j] += " --set language=\"" + curLangCode + "\""; editCount++; } if (chbExtraCmdVideo[j].isSelected() && !txtExtraCmdVideo[j].getText().trim().isEmpty()) { tmpCmdLineVideo[j] += " " + txtExtraCmdVideo[j].getText(); tmpCmdLineVideoOpt[j] += " " + txtExtraCmdVideo[j].getText(); editCount++; } if (editCount == 0) { tmpCmdLineVideo[j] = ""; tmpCmdLineVideoOpt[j] = ""; } } else { tmpCmdLineVideo[j] = ""; tmpCmdLineVideoOpt[j] = ""; } } } for (int i = 0; i < nVideo; i++) { for (int j = 0; j < modelFiles.size(); j++) { String tmpText = tmpCmdLineVideo[i]; String tmpText2 = tmpCmdLineVideoOpt[i]; if (cbNumbVideo[i].isSelected() && chbEditVideo[i].isSelected()) { tmpText = tmpText.replace("{num}", padNumber(numPadVideo[i]).format(numStartVideo[i])); tmpText2 = tmpText.replace("{num}", padNumber(numPadVideo[i]).format(numStartVideo[i])); numStartVideo[i]++; } cmdLineVideo[j] += tmpText; cmdLineVideoOpt[j] += tmpText2; } } } private void setCmdLineAudio() { cmdLineAudio = new String[modelFiles.size()]; cmdLineAudioOpt = new String[modelFiles.size()]; String[] tmpCmdLineAudio = new String[nAudio]; String[] tmpCmdLineAudioOpt = new String[nAudio]; int[] numStartAudio = new int[nAudio]; int[] numPadAudio = new int[nAudio]; for (int i = 0; i < modelFiles.size(); i++) { int editCount = 0; cmdLineAudio[i] = ""; cmdLineAudioOpt[i] = ""; for (int j = 0; j < nAudio; j++) { if (chbEditAudio[j].isSelected()) { numStartAudio[j] = Integer.parseInt(txtNumbStartAudio[j].getText()); numPadAudio[j] = Integer.parseInt(txtNumbPadAudio[j].getText()); tmpCmdLineAudio[j] = ""; tmpCmdLineAudioOpt[j] = ""; if (chbEditAudio[j].isSelected()) { tmpCmdLineAudio[j] += " --edit track:a" + (j+1); tmpCmdLineAudioOpt[j] += " --edit track:a" + (j+1); } if (chbDefaultAudio[j].isSelected()) { tmpCmdLineAudio[j] += " --set flag-default="; tmpCmdLineAudioOpt[j] += " --set flag-default="; if (rbYesDefAudio[j].isSelected()) { tmpCmdLineAudio[j] += "1"; tmpCmdLineAudioOpt[j] += "1"; } else { tmpCmdLineAudio[j] += "0"; tmpCmdLineAudioOpt[j] += "0"; } editCount++; } if (chbForcedAudio[j].isSelected()) { tmpCmdLineAudio[j] += " --set flag-forced="; tmpCmdLineAudioOpt[j] += " --set flag-forced="; if (rbYesForcedAudio[j].isSelected()) { tmpCmdLineAudio[j] += "1"; tmpCmdLineAudioOpt[j] += "1"; } else { tmpCmdLineAudio[j] += "0"; tmpCmdLineAudioOpt[j] += "0"; } editCount++; } if (chbNameAudio[j].isSelected()) { tmpCmdLineAudio[j] += " --set name=\"" + escapeNameCmdLine(txtNameAudio[j].getText()) + "\""; tmpCmdLineAudioOpt[j] += " --set name=\"" + escapeName(txtNameAudio[j].getText()) + "\""; editCount++; } if (chbLangAudio[j].isSelected()) { String curLangCode = mkvLang.getAsLangCode().get(cbLangAudio[j].getSelectedIndex()); tmpCmdLineAudio[j] += " --set language=\"" + curLangCode + "\""; tmpCmdLineAudioOpt[j] += " --set language=\"" + curLangCode + "\""; editCount++; } if (chbExtraCmdAudio[j].isSelected() && !txtExtraCmdAudio[j].getText().trim().isEmpty()) { tmpCmdLineAudio[j] += " " + txtExtraCmdAudio[j].getText(); tmpCmdLineAudioOpt[j] += " " + txtExtraCmdAudio[j].getText(); editCount++; } if (editCount == 0) { tmpCmdLineAudio[j] = ""; tmpCmdLineAudioOpt[j] = ""; } } else { tmpCmdLineAudio[j] = ""; tmpCmdLineAudioOpt[j] = ""; } } } for (int i = 0; i < nAudio; i++) { for (int j = 0; j < modelFiles.size(); j++) { String tmpText = tmpCmdLineAudio[i]; String tmpText2 = tmpCmdLineAudioOpt[i]; if (cbNumbAudio[i].isSelected() && chbEditAudio[i].isSelected()) { tmpText = tmpText.replace("{num}", padNumber(numPadAudio[i]).format(numStartAudio[i])); tmpText2 = tmpText.replace("{num}", padNumber(numPadAudio[i]).format(numStartAudio[i])); numStartAudio[i]++; } cmdLineAudio[j] += tmpText; cmdLineAudioOpt[j] += tmpText2; } } } private void setCmdLineSubtitle() { cmdLineSubtitle = new String[modelFiles.size()]; cmdLineSubtitleOpt = new String[modelFiles.size()]; String[] tmpCmdLineSubtitle = new String[nSubtitle]; String[] tmpCmdLineSubtitleOpt = new String[nSubtitle]; int[] numStartSubtitle = new int[nSubtitle]; int[] numPadSubtitle = new int[nSubtitle]; for (int i = 0; i < modelFiles.size(); i++) { int editCount = 0; cmdLineSubtitle[i] = ""; cmdLineSubtitleOpt[i] = ""; for (int j = 0; j < nSubtitle; j++) { if (chbEditSubtitle[j].isSelected()) { numStartSubtitle[j] = Integer.parseInt(txtNumbStartSubtitle[j].getText()); numPadSubtitle[j] = Integer.parseInt(txtNumbPadSubtitle[j].getText()); tmpCmdLineSubtitle[j] = ""; tmpCmdLineSubtitleOpt[j] = ""; if (chbEditSubtitle[j].isSelected()) { tmpCmdLineSubtitle[j] += " --edit track:s" + (j+1); tmpCmdLineSubtitleOpt[j] += " --edit track:s" + (j+1); } if (chbDefaultSubtitle[j].isSelected()) { tmpCmdLineSubtitle[j] += " --set flag-default="; tmpCmdLineSubtitleOpt[j] += " --set flag-default="; if (rbYesDefSubtitle[j].isSelected()) { tmpCmdLineSubtitle[j] += "1"; tmpCmdLineSubtitleOpt[j] += "1"; } else { tmpCmdLineSubtitle[j] += "0"; tmpCmdLineSubtitleOpt[j] += "0"; } editCount++; } if (chbForcedSubtitle[j].isSelected()) { tmpCmdLineSubtitle[j] += " --set flag-forced="; tmpCmdLineSubtitleOpt[j] += " --set flag-forced="; if (rbYesForcedSubtitle[j].isSelected()) { tmpCmdLineSubtitle[j] += "1"; tmpCmdLineSubtitleOpt[j] += "1"; } else { tmpCmdLineSubtitle[j] += "0"; tmpCmdLineSubtitleOpt[j] += "0"; } editCount++; } if (chbNameSubtitle[j].isSelected()) { tmpCmdLineSubtitle[j] += " --set name=\"" + escapeNameCmdLine(txtNameSubtitle[j].getText()) + "\""; tmpCmdLineSubtitleOpt[j] += " --set name=\"" + escapeName(txtNameSubtitle[j].getText()) + "\""; editCount++; } if (chbLangSubtitle[j].isSelected()) { String curLangCode = mkvLang.getAsLangCode().get(cbLangSubtitle[j].getSelectedIndex()); tmpCmdLineSubtitle[j] += " --set language=\"" + curLangCode + "\""; tmpCmdLineSubtitleOpt[j] += " --set language=\"" + curLangCode + "\""; editCount++; } if (chbExtraCmdSubtitle[j].isSelected() && !txtExtraCmdSubtitle[j].getText().trim().isEmpty()) { tmpCmdLineSubtitle[j] += " " + txtExtraCmdSubtitle[j].getText(); tmpCmdLineSubtitleOpt[j] += " " + txtExtraCmdSubtitle[j].getText(); editCount++; } if (editCount == 0) { tmpCmdLineSubtitle[j] = ""; tmpCmdLineSubtitleOpt[j] = ""; } } else { tmpCmdLineSubtitle[j] = ""; tmpCmdLineSubtitleOpt[j] = ""; } } } for (int i = 0; i < nSubtitle; i++) { for (int j = 0; j < modelFiles.size(); j++) { String tmpText = tmpCmdLineSubtitle[i]; String tmpText2 = tmpCmdLineSubtitleOpt[i]; if (cbNumbSubtitle[i].isSelected() && chbEditSubtitle[i].isSelected()) { tmpText = tmpText.replace("{num}", padNumber(numPadSubtitle[i]).format(numStartSubtitle[i])); tmpText2 = tmpText.replace("{num}", padNumber(numPadSubtitle[i]).format(numStartSubtitle[i])); numStartSubtitle[i]++; } cmdLineSubtitle[j] += tmpText; cmdLineSubtitleOpt[j] += tmpText2; } } } private void setCmdLine() { setCmdLineGeneral(); setCmdLineVideo(); setCmdLineAudio(); setCmdLineSubtitle(); cmdLineBatch = new ArrayList<String>(); cmdLineBatchOpt = new ArrayList<String>(); String cmdTemp = cmdLineGeneral[0] + cmdLineVideo[0] + cmdLineAudio[0] + cmdLineSubtitle[0]; if (!cmdTemp.isEmpty()) { for (int i = 0; i < modelFiles.getSize(); i++) { String cmdLineAll = cmdLineGeneral[i] + cmdLineVideo[i] + cmdLineAudio[i] + cmdLineSubtitle[i]; String cmdLineAllOpt = cmdLineGeneralOpt[i] + cmdLineVideoOpt[i] + cmdLineAudioOpt[i] + cmdLineSubtitleOpt[i]; if (isWindows()) { cmdLineBatch.add("\"" + txtMkvPropExe.getText() + "\" \"" + modelFiles.get(i) + "\"" + cmdLineAll); cmdLineBatchOpt.add("\"" + escapePath((String) modelFiles.get(i)) + "\"" + cmdLineAllOpt); } else { cmdLineBatch.add(escapePath(txtMkvPropExe.getText()) + " " + escapePath((String) modelFiles.get(i)) + cmdLineAll); cmdLineBatchOpt.add("\"" + (String) modelFiles.get(i) + "\"" + cmdLineAllOpt); } } } } private void executeBatch() { worker = new SwingWorker<Void, Void>() { @Override public Void doInBackground() { try { txtOutput.setText(""); tabbedPane.setSelectedIndex(tabbedPane.getTabCount()-1); tabbedPane.setEnabled(false); btnProcessFiles.setEnabled(false); btnGenerateCmdLine.setEnabled(false); for (int i = 0; i < cmdLineBatch.size(); i++) { File optFile = new File("options.txt"); PrintWriter optFilePW = new PrintWriter(new BufferedWriter(new FileWriter(optFile))); String[] optFileContents = Commandline.translateCommandline(cmdLineBatchOpt.get(i)); if (!optFile.exists()) { optFile.createNewFile(); } for (String content:optFileContents) { optFilePW.println(content); } optFilePW.flush(); optFilePW.close(); if (isWindows()) { proc = rt.exec("\"" + txtMkvPropExe.getText() + "\" @options.txt"); } else { proc = rt.exec(escapePath(txtMkvPropExe.getText()) + " @options.txt"); } txtOutput.append("File: " + modelFiles.get(i) + "\n"); txtOutput.append("Command line: " + cmdLineBatch.get(i) + "\n\n"); StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), txtOutput); StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), txtOutput); outputGobbler.start(); errorGobbler.start(); proc.waitFor(); optFile.delete(); if (i < cmdLineBatch.size()-1) txtOutput.append("--------------\n\n"); } } catch (IOException e) { } catch (InterruptedException e) { } return null; } @Override protected void done() { tabbedPane.setEnabled(true); btnProcessFiles.setEnabled(true); btnGenerateCmdLine.setEnabled(true); } }; worker.execute(); } /* End of command line operations */ /* Start of INI configuration file operations */ private void readIniFile() { Ini ini = null; if (iniFile.exists()) { try { ini = new Ini(iniFile); String exePath = ini.get("General", "mkvpropedit"); if (exePath != null) { File exeFile = new File(exePath); if (exeFile.exists()) { if (exeFile.toString().equals("mkvpropedit.exe") && isWindows()) { cbMkvPropExeDef.setSelected(true); cbMkvPropExeDef.setEnabled(false); } else if (exeFile.toString().equals("/usr/bin/mkvpropedit") && !isWindows()) { cbMkvPropExeDef.setSelected(true); cbMkvPropExeDef.setEnabled(false); } else { txtMkvPropExe.setText(exePath); cbMkvPropExeDef.setSelected(false); cbMkvPropExeDef.setEnabled(true); } } else { if (isWindows()) txtMkvPropExe.setText("mvkpropedit.exe"); else txtMkvPropExe.setText("/usr/bin/mkvpropedit"); cbMkvPropExeDef.setSelected(true); cbMkvPropExeDef.setEnabled(false); } } } catch (InvalidFileFormatException e) { } catch (IOException e) { } } else if (isWindows()) { String exePath = getMkvPropExeFromReg(); if (exePath != null) { txtMkvPropExe.setText(exePath); cbMkvPropExeDef.setSelected(false); cbMkvPropExeDef.setEnabled(true); saveIniFile(new File(exePath)); } } } private void saveIniFile(File exeFile) { if (exeFile.exists()) { Ini ini = null; if (!iniFile.exists()) { try { iniFile.createNewFile(); } catch (IOException e1) { } } txtMkvPropExe.setText(exeFile.toString()); cbMkvPropExeDef.setSelected(false); cbMkvPropExeDef.setEnabled(true); try { ini = new Ini(iniFile); ini.put("General", "mkvpropedit", exeFile.toString()); ini.store(); } catch (InvalidFileFormatException e1) { } catch (IOException e1) { } } } private void defaultIniFile() { Ini ini = null; if (!iniFile.exists()) { try { iniFile.createNewFile(); } catch (IOException e1) { } } try { ini = new Ini(iniFile); if (isWindows()) ini.put("General", "mkvpropedit", "mkvpropedit.exe"); else ini.put("General", "mkvpropedit", "/usr/bin/mkvpropedit"); ini.store(); } catch (InvalidFileFormatException e1) { } catch (IOException e1) { } } private String getMkvPropExeFromReg() { String exePath = null; try { exePath = WinRegistry.readString(WinRegistry.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\MKVtoolnix", "UninstallString"); if (exePath == null) exePath = WinRegistry.readString(WinRegistry.HKEY_LOCAL_MACHINE, "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\MKVtoolnix", "UninstallString"); } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } if (exePath != null) { File tmpExe = new File(exePath); tmpExe = new File(tmpExe.getParent()+"\\mkvpropedit.exe"); if (tmpExe.exists()) { exePath = tmpExe.toString(); } } return exePath; } /* End of INI configuration file operations */ /* Start of escaping functions */ private String escapeName (String name) { if (!name.isEmpty()) { name = name.replace("\\","\\\\"); name = name.replace(" ", "\\s"); name = name.replace("\"","\\2"); name = name.replace(":","\\c"); name = name.replace("#","\\h"); } return name; } private String escapeNameCmdLine (String name) { name = name.replace("\"", "\\\""); return name; } private String escapePath (String path) { if (isWindows()) { path = path.replace("\\", "\\\\"); } else { path = path.replace("\\", "\\\\"); path = path.replace(" ", "\\ "); path = path.replace("[", "\\["); path = path.replace("]", "\\]"); path = path.replace("<", "\\<"); path = path.replace(">", "\\>"); path = path.replace("\'", "\\\'"); path = path.replace("\"", "\\\""); path = path.replace("&", "\\&"); path = path.replace("*", "\\*"); path = path.replace("?", "\\?"); path = path.replace("|", "\\|"); path = path.replace(":", "\\:"); path = path.replace(";", "\\;"); } return path; } /* End of escaping functions */ private NumberFormat padNumber(int pad) { NumberFormat formatter = new DecimalFormat("0"); if (pad > 0) { String n = ""; for (int i = 0; i < pad; i++) { n += 0; } formatter = new DecimalFormat(n); } return formatter; } private boolean isWindows() { String OS = System.getProperty("os.name"); if (OS.startsWith("Windows")) return true; else return false; } }
Added two more characters for escaping on *nix; Version bumped to 1.0.3.1.
trunk/src/com/googlecode/jmkvpropedit/JMkvpropedit.java
Added two more characters for escaping on *nix; Version bumped to 1.0.3.1.
<ide><path>runk/src/com/googlecode/jmkvpropedit/JMkvpropedit.java <ide> */ <ide> private void initialize() { <ide> frmJMkvpropedit = new JFrame(); <del> frmJMkvpropedit.setTitle("JMkvpropedit 1.0.3"); /* Version */ <add> frmJMkvpropedit.setTitle("JMkvpropedit 1.0.3.1"); /* Version */ <ide> frmJMkvpropedit.setResizable(false); <ide> frmJMkvpropedit.setBounds(100, 100, 759, 444); <ide> frmJMkvpropedit.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); <ide> path = path.replace(" ", "\\ "); <ide> path = path.replace("[", "\\["); <ide> path = path.replace("]", "\\]"); <add> path = path.replace("{", "\\{"); <add> path = path.replace("}", "\\}"); <ide> path = path.replace("<", "\\<"); <ide> path = path.replace(">", "\\>"); <ide> path = path.replace("\'", "\\\'");
Java
apache-2.0
7fc0af1c0c11904e9434aea247695396e4f9499b
0
alien4cloud/alien4cloud-cloudify3-provider,alien4cloud/alien4cloud-cloudify3-provider,victorkeophila/alien4cloud-cloudify3-provider,alien4cloud/alien4cloud-cloudify3-provider,victorkeophila/alien4cloud-cloudify3-provider,victorkeophila/alien4cloud-cloudify3-provider
package alien4cloud.paas.cloudify3.location; import java.nio.file.Path; import java.util.List; import java.util.Set; import javax.annotation.PostConstruct; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import alien4cloud.model.cloud.IaaSType; import alien4cloud.model.orchestrators.locations.LocationResourceTemplate; import alien4cloud.orchestrators.plugin.ILocationResourceAccessor; import alien4cloud.orchestrators.plugin.model.PluginArchive; import alien4cloud.paas.cloudify3.error.BadConfigurationException; import alien4cloud.plugin.model.ManagedPlugin; import alien4cloud.tosca.ArchiveParser; import alien4cloud.tosca.ArchivePostProcessor; import alien4cloud.tosca.model.ArchiveRoot; import alien4cloud.tosca.parser.ParsingException; import alien4cloud.tosca.parser.ParsingResult; import com.google.common.collect.Lists; import com.google.common.collect.Sets; @Slf4j @Component public class OpenstackLocationConfigurator implements ITypeAwareLocationConfigurator { @Inject private ArchiveParser archiveParser; @Inject private ArchivePostProcessor postProcessor; @Inject private ManagedPlugin selfContext; private List<PluginArchive> archives; @PostConstruct public void postConstruct() { this.archives = Lists.newArrayList(); Path archivePath = this.selfContext.getPluginPath().resolve("provider/openstack/configuration"); // Parse the archives try { ParsingResult<ArchiveRoot> result = this.archiveParser.parseDir(archivePath); postProcessor.postProcess(result); PluginArchive pluginArchive = new PluginArchive(result.getResult(), archivePath); this.archives.add(pluginArchive); } catch (ParsingException e) { log.error("Failed to parse archive, plugin won't work", e); throw new BadConfigurationException("Failed to parse archive, plugin won't work", e); } } @Override public List<PluginArchive> pluginArchives() { return this.archives; } @Override public List<String> getResourcesTypes() { List<String> resourcesTypes = Lists.newArrayList(); for (PluginArchive pluginArchive : this.archives) { resourcesTypes.addAll(pluginArchive.getArchive().getNodeTypes().keySet()); } return resourcesTypes; } @Override public List<LocationResourceTemplate> instances(ILocationResourceAccessor resourceAccessor) { return null; } @Override public Set<String> getManagedLocationTypes() { return Sets.newHashSet(IaaSType.OPENSTACK.toString()); } }
src/main/java/alien4cloud/paas/cloudify3/location/OpenstackLocationConfigurator.java
package alien4cloud.paas.cloudify3.location; import java.nio.file.Path; import java.util.List; import java.util.Set; import javax.annotation.PostConstruct; import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import alien4cloud.model.cloud.IaaSType; import alien4cloud.model.orchestrators.locations.LocationResourceTemplate; import alien4cloud.orchestrators.plugin.ILocationResourceAccessor; import alien4cloud.orchestrators.plugin.model.PluginArchive; import alien4cloud.paas.cloudify3.error.BadConfigurationException; import alien4cloud.plugin.model.ManagedPlugin; import alien4cloud.tosca.ArchiveParser; import alien4cloud.tosca.model.ArchiveRoot; import alien4cloud.tosca.parser.ParsingException; import alien4cloud.tosca.parser.ParsingResult; import com.google.common.collect.Lists; import com.google.common.collect.Sets; @Slf4j @Component public class OpenstackLocationConfigurator implements ITypeAwareLocationConfigurator { @Resource private ArchiveParser archiveParser; @Resource private ManagedPlugin selfContext; private List<PluginArchive> archives; @PostConstruct public void postConstruct() { this.archives = Lists.newArrayList(); Path archivePath = this.selfContext.getPluginPath().resolve("provider/openstack/configuration"); // Parse the archives try { ParsingResult<ArchiveRoot> result = this.archiveParser.parseDir(archivePath); PluginArchive pluginArchive = new PluginArchive(result.getResult(), archivePath); this.archives.add(pluginArchive); } catch (ParsingException e) { log.error("Failed to parse archive, plugin won't work", e); throw new BadConfigurationException("Failed to parse archive, plugin won't work", e); } } @Override public List<PluginArchive> pluginArchives() { return this.archives; } @Override public List<String> getResourcesTypes() { List<String> resourcesTypes = Lists.newArrayList(); for (PluginArchive pluginArchive : this.archives) { resourcesTypes.addAll(pluginArchive.getArchive().getNodeTypes().keySet()); } return resourcesTypes; } @Override public List<LocationResourceTemplate> instances(ILocationResourceAccessor resourceAccessor) { return null; } @Override public Set<String> getManagedLocationTypes() { return Sets.newHashSet(IaaSType.OPENSTACK.toString()); } }
WIP orchestrator location configuration
src/main/java/alien4cloud/paas/cloudify3/location/OpenstackLocationConfigurator.java
WIP orchestrator location configuration
<ide><path>rc/main/java/alien4cloud/paas/cloudify3/location/OpenstackLocationConfigurator.java <ide> import java.util.Set; <ide> <ide> import javax.annotation.PostConstruct; <del>import javax.annotation.Resource; <add>import javax.inject.Inject; <ide> <ide> import lombok.extern.slf4j.Slf4j; <ide> <ide> import alien4cloud.paas.cloudify3.error.BadConfigurationException; <ide> import alien4cloud.plugin.model.ManagedPlugin; <ide> import alien4cloud.tosca.ArchiveParser; <add>import alien4cloud.tosca.ArchivePostProcessor; <ide> import alien4cloud.tosca.model.ArchiveRoot; <ide> import alien4cloud.tosca.parser.ParsingException; <ide> import alien4cloud.tosca.parser.ParsingResult; <ide> @Component <ide> public class OpenstackLocationConfigurator implements ITypeAwareLocationConfigurator { <ide> <del> @Resource <add> @Inject <ide> private ArchiveParser archiveParser; <del> <del> @Resource <add> @Inject <add> private ArchivePostProcessor postProcessor; <add> @Inject <ide> private ManagedPlugin selfContext; <ide> <ide> private List<PluginArchive> archives; <ide> // Parse the archives <ide> try { <ide> ParsingResult<ArchiveRoot> result = this.archiveParser.parseDir(archivePath); <add> postProcessor.postProcess(result); <ide> PluginArchive pluginArchive = new PluginArchive(result.getResult(), archivePath); <ide> this.archives.add(pluginArchive); <ide> } catch (ParsingException e) {
Java
apache-2.0
4fd72ab6166388471e2a75c01e8e70aadee3197f
0
fnl/txtfnnl,fnl/txtfnnl,fnl/txtfnnl,fnl/txtfnnl
package txtfnnl.pipelines; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.uima.UIMAException; import org.apache.uima.resource.ExternalResourceDescription; import org.apache.uima.resource.ResourceInitializationException; import txtfnnl.uima.analysis_component.BioLemmatizerAnnotator; import txtfnnl.uima.analysis_component.GazetteerAnnotator; import txtfnnl.uima.analysis_component.GeniaTaggerAnnotator; import txtfnnl.uima.analysis_component.NOOPAnnotator; import txtfnnl.uima.analysis_component.RelationshipFilter; import txtfnnl.uima.analysis_component.SentenceFilter; import txtfnnl.uima.analysis_component.SyntaxPatternAnnotator; import txtfnnl.uima.analysis_component.opennlp.SentenceAnnotator; import txtfnnl.uima.analysis_component.opennlp.TokenAnnotator; import txtfnnl.uima.collection.RelationshipWriter; import txtfnnl.uima.resource.JdbcGazetteerResource; import txtfnnl.uima.resource.LineBasedStringArrayResource; /** * A pattern-based relationship extractor between normalized entities. * <p> * Input files can be read from a directory or listed explicitly, while output lines are written to * some directory or to STDOUT. Relationships are written on a single line. A relationship consists * of the document URL, the relationship type, the actor entity ID, the target entity ID, and the * sentence evidence where the relationship was found, all separated by tabs. * <p> * The default setup assumes gene and/or protein entities found in a <a * href="https://github.com/fnl/gnamed">gnamed</a> database. * * @author Florian Leitner */ public class RelationshipExtractor extends Pipeline { static final String DEFAULT_DATABASE = "gnamed"; static final String DEFAULT_JDBC_DRIVER = "org.postgresql.Driver"; static final String DEFAULT_DB_PROVIDER = "postgresql"; // default entity set: all human, mouse, and rat gene symbols (roughly 500k symbols) static final String DEFAULT_SQL_QUERY = "SELECT r.accession, s.value FROM " + "genes AS g, gene_strings AS s, gene_refs AS r WHERE g.id = s.id AND g.id = r.id " + "AND g.species_id IN (9606, 10090, 10116) AND s.cat = 'symbol' AND r.namespace = 'gi'"; // TODO: make this next thing a parameter (SQL query files?) static final String MAMMALIAN_TF_IDS = "('10002', '100072', '100073351', '10009', '100128927', '100129885', '100131390', '100132074', '100182', '100187701', '100271849', '100361818', '100361836', '10062', '100978', '101023', '10113', '10127', '10153', '10172', '10194', '10215', '102423', '102442', '10260', '10265', '10308', '10320', '10357', '10363', '10365', '10379', '103836', '103889', '104156', '104338', '104360', '104382', '104394', '1044', '1045', '1046', '10472', '10481', '10485', '10488', '1050', '1051', '1052', '10522', '1053', '10538', '1054', '10553', '10608', '106143', '10620', '106389', '10655', '10660', '10661', '10664', '10691', '10716', '10725', '10732', '10736', '10743', '107503', '107586', '107587', '107751', '10782', '10795', '10865', '108655', '108961', '109032', '109575', '109663', '109889', '109910', '109947', '109948', '11016', '110521', '110593', '11063', '110648', '110685', '110784', '110794', '110796', '110805', '11083', '11107', '11108', '1112', '11166', '112400', '112770', '11278', '11279', '11281', '112939', '11317', '113931', '113983', '113984', '114090', '114109', '114142', '114208', '114213', '114485', '114498', '114499', '114500', '114501', '114502', '114503', '114505', '114519', '114565', '114604', '114634', '114712', '114845', '11545', '11568', '11569', '115768', '116039', '116113', '11614', '11622', '11634', '116448', '116490', '116543', '116544', '116545', '116557', '116639', '116648', '116651', '116668', '116674', '116810', '11694', '11695', '117034', '117058', '117062', '117095', '117107', '117140', '117154', '117232', '117282', '117560', '11792', '11819', '11835', '118445', '11859', '11863', '11864', '11865', '11878', '11906', '11908', '11909', '11910', '11911', '11921', '11922', '11923', '11924', '11925', '12013', '12014', '12020', '12022', '12023', '120237', '12029', '12053', '121340', '12142', '121536', '121551', '121599', '121643', '12173', '12224', '122953', '12355', '12393', '12394', '12399', '124411', '12590', '12591', '12592', '12606', '12607', '12608', '12609', '12611', '12677', '127343', '12753', '12785', '128209', '128408', '128553', '12912', '12913', '12915', '12916', '12951', '13017', '13018', '13047', '13048', '130497', '130557', '1316', '13170', '13172', '13198', '132625', '13390', '13392', '13393', '13394', '13395', '13396', '134187', '13496', '13555', '13557', '13559', '13560', '13591', '13592', '13593', '135935', '136259', '13626', '13653', '13654', '13655', '13656', '13661', '13709', '13710', '13711', '13712', '13713', '13714', '137814', '13796', '13797', '13798', '13799', '13806', '13813', '13819', '1385', '1386', '13864', '13865', '138715', '13875', '13876', '1388', '1389', '1390', '139628', '13982', '13983', '13984', '14008', '14009', '14011', '14013', '14025', '14030', '140477', '140489', '140586', '140587', '140588', '140589', '1406', '140628', '140690', '14106', '142', '14233', '14234', '14235', '14236', '14237', '14238', '14239', '14240', '14241', '14247', '14281', '14282', '14283', '14284', '14390', '144455', '14460', '14461', '14462', '14463', '14464', '14465', '14472', '145258', '14531', '14536', '14581', '14582', '145873', '14632', '14633', '14634', '147912', '14815', '148198', '1482', '148327', '14836', '14842', '14843', '1488', '148979', '14912', '15110', '15111', '15191', '15205', '15206', '15207', '15208', '15209', '15214', '15218', '15220', '15221', '15223', '15227', '15228', '15229', '1523', '15242', '15248', '15251', '152518', '15273', '15284', '153222', '153572', '15361', '15364', '15370', '15371', '15373', '15375', '15376', '15377', '15378', '15379', '15384', '15387', '15394', '15395', '15396', '15398', '15399', '15400', '15401', '15402', '15403', '15404', '15405', '15407', '15408', '15410', '15412', '15413', '15414', '15415', '15416', '15417', '15422', '15423', '15424', '15425', '15426', '15429', '15430', '15431', '15433', '15434', '15436', '15437', '15438', '15460', '15499', '15500', '155061', '155430', '156726', '157848', '15900', '159296', '15936', '15951', '161452', '162239', '1628', '163059', '16362', '16363', '16364', '16371', '16372', '16373', '16391', '16392', '16468', '16476', '16477', '16478', '1649', '165', '16549', '16596', '16597', '16598', '16599', '16600', '16601', '16656', '16658', '167826', '16814', '168374', '16842', '168544', '168620', '16869', '16870', '16871', '16872', '16874', '16876', '16909', '16917', '16918', '16969', '16978', '169792', '170302', '170574', '170671', '170729', '170820', '170825', '170909', '170959', '171017', '171018', '171068', '171078', '171137', '17119', '17121', '17122', '17125', '17126', '17127', '17128', '17129', '171299', '17130', '171302', '17132', '17133', '17134', '17135', '171355', '171356', '171360', '171454', '17172', '17173', '17187', '17188', '17258', '17259', '17260', '17261', '17268', '17285', '17286', '17292', '17293', '17300', '17301', '17341', '17342', '17425', '17428', '1745', '1746', '1747', '1748', '1749', '1750', '17536', '1761', '17681', '17701', '17702', '17764', '17765', '17859', '17863', '17864', '17865', '17869', '17876', '17877', '17878', '17927', '17928', '17932', '17933', '18012', '18013', '18014', '18018', '18019', '18021', '18022', '18023', '18024', '18025', '18027', '18028', '18029', '18030', '18032', '18033', '18034', '18044', '18046', '18071', '18072', '18088', '18089', '18091', '18092', '18094', '18095', '18096', '18109', '18124', '18142', '18143', '18171', '18181', '18185', '1820', '18227', '18291', '18420', '18423', '18424', '18426', '18503', '18504', '18505', '18506', '18507', '18508', '18509', '18510', '18511', '18514', '18515', '18516', '18609', '18612', '18616', '18617', '18667', '1869', '1870', '1871', '18736', '1874', '18740', '18741', '18742', '1875', '1876', '1877', '18771', '1879', '18933', '18935', '18986', '18987', '18988', '18991', '18992', '18993', '18994', '18996', '18997', '18998', '18999', '190', '19009', '19013', '19015', '19016', '19127', '19130', '192109', '192110', '19213', '192274', '19290', '19291', '19377', '19401', '19411', '19434', '194655', '195333', '195733', '1958', '195828', '1959', '196', '1960', '1961', '19664', '19668', '19696', '19697', '19698', '19712', '19724', '19725', '19726', '19821', '19883', '19885', '1997', '1998', '1999', '2000', '2001', '2002', '200350', '2004', '2005', '201516', '2016', '2018', '20181', '20182', '20183', '20186', '2019', '2020', '20204', '2023', '20230', '20231', '20289', '2034', '20371', '20375', '20429', '20464', '20465', '20471', '20472', '20473', '20474', '20475', '20476', '20482', '20583', '20585', '20613', '2063', '20658', '20664', '20665', '20666', '20667', '20668', '20669', '20670', '20671', '20672', '20674', '20675', '20677', '20678', '20679', '20680', '20681', '20682', '20683', '20687', '20688', '20689', '20728', '2077', '207785', '2078', '20787', '20788', '20807', '208076', '208104', '20841', '20846', '20847', '20848', '20849', '20850', '20851', '20852', '208647', '208677', '20893', '209446', '209448', '209707', '2099', '20997', '2100', '2101', '2103', '2104', '210719', '2113', '211323', '2114', '2115', '211586', '2116', '2117', '2118', '2119', '2120', '2122', '212712', '2130', '21349', '21375', '21380', '21384', '21385', '21386', '21387', '21388', '21389', '21405', '21406', '21407', '21408', '21410', '214105', '21411', '21412', '21413', '21414', '21415', '21416', '214162', '21417', '21418', '21419', '21420', '21422', '21423', '21425', '21426', '21428', '21454', '214855', '215418', '216285', '21674', '21676', '21677', '21679', '21685', '217082', '217166', '21769', '21780', '21781', '218030', '21804', '21807', '218100', '21815', '21833', '21834', '21847', '21869', '218772', '21907', '21908', '21909', '219150', '219409', '220202', '22025', '22026', '22059', '22062', '22157', '22160', '22165', '221833', '221937', '22221', '222546', '22259', '22260', '22278', '22282', '222894', '223227', '22337', '22344', '223669', '223843', '223922', '22431', '22433', '224656', '225497', '225631', '225872', '225998', '226049', '226075', '22608', '22632', '22634', '22640', '22642', '226442', '22661', '226641', '22666', '22671', '22685', '226896', '22694', '22696', '22697', '22701', '22702', '22712', '22724', '22751', '22754', '22755', '22757', '22758', '227631', '22764', '22767', '22771', '22772', '22773', '22774', '22778', '22779', '22780', '22797', '22806', '22807', '22809', '22823', '22834', '228598', '228662', '22877', '22882', '228829', '22887', '228880', '22890', '228911', '228913', '2290', '229004', '229007', '22903', '229055', '22926', '2294', '22947', '2295', '2296', '2297', '2298', '2299', '2300', '230025', '2301', '230119', '230162', '2302', '2303', '23036', '2304', '23040', '2305', '23051', '230587', '2306', '2307', '230700', '2308', '230824', '2309', '23090', '231044', '23119', '2313', '23152', '231991', '232430', '23261', '23269', '232791', '232879', '232906', '232934', '233060', '23314', '23316', '233410', '234219', '23440', '23493', '23512', '23528', '2353', '235320', '2354', '2355', '23613', '23660', '237336', '23764', '237911', '238455', '23849', '23856', '23857', '238673', '23871', '23872', '239099', '239546', '23958', '23967', '240690', '241066', '24113', '24136', '241514', '24208', '24209', '242509', '24252', '24253', '242705', '24309', '24330', '24333', '24356', '24370', '243833', '24388', '243931', '243937', '24413', '244219', '24452', '24453', '24457', '244579', '24459', '24460', '244713', '244813', '24508', '24516', '24517', '24518', '24522', '245368', '245572', '245583', '245595', '24566', '245671', '24577', '245980', '246073', '246086', '246149', '246264', '246271', '246282', '246301', '24631', '246334', '246361', '246760', '24705', '24706', '24790', '24817', '24831', '24842', '24873', '24883', '24890', '24916', '24918', '24919', '2494', '25094', '25098', '25099', '25100', '25124', '25125', '25126', '25129', '25148', '25149', '25154', '25157', '25159', '2516', '25162', '25172', '25221', '25231', '25242', '25243', '25271', '252856', '252880', '252885', '252886', '252915', '252917', '252924', '252973', '25301', '25334', '25337', '253738', '25389', '25401', '25410', '254251', '25431', '25445', '25446', '25483', '25492', '25509', '2551', '25517', '25546', '25554', '255877', '25591', '25607', '25620', '25628', '256297', '25631', '256380', '25640', '25646', '25664', '25671', '25672', '25682', '25690', '25695', '257', '25701', '25705', '25714', '25720', '25735', '25747', '257634', '25803', '25806', '25833', '259241', '25988', '260298', '260325', '26137', '26205', '2623', '2624', '2625', '26257', '2626', '2627', '26296', '26298', '2636', '2637', '26379', '26380', '26381', '26386', '26423', '26424', '26427', '26468', '2649', '26508', '26584', '266680', '266716', '266734', '266738', '266743', '266787', '266792', '266813', '2672', '268297', '268417', '268469', '268564', '26910', '26927', '269389', '269401', '26959', '269800', '270004', '27022', '27023', '27049', '27056', '27080', '27086', '27164', '27217', '272322', '272382', '27287', '27319', '27324', '2735', '2736', '2737', '27386', '277353', '282825', '282840', '283078', '283150', '284695', '286101', '286380', '287074', '287076', '287185', '287361', '287423', '287441', '287469', '287521', '287615', '287638', '287647', '287940', '288105', '288151', '288152', '288153', '288154', '288353', '288457', '288665', '288736', '288774', '288821', '288906', '289026', '289048', '289201', '289230', '289311', '289595', '289752', '289754', '28999', '290221', '290317', '290749', '290765', '2908', '2909', '291100', '291105', '291228', '29148', '291908', '291960', '29203', '292060', '29227', '29228', '292301', '292404', '292721', '29279', '2928', '292820', '292892', '292934', '292935', '29300', '293012', '293017', '293038', '293046', '293104', '293165', '293405', '293537', '293568', '29357', '29361', '29362', '293624', '293701', '29394', '293992', '29410', '294322', '294328', '294395', '294515', '29452', '294562', '29458', '294640', '29467', '294924', '29508', '295248', '295297', '295315', '295327', '29535', '295475', '295568', '29560', '29567', '295695', '29577', '29588', '29589', '295965', '29609', '296201', '296272', '296281', '296320', '296344', '296374', '296399', '296420', '296478', '296499', '296500', '296510', '296511', '29657', '296706', '296953', '29721', '297480', '297705', '297769', '297783', '297804', '29808', '298084', '298189', '298316', '298400', '29841', '29842', '298449', '298506', '298555', '29861', '298732', '298878', '298894', '299016', '299061', '299138', '299186', '299206', '299210', '299499', '299766', '299897', '299979', '300054', '30009', '300095', '300260', '30046', '30051', '30062', '300807', '300947', '300954', '301038', '301121', '301284', '301285', '301476', '301570', '302327', '302333', '302369', '302400', '302415', '302582', '302583', '302811', '302946', '302962', '302993', '303164', '303188', '303226', '303310', '303398', '303399', '303469', '303480', '303488', '303489', '303491', '303496', '303499', '303511', '303698', '303753', '303828', '303836', '303970', '303991', '304005', '304054', '304056', '304063', '304071', '304092', '304103', '304127', '304275', '304298', '304342', '304479', '304514', '304666', '304729', '304741', '304786', '304815', '304850', '304935', '304947', '304962', '305066', '305083', '305311', '305471', '305494', '305501', '305584', '305589', '305719', '305848', '305854', '305858', '305896', '305897', '305968', '305972', '305999', '306110', '306168', '306330', '306400', '306657', '306659', '306695', '3068', '306862', '306873', '306977', '307217', '307498', '307547', '307715', '307721', '307740', '307794', '307806', '307820', '307829', '307834', '307839', '307919', '30812', '308126', '30818', '308311', '30832', '308336', '30834', '308363', '308366', '308387', '3084', '308406', '308411', '308435', '308482', '308523', '308582', '308607', '3087', '308766', '308900', '3090', '309002', '309031', '309095', '3091', '309164', '309165', '30923', '30927', '30928', '309288', '309389', '30942', '309430', '30944', '309452', '309457', '3096', '3097', '309728', '309859', '309871', '309888', '309900', '309957', '310375', '310616', '310659', '310660', '311071', '311093', '311311', '311414', '311462', '311505', '311508', '311547', '311575', '311604', '311615', '311658', '311721', '311723', '311742', '311764', '311832', '311876', '311901', '312195', '312203', '312303', '312331', '312451', '312777', '312897', '312936', '3131', '313166', '313219', '313504', '313507', '313512', '313554', '313557', '313558', '313575', '313666', '313678', '313913', '313978', '313993', '313994', '3142', '314221', '314246', '314322', '314374', '314423', '314436', '314539', '314586', '314616', '314638', '314675', '314711', '314818', '314988', '315039', '315081', '315101', '315305', '315308', '315309', '315333', '315337', '315338', '315341', '315497', '315532', '315601', '315606', '315689', '315804', '315870', '315882', '3159', '316052', '316102', '316164', '316214', '316327', '316351', '3164', '3166', '316626', '316742', '3169', '3170', '3171', '3172', '317268', '317376', '317382', '3174', '3175', '317715', '3182', '3190', '3195', '3196', '319758', '3198', '3199', '3200', '3201', '320145', '3202', '320267', '3203', '3204', '3205', '320522', '3206', '3207', '320799', '3209', '320995', '3211', '3212', '3213', '3214', '3215', '3216', '3217', '3218', '3219', '3221', '3222', '3223', '3224', '3226', '3227', '3229', '3231', '3232', '3233', '3234', '3235', '3236', '3237', '3239', '326', '328', '3280', '3297', '3298', '3299', '329934', '332221', '332937', '333929', '3344', '337868', '338917', '339344', '3394', '339488', '339559', '340069', '340385', '340784', '3428', '342909', '3431', '343472', '344018', '346389', '347853', '3516', '353088', '353187', '353227', '353305', '360204', '360389', '360482', '360551', '360588', '360610', '360631', '360635', '3607', '360737', '360775', '360858', '360896', '360905', '360960', '360961', '361060', '361095', '361096', '361131', '361400', '361508', '361544', '361576', '361627', '361630', '361668', '361746', '361784', '361801', '361809', '361816', '361944', '361946', '362085', '362106', '362125', '362165', '362176', '362268', '362280', '362286', '362291', '362339', '362391', '362453', '362464', '362530', '362591', '362665', '362675', '362686', '362733', '362741', '362871', '362896', '362925', '362948', '363165', '363185', '363243', '363595', '363632', '363656', '363667', '363672', '363684', '363735', '363831', '364069', '364081', '364140', '364152', '3642', '364418', '364510', '364680', '364706', '364712', '364855', '364883', '364910', '3651', '365299', '365371', '365564', '365744', '365748', '3659', '365900', '3660', '366078', '3661', '366126', '366142', '3662', '366210', '366214', '366229', '3663', '366340', '3664', '3665', '366542', '366598', '366829', '366949', '366951', '366954', '366960', '366964', '366996', '366998', '367', '3670', '367092', '367100', '367106', '367152', '367218', '367264', '367314', '367832', '367846', '367944', '367950', '368057', '368158', '3720', '3725', '3726', '3727', '378435', '380912', '380993', '381319', '381359', '381373', '381463', '381549', '381990', '382066', '382074', '382639', '383491', '385674', '387609', '388112', '388566', '388585', '389058', '389549', '389692', '390010', '390259', '390874', '390992', '391723', '3975', '399489', '399823', '4005', '4009', '401', '4010', '402381', '404281', '405', '406', '406164', '406169', '4084', '4086', '4087', '4088', '4089', '4090', '4091', '4094', '4097', '414065', '4149', '4150', '4205', '4207', '4208', '4209', '4211', '4212', '4222', '4223', '4286', '429', '4297', '430', '4303', '4306', '432731', '4330', '4335', '433938', '434174', '436240', '440097', '442425', '4487', '4488', '4520', '4601', '4602', '4603', '4605', '4609', '4610', '4613', '4617', '4618', '463', '4654', '4656', '466', '4661', '467', '468', '474', '4760', '4761', '4762', '4772', '4773', '4774', '4775', '4776', '4778', '4779', '4780', '4781', '4782', '4783', '4784', '4790', '4791', '4799', '4800', '4802', '4807', '4808', '4821', '4824', '4825', '4849', '4861', '4862', '4899', '4901', '4904', '4929', '494344', '497984', '497985', '497986', '497987', '497988', '498194', '498407', '49854', '498545', '498575', '498607', '498633', '498864', '498918', '498945', '498952', '4990', '499016', '499090', '499146', '499171', '499361', '499362', '499380', '499497', '499510', '499593', '499874', '499900', '499951', '499952', '499964', '500023', '500037', '500048', '500110', '500126', '500129', '500131', '500137', '500156', '500235', '500239', '500538', '500558', '500574', '500818', '500950', '500964', '500981', '500982', '501099', '501145', '5013', '5015', '501506', '5017', '502759', '502886', '502946', '50496', '50524', '50545', '50552', '50554', '50659', '50662', '50674', '5075', '5076', '5077', '5078', '5079', '50794', '50796', '5080', '50804', '5081', '5083', '50862', '5087', '5089', '5090', '50907', '50913', '50914', '50943', '50945', '51043', '51085', '51157', '51176', '51193', '51222', '51230', '51270', '51274', '51341', '51351', '51385', '51450', '51513', '51533', '51621', '5178', '51804', '51886', '5241', '52615', '52679', '52712', '5307', '5308', '5309', '5316', '5324', '5325', '5326', '53314', '53335', '53404', '53415', '53417', '53626', '5396', '53970', '54006', '54123', '54131', '54139', '541457', '54254', '54264', '54267', '54276', '54278', '54284', '54345', '54352', '54367', '54422', '54446', '5449', '5451', '5452', '5453', '5454', '545474', '5455', '5456', '5457', '5458', '54585', '5459', '5460', '54601', '54626', '5463', '5465', '5467', '5468', '54711', '54713', '54738', '54796', '54897', '54937', '550619', '55079', '55274', '55502', '55509', '55553', '55565', '55578', '55634', '55657', '55806', '55810', '55840', '55893', '55897', '55900', '55922', '55927', '56033', '56198', '56218', '56259', '5626', '5629', '56380', '56449', '56458', '56461', '56484', '56490', '56501', '56676', '56711', '56722', '56734', '56751', '56787', '56790', '56805', '56809', '56938', '56956', '56980', '56987', '56995', '57057', '571', '57167', '57215', '57233', '57246', '57343', '57432', '57473', '57592', '57593', '57594', '57615', '57616', '57621', '57623', '57659', '57693', '57765', '57801', '57822', '579', '5813', '5814', '58158', '58180', '58198', '58208', '58495', '58500', '58805', '58820', '58842', '58850', '58851', '58852', '58853', '58921', '58954', '59016', '59057', '59058', '59112', '5914', '5915', '5916', '59269', '59328', '59335', '59336', '59348', '5966', '5970', '5971', '5978', '5989', '5990', '5991', '5992', '5993', '60329', '60349', '60351', '60394', '604', '60446', '60447', '6045', '60462', '60468', '60529', '60563', '60611', '60661', '60685', '6095', '6096', '6097', '619575', '619665', '6239', '6256', '6257', '6258', '6297', '6299', '6304', '630579', '63876', '639', '63973', '63974', '63976', '63977', '63978', '64067', '641339', '64186', '64188', '64288', '64290', '64321', '64332', '64344', '64345', '643609', '64376', '64379', '64406', '64412', '644168', '64441', '64444', '64530', '64572', '646', '64618', '64619', '64628', '64637', '64641', '64651', '6473', '6474', '64764', '64826', '64843', '64864', '64919', '6492', '6493', '6495', '6496', '6498', '65035', '65050', '65100', '65161', '65193', '65199', '653404', '653427', '654496', '6591', '6596', '65986', '66019', '66136', '6615', '66277', '664783', '664799', '6651', '6656', '6657', '6658', '6659', '6660', '6662', '6663', '6664', '66642', '6665', '6666', '6667', '6668', '6670', '6671', '668', '66830', '66867', '6688', '6689', '66953', '67143', '67150', '6720', '6721', '6722', '67255', '6736', '6772', '6773', '6774', '6775', '6776', '6777', '67778', '6778', '679028', '679571', '679701', '679712', '679869', '680117', '680201', '680427', '680620', '680712', '680751', '681092', '681359', '683504', '684085', '685072', '685102', '685360', '685732', '686117', '6862', '687', '68750', '688', '68837', '68842', '6886', '688699', '688822', '688999', '689030', '68910', '689210', '689695', '689788', '6899', '689918', '68992', '689988', '690430', '690820', '6909', '6910', '6911', '6913', '691398', '691556', '691842', '69228', '6925', '69257', '6926', '6927', '6928', '6929', '6932', '6934', '6935', '6936', '6938', '6939', '6940', '6942', '6943', '6945', '69743', '69890', '7003', '7004', '7008', '70127', '7019', '7020', '7021', '7022', '7023', '7024', '7025', '7026', '7027', '7029', '7030', '7041', '7050', '70508', '7067', '70673', '7068', '7071', '70779', '7080', '70998', '7101', '71041', '71137', '71371', '71375', '7157', '71591', '7161', '71702', '71722', '7181', '7182', '71838', '71950', '72057', '72154', '7227', '72465', '72567', '72739', '727857', '727940', '72843', '7287', '7288', '728957', '7291', '7294', '73181', '73191', '73389', '7342', '7376', '7391', '7392', '74007', '74120', '74123', '74164', '7421', '74352', '74434', '74451', '745', '74533', '74561', '7490', '7494', '7528', '7539', '7541', '7543', '7544', '7545', '7546', '7547', '75507', '7552', '7553', '7554', '7555', '7556', '75580', '7566', '7567', '7570', '7571', '7572', '75753', '7584', '7587', '75871', '7589', '7592', '7593', '7594', '7596', '7629', '7634', '76365', '7637', '7639', '7643', '7644', '7678', '7690', '7691', '7692', '7693', '7694', '7695', '7697', '7699', '7702', '7704', '7707', '7709', '7710', '7711', '7712', '7716', '7718', '7727', '7728', '77286', '7730', '7732', '7741', '7743', '7746', '7753', '7755', '7761', '7762', '7764', '7767', '7773', '77771', '7799', '78266', '78284', '7849', '78912', '78968', '78972', '78974', '790969', '79116', '79190', '79191', '79192', '79225', '79237', '79240', '79241', '79245', '79255', '79362', '79365', '79401', '7942', '79431', '79618', '79692', '79733', '7975', '79759', '79800', '79923', '79977', '80034', '8013', '8022', '80317', '80320', '80338', '8061', '80709', '80712', '80714', '80720', '80778', '80859', '80902', '8091', '8092', '8110', '81518', '81524', '81566', '81646', '81647', '81703', '81710', '81717', '81736', '81808', '81812', '81813', '81817', '81819', '8187', '81879', '8193', '81931', '8320', '8328', '83383', '83395', '83396', '83439', '83463', '83474', '83482', '83498', '83574', '83586', '83595', '83618', '83619', '83630', '83632', '83635', '83726', '83741', '83807', '83826', '83855', '83879', '83881', '83925', '83990', '83993', '84017', '8403', '84046', '84107', '84108', '84159', '84295', '84382', '84385', '84410', '84449', '84482', '84504', '84524', '84528', '8456', '84574', '84619', '8462', '8463', '84653', '84654', '84662', '84667', '84699', '84838', '84839', '84878', '84891', '84911', '84969', '8521', '8531', '8538', '85416', '85424', '85434', '8545', '85471', '85489', '85497', '85508', '8553', '8570', '860', '8609', '861', '8626', '864', '8726', '8820', '8848', '8856', '8880', '8928', '8929', '8939', '89884', '90316', '90333', '9095', '9096', '90987', '90993', '91752', '9189', '91975', '9208', '9242', '9314', '9355', '93691', '93730', '93837', '93986', '94187', '94188', '9421', '94222', '94234', '9464', '9480', '9489', '9496', '9516', '9519', '9572', '9575', '9580', '9586', '9592', '9603', '9640', '9705', '9745', '9753', '9774', '9839', '988', '9915', '9925', '9935', '99377', '9970', '9971', '9975', '9988', '12151', '12400', '15901', '15902', '15903', '161882', '17131', '19017', '23414', '4092', '672', '9612')"; static final String MAMMALIAN_TF_QUERY = "SELECT r.accession, s.value FROM " + "genes AS g, gene_strings AS s, gene_refs AS r WHERE g.id = s.id AND g.id = r.id " + "AND s.cat = 'symbol' AND r.namespace = 'gi' AND r.accession IN " + MAMMALIAN_TF_IDS; private RelationshipExtractor() { throw new AssertionError("n/a"); } public static ExternalResourceDescription getGazetteerResource(CommandLine cmd, Logger l, String querySql, boolean idMatching, boolean exactCaseMatching, String defaultDriverClass, String defaultProvider, String defaultDbName) throws ResourceInitializationException, ClassNotFoundException { // driver class name final String driverClass = cmd.getOptionValue('D', defaultDriverClass); Class.forName(driverClass); // db url final String dbHost = cmd.getOptionValue('H', "localhost"); final String dbProvider = cmd.getOptionValue('P', defaultProvider); final String dbName = cmd.getOptionValue('d', defaultDbName); final String dbUrl = String.format("jdbc:%s://%s/%s", dbProvider, dbHost, dbName); l.log(Level.INFO, "JDBC URL: {0}", dbUrl); // create builder JdbcGazetteerResource.Builder b = JdbcGazetteerResource .configure(dbUrl, driverClass, querySql).idMatching() .setSeparators(JdbcGazetteerResource.SEPARATORS + "\\:\\,\\.\\/\\\\\\[\\]\\{\\}\\(\\)"); // set username/password options if (cmd.hasOption('u')) b.setUsername(cmd.getOptionValue('u')); if (cmd.hasOption('p')) b.setPassword(cmd.getOptionValue('p')); return b.create(); } public static void main(String[] arguments) { final CommandLineParser parser = new PosixParser(); final Options opts = new Options(); CommandLine cmd = null; Pipeline.addLogHelpAndInputOptions(opts); Pipeline.addTikaOptions(opts); Pipeline.addJdbcResourceOptions(opts, DEFAULT_JDBC_DRIVER, DEFAULT_DB_PROVIDER, DEFAULT_DATABASE); Pipeline.addOutputOptions(opts); // sentence splitter options opts.addOption("S", "successive-newlines", false, "split sentences on successive newlines"); opts.addOption("s", "single-newlines", false, "split sentences on single newlines"); // sentence filter options opts.addOption("f", "filter-sentences", true, "retain sentences using a file of regex matches"); opts.addOption("F", "filter-remove", false, "filter removes sentences with matches"); // tokenizer options setup opts.addOption("G", "genia", true, "use GENIA (with the dir containing 'morphdic/') instead of OpenNLP"); // semantic patterns - REQUIRED! opts.addOption("p", "patterns", true, "match sentences with semantic patterns"); // actor and target ID, name pairs opts.addOption("a", "actor-sql", true, "SQL query that produces actor ID, name pairs"); opts.addOption("t", "target-sql", true, "SQL query that produces target ID, name pairs"); try { cmd = parser.parse(opts, arguments); } catch (final ParseException e) { System.err.println(e.getLocalizedMessage()); System.exit(1); // == EXIT == } final Logger l = Pipeline.loggingSetup(cmd, opts, "txtfnnl rex [options] -p <patterns> <directory|files...>\n"); // sentence splitter String splitSentences = null; // S, s if (cmd.hasOption('s')) { splitSentences = "single"; } else if (cmd.hasOption('S')) { splitSentences = "successive"; } // sentence filter final File sentenceFilterPatterns = cmd.hasOption('f') ? new File(cmd.getOptionValue('f')) : null; final boolean removingSentenceFilter = cmd.hasOption('F'); // (GENIA) tokenizer final String geniaDir = cmd.getOptionValue('G'); // semantic patterns File patterns = null; try { patterns = new File(cmd.getOptionValue('p')); } catch (NullPointerException e) { l.severe("no patterns file"); System.err.println("patterns file missing"); System.exit(1); // == EXIT == } // entity queries final String actorSQL = cmd.hasOption('a') ? cmd.getOptionValue('a') : MAMMALIAN_TF_QUERY; final String targetSQL = cmd.hasOption('t') ? cmd.getOptionValue('t') : DEFAULT_SQL_QUERY; // DB resource ExternalResourceDescription actorGazetteer = null; ExternalResourceDescription targetGazetteer = null; try { actorGazetteer = getGazetteerResource(cmd, l, actorSQL, true, false, DEFAULT_JDBC_DRIVER, DEFAULT_DB_PROVIDER, DEFAULT_DATABASE); targetGazetteer = getGazetteerResource(cmd, l, targetSQL, true, false, DEFAULT_JDBC_DRIVER, DEFAULT_DB_PROVIDER, DEFAULT_DATABASE); } catch (final ResourceInitializationException e) { System.err.println("JDBC resoruce setup failed:"); System.err.println(e.toString()); System.exit(1); // == EXIT == } catch (final ClassNotFoundException e) { System.err.println("JDBC driver class unknown:"); System.err.println(e.toString()); System.exit(1); // == EXIT == } // output (format) final String encoding = Pipeline.outputEncoding(cmd); final File outputDirectory = Pipeline.outputDirectory(cmd); final boolean overwriteFiles = Pipeline.outputOverwriteFiles(cmd); try { ExternalResourceDescription patternResource = LineBasedStringArrayResource.configure( "file:" + patterns.getCanonicalPath()).create(); // 0:tika, 1:splitter, 2:filter, 3:tokenizer, 4:lemmatizer, 5:patternMatcher, // 6:actor gazetteer, 7:target gazetteer, 8:filter regulator 9: filter target final Pipeline rex = new Pipeline(10); rex.setReader(cmd); rex.configureTika(cmd); rex.set(1, SentenceAnnotator.configure(splitSentences)); if (sentenceFilterPatterns == null) rex.set(2, NOOPAnnotator.configure()); else rex.set(2, SentenceFilter.configure(sentenceFilterPatterns, removingSentenceFilter)); if (geniaDir == null) { rex.set(3, TokenAnnotator.configure()); rex.set(4, BioLemmatizerAnnotator.configure()); } else { rex.set(3, GeniaTaggerAnnotator.configure(new File(geniaDir))); // the GENIA Tagger already lemmatizes; nothing to do rex.set(4, NOOPAnnotator.configure()); } rex.set(5, SyntaxPatternAnnotator.configure(patternResource).removeUnmatched().create()); rex.set(6, GazetteerAnnotator.configure("UniProt", actorGazetteer).setTextNamespace("actor") .setTextIdentifier("regulator").create()); rex.set(7, GazetteerAnnotator.configure("Entrez", targetGazetteer).setTextNamespace("actor") .setTextIdentifier("target").create()); rex.set(8, RelationshipFilter.configure(SyntaxPatternAnnotator.URI, "event", "tre", SyntaxPatternAnnotator.URI, "actor", "regulator", GazetteerAnnotator.URI, "UniProt", null, false)); rex.set(9, RelationshipFilter.configure(SyntaxPatternAnnotator.URI, "event", "tre", SyntaxPatternAnnotator.URI, "actor", "target", GazetteerAnnotator.URI, "Entrez", null, false)); rex.setConsumer(RelationshipWriter.configure(outputDirectory, encoding, outputDirectory == null, overwriteFiles, true, null, true, true)); rex.run(); } catch (final UIMAException e) { l.severe(e.toString()); System.err.println(e.getLocalizedMessage()); System.exit(1); // == EXIT == } catch (final IOException e) { l.severe(e.toString()); System.err.println(e.getLocalizedMessage()); System.exit(1); // == EXIT == } System.exit(0); } }
txtfnnl-bin/src/main/java/txtfnnl/pipelines/RelationshipExtractor.java
package txtfnnl.pipelines; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.uima.UIMAException; import org.apache.uima.resource.ExternalResourceDescription; import org.apache.uima.resource.ResourceInitializationException; import txtfnnl.uima.analysis_component.BioLemmatizerAnnotator; import txtfnnl.uima.analysis_component.GazetteerAnnotator; import txtfnnl.uima.analysis_component.GeniaTaggerAnnotator; import txtfnnl.uima.analysis_component.NOOPAnnotator; import txtfnnl.uima.analysis_component.RelationshipFilter; import txtfnnl.uima.analysis_component.SentenceFilter; import txtfnnl.uima.analysis_component.SyntaxPatternAnnotator; import txtfnnl.uima.analysis_component.opennlp.SentenceAnnotator; import txtfnnl.uima.analysis_component.opennlp.TokenAnnotator; import txtfnnl.uima.collection.RelationshipWriter; import txtfnnl.uima.resource.JdbcGazetteerResource; import txtfnnl.uima.resource.LineBasedStringArrayResource; /** * A pattern-based relationship extractor between normalized entities. * <p> * Input files can be read from a directory or listed explicitly, while output lines are written to * some directory or to STDOUT. Relationships are written on a single line. A relationship consists * of the document URL, the relationship type, the actor entity ID, the target entity ID, and the * sentence evidence where the relationship was found, all separated by tabs. * <p> * The default setup assumes gene and/or protein entities found in a <a * href="https://github.com/fnl/gnamed">gnamed</a> database. * * @author Florian Leitner */ public class RelationshipExtractor extends Pipeline { static final String DEFAULT_DATABASE = "gnamed"; static final String DEFAULT_JDBC_DRIVER = "org.postgresql.Driver"; static final String DEFAULT_DB_PROVIDER = "postgresql"; // default entity set: all human and mouse gene symbols (roughly 300k symbols) static final String DEFAULT_SQL_QUERY = "SELECT r.accession, s.value FROM " + "genes AS g, gene_strings AS s, gene_refs AS r WHERE g.id = s.id AND g.id = r.id " + "AND g.species_id IN (9606, 10090, 10116) AND s.cat = 'symbol' AND r.namespace = 'gi'"; static final String MAMMALIAN_TF_IDS = "('10002', '100072', '100073351', '10009', '100128927', '100129885', '100131390', '100132074', '100182', '100187701', '100271849', '100361818', '100361836', '10062', '100978', '101023', '10113', '10127', '10153', '10172', '10194', '10215', '102423', '102442', '10260', '10265', '10308', '10320', '10357', '10363', '10365', '10379', '103836', '103889', '104156', '104338', '104360', '104382', '104394', '1044', '1045', '1046', '10472', '10481', '10485', '10488', '1050', '1051', '1052', '10522', '1053', '10538', '1054', '10553', '10608', '106143', '10620', '106389', '10655', '10660', '10661', '10664', '10691', '10716', '10725', '10732', '10736', '10743', '107503', '107586', '107587', '107751', '10782', '10795', '10865', '108655', '108961', '109032', '109575', '109663', '109889', '109910', '109947', '109948', '11016', '110521', '110593', '11063', '110648', '110685', '110784', '110794', '110796', '110805', '11083', '11107', '11108', '1112', '11166', '112400', '112770', '11278', '11279', '11281', '112939', '11317', '113931', '113983', '113984', '114090', '114109', '114142', '114208', '114213', '114485', '114498', '114499', '114500', '114501', '114502', '114503', '114505', '114519', '114565', '114604', '114634', '114712', '114845', '11545', '11568', '11569', '115768', '116039', '116113', '11614', '11622', '11634', '116448', '116490', '116543', '116544', '116545', '116557', '116639', '116648', '116651', '116668', '116674', '116810', '11694', '11695', '117034', '117058', '117062', '117095', '117107', '117140', '117154', '117232', '117282', '117560', '11792', '11819', '11835', '118445', '11859', '11863', '11864', '11865', '11878', '11906', '11908', '11909', '11910', '11911', '11921', '11922', '11923', '11924', '11925', '12013', '12014', '12020', '12022', '12023', '120237', '12029', '12053', '121340', '12142', '121536', '121551', '121599', '121643', '12173', '12224', '122953', '12355', '12393', '12394', '12399', '124411', '12590', '12591', '12592', '12606', '12607', '12608', '12609', '12611', '12677', '127343', '12753', '12785', '128209', '128408', '128553', '12912', '12913', '12915', '12916', '12951', '13017', '13018', '13047', '13048', '130497', '130557', '1316', '13170', '13172', '13198', '132625', '13390', '13392', '13393', '13394', '13395', '13396', '134187', '13496', '13555', '13557', '13559', '13560', '13591', '13592', '13593', '135935', '136259', '13626', '13653', '13654', '13655', '13656', '13661', '13709', '13710', '13711', '13712', '13713', '13714', '137814', '13796', '13797', '13798', '13799', '13806', '13813', '13819', '1385', '1386', '13864', '13865', '138715', '13875', '13876', '1388', '1389', '1390', '139628', '13982', '13983', '13984', '14008', '14009', '14011', '14013', '14025', '14030', '140477', '140489', '140586', '140587', '140588', '140589', '1406', '140628', '140690', '14106', '142', '14233', '14234', '14235', '14236', '14237', '14238', '14239', '14240', '14241', '14247', '14281', '14282', '14283', '14284', '14390', '144455', '14460', '14461', '14462', '14463', '14464', '14465', '14472', '145258', '14531', '14536', '14581', '14582', '145873', '14632', '14633', '14634', '147912', '14815', '148198', '1482', '148327', '14836', '14842', '14843', '1488', '148979', '14912', '15110', '15111', '15191', '15205', '15206', '15207', '15208', '15209', '15214', '15218', '15220', '15221', '15223', '15227', '15228', '15229', '1523', '15242', '15248', '15251', '152518', '15273', '15284', '153222', '153572', '15361', '15364', '15370', '15371', '15373', '15375', '15376', '15377', '15378', '15379', '15384', '15387', '15394', '15395', '15396', '15398', '15399', '15400', '15401', '15402', '15403', '15404', '15405', '15407', '15408', '15410', '15412', '15413', '15414', '15415', '15416', '15417', '15422', '15423', '15424', '15425', '15426', '15429', '15430', '15431', '15433', '15434', '15436', '15437', '15438', '15460', '15499', '15500', '155061', '155430', '156726', '157848', '15900', '159296', '15936', '15951', '161452', '162239', '1628', '163059', '16362', '16363', '16364', '16371', '16372', '16373', '16391', '16392', '16468', '16476', '16477', '16478', '1649', '165', '16549', '16596', '16597', '16598', '16599', '16600', '16601', '16656', '16658', '167826', '16814', '168374', '16842', '168544', '168620', '16869', '16870', '16871', '16872', '16874', '16876', '16909', '16917', '16918', '16969', '16978', '169792', '170302', '170574', '170671', '170729', '170820', '170825', '170909', '170959', '171017', '171018', '171068', '171078', '171137', '17119', '17121', '17122', '17125', '17126', '17127', '17128', '17129', '171299', '17130', '171302', '17132', '17133', '17134', '17135', '171355', '171356', '171360', '171454', '17172', '17173', '17187', '17188', '17258', '17259', '17260', '17261', '17268', '17285', '17286', '17292', '17293', '17300', '17301', '17341', '17342', '17425', '17428', '1745', '1746', '1747', '1748', '1749', '1750', '17536', '1761', '17681', '17701', '17702', '17764', '17765', '17859', '17863', '17864', '17865', '17869', '17876', '17877', '17878', '17927', '17928', '17932', '17933', '18012', '18013', '18014', '18018', '18019', '18021', '18022', '18023', '18024', '18025', '18027', '18028', '18029', '18030', '18032', '18033', '18034', '18044', '18046', '18071', '18072', '18088', '18089', '18091', '18092', '18094', '18095', '18096', '18109', '18124', '18142', '18143', '18171', '18181', '18185', '1820', '18227', '18291', '18420', '18423', '18424', '18426', '18503', '18504', '18505', '18506', '18507', '18508', '18509', '18510', '18511', '18514', '18515', '18516', '18609', '18612', '18616', '18617', '18667', '1869', '1870', '1871', '18736', '1874', '18740', '18741', '18742', '1875', '1876', '1877', '18771', '1879', '18933', '18935', '18986', '18987', '18988', '18991', '18992', '18993', '18994', '18996', '18997', '18998', '18999', '190', '19009', '19013', '19015', '19016', '19127', '19130', '192109', '192110', '19213', '192274', '19290', '19291', '19377', '19401', '19411', '19434', '194655', '195333', '195733', '1958', '195828', '1959', '196', '1960', '1961', '19664', '19668', '19696', '19697', '19698', '19712', '19724', '19725', '19726', '19821', '19883', '19885', '1997', '1998', '1999', '2000', '2001', '2002', '200350', '2004', '2005', '201516', '2016', '2018', '20181', '20182', '20183', '20186', '2019', '2020', '20204', '2023', '20230', '20231', '20289', '2034', '20371', '20375', '20429', '20464', '20465', '20471', '20472', '20473', '20474', '20475', '20476', '20482', '20583', '20585', '20613', '2063', '20658', '20664', '20665', '20666', '20667', '20668', '20669', '20670', '20671', '20672', '20674', '20675', '20677', '20678', '20679', '20680', '20681', '20682', '20683', '20687', '20688', '20689', '20728', '2077', '207785', '2078', '20787', '20788', '20807', '208076', '208104', '20841', '20846', '20847', '20848', '20849', '20850', '20851', '20852', '208647', '208677', '20893', '209446', '209448', '209707', '2099', '20997', '2100', '2101', '2103', '2104', '210719', '2113', '211323', '2114', '2115', '211586', '2116', '2117', '2118', '2119', '2120', '2122', '212712', '2130', '21349', '21375', '21380', '21384', '21385', '21386', '21387', '21388', '21389', '21405', '21406', '21407', '21408', '21410', '214105', '21411', '21412', '21413', '21414', '21415', '21416', '214162', '21417', '21418', '21419', '21420', '21422', '21423', '21425', '21426', '21428', '21454', '214855', '215418', '216285', '21674', '21676', '21677', '21679', '21685', '217082', '217166', '21769', '21780', '21781', '218030', '21804', '21807', '218100', '21815', '21833', '21834', '21847', '21869', '218772', '21907', '21908', '21909', '219150', '219409', '220202', '22025', '22026', '22059', '22062', '22157', '22160', '22165', '221833', '221937', '22221', '222546', '22259', '22260', '22278', '22282', '222894', '223227', '22337', '22344', '223669', '223843', '223922', '22431', '22433', '224656', '225497', '225631', '225872', '225998', '226049', '226075', '22608', '22632', '22634', '22640', '22642', '226442', '22661', '226641', '22666', '22671', '22685', '226896', '22694', '22696', '22697', '22701', '22702', '22712', '22724', '22751', '22754', '22755', '22757', '22758', '227631', '22764', '22767', '22771', '22772', '22773', '22774', '22778', '22779', '22780', '22797', '22806', '22807', '22809', '22823', '22834', '228598', '228662', '22877', '22882', '228829', '22887', '228880', '22890', '228911', '228913', '2290', '229004', '229007', '22903', '229055', '22926', '2294', '22947', '2295', '2296', '2297', '2298', '2299', '2300', '230025', '2301', '230119', '230162', '2302', '2303', '23036', '2304', '23040', '2305', '23051', '230587', '2306', '2307', '230700', '2308', '230824', '2309', '23090', '231044', '23119', '2313', '23152', '231991', '232430', '23261', '23269', '232791', '232879', '232906', '232934', '233060', '23314', '23316', '233410', '234219', '23440', '23493', '23512', '23528', '2353', '235320', '2354', '2355', '23613', '23660', '237336', '23764', '237911', '238455', '23849', '23856', '23857', '238673', '23871', '23872', '239099', '239546', '23958', '23967', '240690', '241066', '24113', '24136', '241514', '24208', '24209', '242509', '24252', '24253', '242705', '24309', '24330', '24333', '24356', '24370', '243833', '24388', '243931', '243937', '24413', '244219', '24452', '24453', '24457', '244579', '24459', '24460', '244713', '244813', '24508', '24516', '24517', '24518', '24522', '245368', '245572', '245583', '245595', '24566', '245671', '24577', '245980', '246073', '246086', '246149', '246264', '246271', '246282', '246301', '24631', '246334', '246361', '246760', '24705', '24706', '24790', '24817', '24831', '24842', '24873', '24883', '24890', '24916', '24918', '24919', '2494', '25094', '25098', '25099', '25100', '25124', '25125', '25126', '25129', '25148', '25149', '25154', '25157', '25159', '2516', '25162', '25172', '25221', '25231', '25242', '25243', '25271', '252856', '252880', '252885', '252886', '252915', '252917', '252924', '252973', '25301', '25334', '25337', '253738', '25389', '25401', '25410', '254251', '25431', '25445', '25446', '25483', '25492', '25509', '2551', '25517', '25546', '25554', '255877', '25591', '25607', '25620', '25628', '256297', '25631', '256380', '25640', '25646', '25664', '25671', '25672', '25682', '25690', '25695', '257', '25701', '25705', '25714', '25720', '25735', '25747', '257634', '25803', '25806', '25833', '259241', '25988', '260298', '260325', '26137', '26205', '2623', '2624', '2625', '26257', '2626', '2627', '26296', '26298', '2636', '2637', '26379', '26380', '26381', '26386', '26423', '26424', '26427', '26468', '2649', '26508', '26584', '266680', '266716', '266734', '266738', '266743', '266787', '266792', '266813', '2672', '268297', '268417', '268469', '268564', '26910', '26927', '269389', '269401', '26959', '269800', '270004', '27022', '27023', '27049', '27056', '27080', '27086', '27164', '27217', '272322', '272382', '27287', '27319', '27324', '2735', '2736', '2737', '27386', '277353', '282825', '282840', '283078', '283150', '284695', '286101', '286380', '287074', '287076', '287185', '287361', '287423', '287441', '287469', '287521', '287615', '287638', '287647', '287940', '288105', '288151', '288152', '288153', '288154', '288353', '288457', '288665', '288736', '288774', '288821', '288906', '289026', '289048', '289201', '289230', '289311', '289595', '289752', '289754', '28999', '290221', '290317', '290749', '290765', '2908', '2909', '291100', '291105', '291228', '29148', '291908', '291960', '29203', '292060', '29227', '29228', '292301', '292404', '292721', '29279', '2928', '292820', '292892', '292934', '292935', '29300', '293012', '293017', '293038', '293046', '293104', '293165', '293405', '293537', '293568', '29357', '29361', '29362', '293624', '293701', '29394', '293992', '29410', '294322', '294328', '294395', '294515', '29452', '294562', '29458', '294640', '29467', '294924', '29508', '295248', '295297', '295315', '295327', '29535', '295475', '295568', '29560', '29567', '295695', '29577', '29588', '29589', '295965', '29609', '296201', '296272', '296281', '296320', '296344', '296374', '296399', '296420', '296478', '296499', '296500', '296510', '296511', '29657', '296706', '296953', '29721', '297480', '297705', '297769', '297783', '297804', '29808', '298084', '298189', '298316', '298400', '29841', '29842', '298449', '298506', '298555', '29861', '298732', '298878', '298894', '299016', '299061', '299138', '299186', '299206', '299210', '299499', '299766', '299897', '299979', '300054', '30009', '300095', '300260', '30046', '30051', '30062', '300807', '300947', '300954', '301038', '301121', '301284', '301285', '301476', '301570', '302327', '302333', '302369', '302400', '302415', '302582', '302583', '302811', '302946', '302962', '302993', '303164', '303188', '303226', '303310', '303398', '303399', '303469', '303480', '303488', '303489', '303491', '303496', '303499', '303511', '303698', '303753', '303828', '303836', '303970', '303991', '304005', '304054', '304056', '304063', '304071', '304092', '304103', '304127', '304275', '304298', '304342', '304479', '304514', '304666', '304729', '304741', '304786', '304815', '304850', '304935', '304947', '304962', '305066', '305083', '305311', '305471', '305494', '305501', '305584', '305589', '305719', '305848', '305854', '305858', '305896', '305897', '305968', '305972', '305999', '306110', '306168', '306330', '306400', '306657', '306659', '306695', '3068', '306862', '306873', '306977', '307217', '307498', '307547', '307715', '307721', '307740', '307794', '307806', '307820', '307829', '307834', '307839', '307919', '30812', '308126', '30818', '308311', '30832', '308336', '30834', '308363', '308366', '308387', '3084', '308406', '308411', '308435', '308482', '308523', '308582', '308607', '3087', '308766', '308900', '3090', '309002', '309031', '309095', '3091', '309164', '309165', '30923', '30927', '30928', '309288', '309389', '30942', '309430', '30944', '309452', '309457', '3096', '3097', '309728', '309859', '309871', '309888', '309900', '309957', '310375', '310616', '310659', '310660', '311071', '311093', '311311', '311414', '311462', '311505', '311508', '311547', '311575', '311604', '311615', '311658', '311721', '311723', '311742', '311764', '311832', '311876', '311901', '312195', '312203', '312303', '312331', '312451', '312777', '312897', '312936', '3131', '313166', '313219', '313504', '313507', '313512', '313554', '313557', '313558', '313575', '313666', '313678', '313913', '313978', '313993', '313994', '3142', '314221', '314246', '314322', '314374', '314423', '314436', '314539', '314586', '314616', '314638', '314675', '314711', '314818', '314988', '315039', '315081', '315101', '315305', '315308', '315309', '315333', '315337', '315338', '315341', '315497', '315532', '315601', '315606', '315689', '315804', '315870', '315882', '3159', '316052', '316102', '316164', '316214', '316327', '316351', '3164', '3166', '316626', '316742', '3169', '3170', '3171', '3172', '317268', '317376', '317382', '3174', '3175', '317715', '3182', '3190', '3195', '3196', '319758', '3198', '3199', '3200', '3201', '320145', '3202', '320267', '3203', '3204', '3205', '320522', '3206', '3207', '320799', '3209', '320995', '3211', '3212', '3213', '3214', '3215', '3216', '3217', '3218', '3219', '3221', '3222', '3223', '3224', '3226', '3227', '3229', '3231', '3232', '3233', '3234', '3235', '3236', '3237', '3239', '326', '328', '3280', '3297', '3298', '3299', '329934', '332221', '332937', '333929', '3344', '337868', '338917', '339344', '3394', '339488', '339559', '340069', '340385', '340784', '3428', '342909', '3431', '343472', '344018', '346389', '347853', '3516', '353088', '353187', '353227', '353305', '360204', '360389', '360482', '360551', '360588', '360610', '360631', '360635', '3607', '360737', '360775', '360858', '360896', '360905', '360960', '360961', '361060', '361095', '361096', '361131', '361400', '361508', '361544', '361576', '361627', '361630', '361668', '361746', '361784', '361801', '361809', '361816', '361944', '361946', '362085', '362106', '362125', '362165', '362176', '362268', '362280', '362286', '362291', '362339', '362391', '362453', '362464', '362530', '362591', '362665', '362675', '362686', '362733', '362741', '362871', '362896', '362925', '362948', '363165', '363185', '363243', '363595', '363632', '363656', '363667', '363672', '363684', '363735', '363831', '364069', '364081', '364140', '364152', '3642', '364418', '364510', '364680', '364706', '364712', '364855', '364883', '364910', '3651', '365299', '365371', '365564', '365744', '365748', '3659', '365900', '3660', '366078', '3661', '366126', '366142', '3662', '366210', '366214', '366229', '3663', '366340', '3664', '3665', '366542', '366598', '366829', '366949', '366951', '366954', '366960', '366964', '366996', '366998', '367', '3670', '367092', '367100', '367106', '367152', '367218', '367264', '367314', '367832', '367846', '367944', '367950', '368057', '368158', '3720', '3725', '3726', '3727', '378435', '380912', '380993', '381319', '381359', '381373', '381463', '381549', '381990', '382066', '382074', '382639', '383491', '385674', '387609', '388112', '388566', '388585', '389058', '389549', '389692', '390010', '390259', '390874', '390992', '391723', '3975', '399489', '399823', '4005', '4009', '401', '4010', '402381', '404281', '405', '406', '406164', '406169', '4084', '4086', '4087', '4088', '4089', '4090', '4091', '4094', '4097', '414065', '4149', '4150', '4205', '4207', '4208', '4209', '4211', '4212', '4222', '4223', '4286', '429', '4297', '430', '4303', '4306', '432731', '4330', '4335', '433938', '434174', '436240', '440097', '442425', '4487', '4488', '4520', '4601', '4602', '4603', '4605', '4609', '4610', '4613', '4617', '4618', '463', '4654', '4656', '466', '4661', '467', '468', '474', '4760', '4761', '4762', '4772', '4773', '4774', '4775', '4776', '4778', '4779', '4780', '4781', '4782', '4783', '4784', '4790', '4791', '4799', '4800', '4802', '4807', '4808', '4821', '4824', '4825', '4849', '4861', '4862', '4899', '4901', '4904', '4929', '494344', '497984', '497985', '497986', '497987', '497988', '498194', '498407', '49854', '498545', '498575', '498607', '498633', '498864', '498918', '498945', '498952', '4990', '499016', '499090', '499146', '499171', '499361', '499362', '499380', '499497', '499510', '499593', '499874', '499900', '499951', '499952', '499964', '500023', '500037', '500048', '500110', '500126', '500129', '500131', '500137', '500156', '500235', '500239', '500538', '500558', '500574', '500818', '500950', '500964', '500981', '500982', '501099', '501145', '5013', '5015', '501506', '5017', '502759', '502886', '502946', '50496', '50524', '50545', '50552', '50554', '50659', '50662', '50674', '5075', '5076', '5077', '5078', '5079', '50794', '50796', '5080', '50804', '5081', '5083', '50862', '5087', '5089', '5090', '50907', '50913', '50914', '50943', '50945', '51043', '51085', '51157', '51176', '51193', '51222', '51230', '51270', '51274', '51341', '51351', '51385', '51450', '51513', '51533', '51621', '5178', '51804', '51886', '5241', '52615', '52679', '52712', '5307', '5308', '5309', '5316', '5324', '5325', '5326', '53314', '53335', '53404', '53415', '53417', '53626', '5396', '53970', '54006', '54123', '54131', '54139', '541457', '54254', '54264', '54267', '54276', '54278', '54284', '54345', '54352', '54367', '54422', '54446', '5449', '5451', '5452', '5453', '5454', '545474', '5455', '5456', '5457', '5458', '54585', '5459', '5460', '54601', '54626', '5463', '5465', '5467', '5468', '54711', '54713', '54738', '54796', '54897', '54937', '550619', '55079', '55274', '55502', '55509', '55553', '55565', '55578', '55634', '55657', '55806', '55810', '55840', '55893', '55897', '55900', '55922', '55927', '56033', '56198', '56218', '56259', '5626', '5629', '56380', '56449', '56458', '56461', '56484', '56490', '56501', '56676', '56711', '56722', '56734', '56751', '56787', '56790', '56805', '56809', '56938', '56956', '56980', '56987', '56995', '57057', '571', '57167', '57215', '57233', '57246', '57343', '57432', '57473', '57592', '57593', '57594', '57615', '57616', '57621', '57623', '57659', '57693', '57765', '57801', '57822', '579', '5813', '5814', '58158', '58180', '58198', '58208', '58495', '58500', '58805', '58820', '58842', '58850', '58851', '58852', '58853', '58921', '58954', '59016', '59057', '59058', '59112', '5914', '5915', '5916', '59269', '59328', '59335', '59336', '59348', '5966', '5970', '5971', '5978', '5989', '5990', '5991', '5992', '5993', '60329', '60349', '60351', '60394', '604', '60446', '60447', '6045', '60462', '60468', '60529', '60563', '60611', '60661', '60685', '6095', '6096', '6097', '619575', '619665', '6239', '6256', '6257', '6258', '6297', '6299', '6304', '630579', '63876', '639', '63973', '63974', '63976', '63977', '63978', '64067', '641339', '64186', '64188', '64288', '64290', '64321', '64332', '64344', '64345', '643609', '64376', '64379', '64406', '64412', '644168', '64441', '64444', '64530', '64572', '646', '64618', '64619', '64628', '64637', '64641', '64651', '6473', '6474', '64764', '64826', '64843', '64864', '64919', '6492', '6493', '6495', '6496', '6498', '65035', '65050', '65100', '65161', '65193', '65199', '653404', '653427', '654496', '6591', '6596', '65986', '66019', '66136', '6615', '66277', '664783', '664799', '6651', '6656', '6657', '6658', '6659', '6660', '6662', '6663', '6664', '66642', '6665', '6666', '6667', '6668', '6670', '6671', '668', '66830', '66867', '6688', '6689', '66953', '67143', '67150', '6720', '6721', '6722', '67255', '6736', '6772', '6773', '6774', '6775', '6776', '6777', '67778', '6778', '679028', '679571', '679701', '679712', '679869', '680117', '680201', '680427', '680620', '680712', '680751', '681092', '681359', '683504', '684085', '685072', '685102', '685360', '685732', '686117', '6862', '687', '68750', '688', '68837', '68842', '6886', '688699', '688822', '688999', '689030', '68910', '689210', '689695', '689788', '6899', '689918', '68992', '689988', '690430', '690820', '6909', '6910', '6911', '6913', '691398', '691556', '691842', '69228', '6925', '69257', '6926', '6927', '6928', '6929', '6932', '6934', '6935', '6936', '6938', '6939', '6940', '6942', '6943', '6945', '69743', '69890', '7003', '7004', '7008', '70127', '7019', '7020', '7021', '7022', '7023', '7024', '7025', '7026', '7027', '7029', '7030', '7041', '7050', '70508', '7067', '70673', '7068', '7071', '70779', '7080', '70998', '7101', '71041', '71137', '71371', '71375', '7157', '71591', '7161', '71702', '71722', '7181', '7182', '71838', '71950', '72057', '72154', '7227', '72465', '72567', '72739', '727857', '727940', '72843', '7287', '7288', '728957', '7291', '7294', '73181', '73191', '73389', '7342', '7376', '7391', '7392', '74007', '74120', '74123', '74164', '7421', '74352', '74434', '74451', '745', '74533', '74561', '7490', '7494', '7528', '7539', '7541', '7543', '7544', '7545', '7546', '7547', '75507', '7552', '7553', '7554', '7555', '7556', '75580', '7566', '7567', '7570', '7571', '7572', '75753', '7584', '7587', '75871', '7589', '7592', '7593', '7594', '7596', '7629', '7634', '76365', '7637', '7639', '7643', '7644', '7678', '7690', '7691', '7692', '7693', '7694', '7695', '7697', '7699', '7702', '7704', '7707', '7709', '7710', '7711', '7712', '7716', '7718', '7727', '7728', '77286', '7730', '7732', '7741', '7743', '7746', '7753', '7755', '7761', '7762', '7764', '7767', '7773', '77771', '7799', '78266', '78284', '7849', '78912', '78968', '78972', '78974', '790969', '79116', '79190', '79191', '79192', '79225', '79237', '79240', '79241', '79245', '79255', '79362', '79365', '79401', '7942', '79431', '79618', '79692', '79733', '7975', '79759', '79800', '79923', '79977', '80034', '8013', '8022', '80317', '80320', '80338', '8061', '80709', '80712', '80714', '80720', '80778', '80859', '80902', '8091', '8092', '8110', '81518', '81524', '81566', '81646', '81647', '81703', '81710', '81717', '81736', '81808', '81812', '81813', '81817', '81819', '8187', '81879', '8193', '81931', '8320', '8328', '83383', '83395', '83396', '83439', '83463', '83474', '83482', '83498', '83574', '83586', '83595', '83618', '83619', '83630', '83632', '83635', '83726', '83741', '83807', '83826', '83855', '83879', '83881', '83925', '83990', '83993', '84017', '8403', '84046', '84107', '84108', '84159', '84295', '84382', '84385', '84410', '84449', '84482', '84504', '84524', '84528', '8456', '84574', '84619', '8462', '8463', '84653', '84654', '84662', '84667', '84699', '84838', '84839', '84878', '84891', '84911', '84969', '8521', '8531', '8538', '85416', '85424', '85434', '8545', '85471', '85489', '85497', '85508', '8553', '8570', '860', '8609', '861', '8626', '864', '8726', '8820', '8848', '8856', '8880', '8928', '8929', '8939', '89884', '90316', '90333', '9095', '9096', '90987', '90993', '91752', '9189', '91975', '9208', '9242', '9314', '9355', '93691', '93730', '93837', '93986', '94187', '94188', '9421', '94222', '94234', '9464', '9480', '9489', '9496', '9516', '9519', '9572', '9575', '9580', '9586', '9592', '9603', '9640', '9705', '9745', '9753', '9774', '9839', '988', '9915', '9925', '9935', '99377', '9970', '9971', '9975', '9988', '12151', '12400', '15901', '15902', '15903', '161882', '17131', '19017', '23414', '4092', '672', '9612')"; static final String MAMMALIAN_TF_QUERY = "SELECT r.accession, s.value FROM " + "genes AS g, gene_strings AS s, gene_refs AS r WHERE g.id = s.id AND g.id = r.id " + "AND s.cat = 'symbol' AND r.namespace = 'gi' AND r.accession IN " + MAMMALIAN_TF_IDS; private RelationshipExtractor() { throw new AssertionError("n/a"); } public static ExternalResourceDescription getGazetteerResource(CommandLine cmd, Logger l, String querySql, boolean idMatching, boolean exactCaseMatching, String defaultDriverClass, String defaultProvider, String defaultDbName) throws ResourceInitializationException, ClassNotFoundException { // driver class name final String driverClass = cmd.getOptionValue('D', defaultDriverClass); Class.forName(driverClass); // db url final String dbHost = cmd.getOptionValue('H', "localhost"); final String dbProvider = cmd.getOptionValue('P', defaultProvider); final String dbName = cmd.getOptionValue('d', defaultDbName); final String dbUrl = String.format("jdbc:%s://%s/%s", dbProvider, dbHost, dbName); l.log(Level.INFO, "JDBC URL: {0}", dbUrl); // create builder JdbcGazetteerResource.Builder b = JdbcGazetteerResource .configure(dbUrl, driverClass, querySql).idMatching() .setSeparators(JdbcGazetteerResource.SEPARATORS + "\\:\\,\\.\\/\\\\\\[\\]\\{\\}\\(\\)"); // set username/password options if (cmd.hasOption('u')) b.setUsername(cmd.getOptionValue('u')); if (cmd.hasOption('p')) b.setPassword(cmd.getOptionValue('p')); return b.create(); } public static void main(String[] arguments) { final CommandLineParser parser = new PosixParser(); final Options opts = new Options(); CommandLine cmd = null; Pipeline.addLogHelpAndInputOptions(opts); Pipeline.addTikaOptions(opts); Pipeline.addJdbcResourceOptions(opts, DEFAULT_JDBC_DRIVER, DEFAULT_DB_PROVIDER, DEFAULT_DATABASE); Pipeline.addOutputOptions(opts); // sentence splitter options opts.addOption("S", "successive-newlines", false, "split sentences on successive newlines"); opts.addOption("s", "single-newlines", false, "split sentences on single newlines"); // sentence filter options opts.addOption("f", "filter-sentences", true, "retain sentences using a file of regex matches"); opts.addOption("F", "filter-remove", false, "filter removes sentences with matches"); // tokenizer options setup opts.addOption("G", "genia", true, "use GENIA (with the dir containing 'morphdic/') instead of OpenNLP"); // semantic patterns - REQUIRED! opts.addOption("p", "patterns", true, "match sentences with semantic patterns"); // actor and target ID, name pairs opts.addOption("a", "actor-sql", true, "SQL query that produces actor ID, name pairs"); opts.addOption("t", "target-sql", true, "SQL query that produces target ID, name pairs"); try { cmd = parser.parse(opts, arguments); } catch (final ParseException e) { System.err.println(e.getLocalizedMessage()); System.exit(1); // == EXIT == } final Logger l = Pipeline.loggingSetup(cmd, opts, "txtfnnl rex [options] -p <patterns> <directory|files...>\n"); // sentence splitter String splitSentences = null; // S, s if (cmd.hasOption('s')) { splitSentences = "single"; } else if (cmd.hasOption('S')) { splitSentences = "successive"; } // sentence filter final File sentenceFilterPatterns = cmd.hasOption('f') ? new File(cmd.getOptionValue('f')) : null; final boolean removingSentenceFilter = cmd.hasOption('F'); // (GENIA) tokenizer final String geniaDir = cmd.getOptionValue('G'); // semantic patterns File patterns = null; try { patterns = new File(cmd.getOptionValue('p')); } catch (NullPointerException e) { l.severe("no patterns file"); System.err.println("patterns file missing"); System.exit(1); // == EXIT == } // entity queries final String actorSQL = cmd.hasOption('a') ? cmd.getOptionValue('a') : MAMMALIAN_TF_QUERY; final String targetSQL = cmd.hasOption('t') ? cmd.getOptionValue('t') : DEFAULT_SQL_QUERY; // DB resource ExternalResourceDescription actorGazetteer = null; ExternalResourceDescription targetGazetteer = null; try { actorGazetteer = getGazetteerResource(cmd, l, actorSQL, true, false, DEFAULT_JDBC_DRIVER, DEFAULT_DB_PROVIDER, DEFAULT_DATABASE); targetGazetteer = getGazetteerResource(cmd, l, targetSQL, true, false, DEFAULT_JDBC_DRIVER, DEFAULT_DB_PROVIDER, DEFAULT_DATABASE); } catch (final ResourceInitializationException e) { System.err.println("JDBC resoruce setup failed:"); System.err.println(e.toString()); System.exit(1); // == EXIT == } catch (final ClassNotFoundException e) { System.err.println("JDBC driver class unknown:"); System.err.println(e.toString()); System.exit(1); // == EXIT == } // output (format) final String encoding = Pipeline.outputEncoding(cmd); final File outputDirectory = Pipeline.outputDirectory(cmd); final boolean overwriteFiles = Pipeline.outputOverwriteFiles(cmd); try { ExternalResourceDescription patternResource = LineBasedStringArrayResource.configure( "file:" + patterns.getCanonicalPath()).create(); // 0:tika, 1:splitter, 2:filter, 3:tokenizer, 4:lemmatizer, 5:patternMatcher, // 6:actor gazetteer, 7:target gazetteer, 8:filter regulator 9: filter target final Pipeline rex = new Pipeline(10); rex.setReader(cmd); rex.configureTika(cmd); rex.set(1, SentenceAnnotator.configure(splitSentences)); if (sentenceFilterPatterns == null) rex.set(2, NOOPAnnotator.configure()); else rex.set(2, SentenceFilter.configure(sentenceFilterPatterns, removingSentenceFilter)); if (geniaDir == null) { rex.set(3, TokenAnnotator.configure()); rex.set(4, BioLemmatizerAnnotator.configure()); } else { rex.set(3, GeniaTaggerAnnotator.configure(new File(geniaDir))); // the GENIA Tagger already lemmatizes; nothing to do rex.set(4, NOOPAnnotator.configure()); } rex.set(5, SyntaxPatternAnnotator.configure(patternResource).removeUnmatched().create()); rex.set(6, GazetteerAnnotator.configure("UniProt", actorGazetteer).setTextNamespace("actor") .setTextIdentifier("regulator").create()); rex.set(7, GazetteerAnnotator.configure("Entrez", targetGazetteer).setTextNamespace("actor") .setTextIdentifier("target").create()); rex.set(8, RelationshipFilter.configure(SyntaxPatternAnnotator.URI, "event", "tre", SyntaxPatternAnnotator.URI, "actor", "regulator", GazetteerAnnotator.URI, "UniProt", null, false)); rex.set(9, RelationshipFilter.configure(SyntaxPatternAnnotator.URI, "event", "tre", SyntaxPatternAnnotator.URI, "actor", "target", GazetteerAnnotator.URI, "Entrez", null, false)); rex.setConsumer(RelationshipWriter.configure(outputDirectory, encoding, outputDirectory == null, overwriteFiles, true, null, true, true)); rex.run(); } catch (final UIMAException e) { l.severe(e.toString()); System.err.println(e.getLocalizedMessage()); System.exit(1); // == EXIT == } catch (final IOException e) { l.severe(e.toString()); System.err.println(e.getLocalizedMessage()); System.exit(1); // == EXIT == } System.exit(0); } }
comments updated
txtfnnl-bin/src/main/java/txtfnnl/pipelines/RelationshipExtractor.java
comments updated
<ide><path>xtfnnl-bin/src/main/java/txtfnnl/pipelines/RelationshipExtractor.java <ide> static final String DEFAULT_DATABASE = "gnamed"; <ide> static final String DEFAULT_JDBC_DRIVER = "org.postgresql.Driver"; <ide> static final String DEFAULT_DB_PROVIDER = "postgresql"; <del> // default entity set: all human and mouse gene symbols (roughly 300k symbols) <add> // default entity set: all human, mouse, and rat gene symbols (roughly 500k symbols) <ide> static final String DEFAULT_SQL_QUERY = "SELECT r.accession, s.value FROM " <ide> + "genes AS g, gene_strings AS s, gene_refs AS r WHERE g.id = s.id AND g.id = r.id " <ide> + "AND g.species_id IN (9606, 10090, 10116) AND s.cat = 'symbol' AND r.namespace = 'gi'"; <add> // TODO: make this next thing a parameter (SQL query files?) <ide> static final String MAMMALIAN_TF_IDS = "('10002', '100072', '100073351', '10009', '100128927', '100129885', '100131390', '100132074', '100182', '100187701', '100271849', '100361818', '100361836', '10062', '100978', '101023', '10113', '10127', '10153', '10172', '10194', '10215', '102423', '102442', '10260', '10265', '10308', '10320', '10357', '10363', '10365', '10379', '103836', '103889', '104156', '104338', '104360', '104382', '104394', '1044', '1045', '1046', '10472', '10481', '10485', '10488', '1050', '1051', '1052', '10522', '1053', '10538', '1054', '10553', '10608', '106143', '10620', '106389', '10655', '10660', '10661', '10664', '10691', '10716', '10725', '10732', '10736', '10743', '107503', '107586', '107587', '107751', '10782', '10795', '10865', '108655', '108961', '109032', '109575', '109663', '109889', '109910', '109947', '109948', '11016', '110521', '110593', '11063', '110648', '110685', '110784', '110794', '110796', '110805', '11083', '11107', '11108', '1112', '11166', '112400', '112770', '11278', '11279', '11281', '112939', '11317', '113931', '113983', '113984', '114090', '114109', '114142', '114208', '114213', '114485', '114498', '114499', '114500', '114501', '114502', '114503', '114505', '114519', '114565', '114604', '114634', '114712', '114845', '11545', '11568', '11569', '115768', '116039', '116113', '11614', '11622', '11634', '116448', '116490', '116543', '116544', '116545', '116557', '116639', '116648', '116651', '116668', '116674', '116810', '11694', '11695', '117034', '117058', '117062', '117095', '117107', '117140', '117154', '117232', '117282', '117560', '11792', '11819', '11835', '118445', '11859', '11863', '11864', '11865', '11878', '11906', '11908', '11909', '11910', '11911', '11921', '11922', '11923', '11924', '11925', '12013', '12014', '12020', '12022', '12023', '120237', '12029', '12053', '121340', '12142', '121536', '121551', '121599', '121643', '12173', '12224', '122953', '12355', '12393', '12394', '12399', '124411', '12590', '12591', '12592', '12606', '12607', '12608', '12609', '12611', '12677', '127343', '12753', '12785', '128209', '128408', '128553', '12912', '12913', '12915', '12916', '12951', '13017', '13018', '13047', '13048', '130497', '130557', '1316', '13170', '13172', '13198', '132625', '13390', '13392', '13393', '13394', '13395', '13396', '134187', '13496', '13555', '13557', '13559', '13560', '13591', '13592', '13593', '135935', '136259', '13626', '13653', '13654', '13655', '13656', '13661', '13709', '13710', '13711', '13712', '13713', '13714', '137814', '13796', '13797', '13798', '13799', '13806', '13813', '13819', '1385', '1386', '13864', '13865', '138715', '13875', '13876', '1388', '1389', '1390', '139628', '13982', '13983', '13984', '14008', '14009', '14011', '14013', '14025', '14030', '140477', '140489', '140586', '140587', '140588', '140589', '1406', '140628', '140690', '14106', '142', '14233', '14234', '14235', '14236', '14237', '14238', '14239', '14240', '14241', '14247', '14281', '14282', '14283', '14284', '14390', '144455', '14460', '14461', '14462', '14463', '14464', '14465', '14472', '145258', '14531', '14536', '14581', '14582', '145873', '14632', '14633', '14634', '147912', '14815', '148198', '1482', '148327', '14836', '14842', '14843', '1488', '148979', '14912', '15110', '15111', '15191', '15205', '15206', '15207', '15208', '15209', '15214', '15218', '15220', '15221', '15223', '15227', '15228', '15229', '1523', '15242', '15248', '15251', '152518', '15273', '15284', '153222', '153572', '15361', '15364', '15370', '15371', '15373', '15375', '15376', '15377', '15378', '15379', '15384', '15387', '15394', '15395', '15396', '15398', '15399', '15400', '15401', '15402', '15403', '15404', '15405', '15407', '15408', '15410', '15412', '15413', '15414', '15415', '15416', '15417', '15422', '15423', '15424', '15425', '15426', '15429', '15430', '15431', '15433', '15434', '15436', '15437', '15438', '15460', '15499', '15500', '155061', '155430', '156726', '157848', '15900', '159296', '15936', '15951', '161452', '162239', '1628', '163059', '16362', '16363', '16364', '16371', '16372', '16373', '16391', '16392', '16468', '16476', '16477', '16478', '1649', '165', '16549', '16596', '16597', '16598', '16599', '16600', '16601', '16656', '16658', '167826', '16814', '168374', '16842', '168544', '168620', '16869', '16870', '16871', '16872', '16874', '16876', '16909', '16917', '16918', '16969', '16978', '169792', '170302', '170574', '170671', '170729', '170820', '170825', '170909', '170959', '171017', '171018', '171068', '171078', '171137', '17119', '17121', '17122', '17125', '17126', '17127', '17128', '17129', '171299', '17130', '171302', '17132', '17133', '17134', '17135', '171355', '171356', '171360', '171454', '17172', '17173', '17187', '17188', '17258', '17259', '17260', '17261', '17268', '17285', '17286', '17292', '17293', '17300', '17301', '17341', '17342', '17425', '17428', '1745', '1746', '1747', '1748', '1749', '1750', '17536', '1761', '17681', '17701', '17702', '17764', '17765', '17859', '17863', '17864', '17865', '17869', '17876', '17877', '17878', '17927', '17928', '17932', '17933', '18012', '18013', '18014', '18018', '18019', '18021', '18022', '18023', '18024', '18025', '18027', '18028', '18029', '18030', '18032', '18033', '18034', '18044', '18046', '18071', '18072', '18088', '18089', '18091', '18092', '18094', '18095', '18096', '18109', '18124', '18142', '18143', '18171', '18181', '18185', '1820', '18227', '18291', '18420', '18423', '18424', '18426', '18503', '18504', '18505', '18506', '18507', '18508', '18509', '18510', '18511', '18514', '18515', '18516', '18609', '18612', '18616', '18617', '18667', '1869', '1870', '1871', '18736', '1874', '18740', '18741', '18742', '1875', '1876', '1877', '18771', '1879', '18933', '18935', '18986', '18987', '18988', '18991', '18992', '18993', '18994', '18996', '18997', '18998', '18999', '190', '19009', '19013', '19015', '19016', '19127', '19130', '192109', '192110', '19213', '192274', '19290', '19291', '19377', '19401', '19411', '19434', '194655', '195333', '195733', '1958', '195828', '1959', '196', '1960', '1961', '19664', '19668', '19696', '19697', '19698', '19712', '19724', '19725', '19726', '19821', '19883', '19885', '1997', '1998', '1999', '2000', '2001', '2002', '200350', '2004', '2005', '201516', '2016', '2018', '20181', '20182', '20183', '20186', '2019', '2020', '20204', '2023', '20230', '20231', '20289', '2034', '20371', '20375', '20429', '20464', '20465', '20471', '20472', '20473', '20474', '20475', '20476', '20482', '20583', '20585', '20613', '2063', '20658', '20664', '20665', '20666', '20667', '20668', '20669', '20670', '20671', '20672', '20674', '20675', '20677', '20678', '20679', '20680', '20681', '20682', '20683', '20687', '20688', '20689', '20728', '2077', '207785', '2078', '20787', '20788', '20807', '208076', '208104', '20841', '20846', '20847', '20848', '20849', '20850', '20851', '20852', '208647', '208677', '20893', '209446', '209448', '209707', '2099', '20997', '2100', '2101', '2103', '2104', '210719', '2113', '211323', '2114', '2115', '211586', '2116', '2117', '2118', '2119', '2120', '2122', '212712', '2130', '21349', '21375', '21380', '21384', '21385', '21386', '21387', '21388', '21389', '21405', '21406', '21407', '21408', '21410', '214105', '21411', '21412', '21413', '21414', '21415', '21416', '214162', '21417', '21418', '21419', '21420', '21422', '21423', '21425', '21426', '21428', '21454', '214855', '215418', '216285', '21674', '21676', '21677', '21679', '21685', '217082', '217166', '21769', '21780', '21781', '218030', '21804', '21807', '218100', '21815', '21833', '21834', '21847', '21869', '218772', '21907', '21908', '21909', '219150', '219409', '220202', '22025', '22026', '22059', '22062', '22157', '22160', '22165', '221833', '221937', '22221', '222546', '22259', '22260', '22278', '22282', '222894', '223227', '22337', '22344', '223669', '223843', '223922', '22431', '22433', '224656', '225497', '225631', '225872', '225998', '226049', '226075', '22608', '22632', '22634', '22640', '22642', '226442', '22661', '226641', '22666', '22671', '22685', '226896', '22694', '22696', '22697', '22701', '22702', '22712', '22724', '22751', '22754', '22755', '22757', '22758', '227631', '22764', '22767', '22771', '22772', '22773', '22774', '22778', '22779', '22780', '22797', '22806', '22807', '22809', '22823', '22834', '228598', '228662', '22877', '22882', '228829', '22887', '228880', '22890', '228911', '228913', '2290', '229004', '229007', '22903', '229055', '22926', '2294', '22947', '2295', '2296', '2297', '2298', '2299', '2300', '230025', '2301', '230119', '230162', '2302', '2303', '23036', '2304', '23040', '2305', '23051', '230587', '2306', '2307', '230700', '2308', '230824', '2309', '23090', '231044', '23119', '2313', '23152', '231991', '232430', '23261', '23269', '232791', '232879', '232906', '232934', '233060', '23314', '23316', '233410', '234219', '23440', '23493', '23512', '23528', '2353', '235320', '2354', '2355', '23613', '23660', '237336', '23764', '237911', '238455', '23849', '23856', '23857', '238673', '23871', '23872', '239099', '239546', '23958', '23967', '240690', '241066', '24113', '24136', '241514', '24208', '24209', '242509', '24252', '24253', '242705', '24309', '24330', '24333', '24356', '24370', '243833', '24388', '243931', '243937', '24413', '244219', '24452', '24453', '24457', '244579', '24459', '24460', '244713', '244813', '24508', '24516', '24517', '24518', '24522', '245368', '245572', '245583', '245595', '24566', '245671', '24577', '245980', '246073', '246086', '246149', '246264', '246271', '246282', '246301', '24631', '246334', '246361', '246760', '24705', '24706', '24790', '24817', '24831', '24842', '24873', '24883', '24890', '24916', '24918', '24919', '2494', '25094', '25098', '25099', '25100', '25124', '25125', '25126', '25129', '25148', '25149', '25154', '25157', '25159', '2516', '25162', '25172', '25221', '25231', '25242', '25243', '25271', '252856', '252880', '252885', '252886', '252915', '252917', '252924', '252973', '25301', '25334', '25337', '253738', '25389', '25401', '25410', '254251', '25431', '25445', '25446', '25483', '25492', '25509', '2551', '25517', '25546', '25554', '255877', '25591', '25607', '25620', '25628', '256297', '25631', '256380', '25640', '25646', '25664', '25671', '25672', '25682', '25690', '25695', '257', '25701', '25705', '25714', '25720', '25735', '25747', '257634', '25803', '25806', '25833', '259241', '25988', '260298', '260325', '26137', '26205', '2623', '2624', '2625', '26257', '2626', '2627', '26296', '26298', '2636', '2637', '26379', '26380', '26381', '26386', '26423', '26424', '26427', '26468', '2649', '26508', '26584', '266680', '266716', '266734', '266738', '266743', '266787', '266792', '266813', '2672', '268297', '268417', '268469', '268564', '26910', '26927', '269389', '269401', '26959', '269800', '270004', '27022', '27023', '27049', '27056', '27080', '27086', '27164', '27217', '272322', '272382', '27287', '27319', '27324', '2735', '2736', '2737', '27386', '277353', '282825', '282840', '283078', '283150', '284695', '286101', '286380', '287074', '287076', '287185', '287361', '287423', '287441', '287469', '287521', '287615', '287638', '287647', '287940', '288105', '288151', '288152', '288153', '288154', '288353', '288457', '288665', '288736', '288774', '288821', '288906', '289026', '289048', '289201', '289230', '289311', '289595', '289752', '289754', '28999', '290221', '290317', '290749', '290765', '2908', '2909', '291100', '291105', '291228', '29148', '291908', '291960', '29203', '292060', '29227', '29228', '292301', '292404', '292721', '29279', '2928', '292820', '292892', '292934', '292935', '29300', '293012', '293017', '293038', '293046', '293104', '293165', '293405', '293537', '293568', '29357', '29361', '29362', '293624', '293701', '29394', '293992', '29410', '294322', '294328', '294395', '294515', '29452', '294562', '29458', '294640', '29467', '294924', '29508', '295248', '295297', '295315', '295327', '29535', '295475', '295568', '29560', '29567', '295695', '29577', '29588', '29589', '295965', '29609', '296201', '296272', '296281', '296320', '296344', '296374', '296399', '296420', '296478', '296499', '296500', '296510', '296511', '29657', '296706', '296953', '29721', '297480', '297705', '297769', '297783', '297804', '29808', '298084', '298189', '298316', '298400', '29841', '29842', '298449', '298506', '298555', '29861', '298732', '298878', '298894', '299016', '299061', '299138', '299186', '299206', '299210', '299499', '299766', '299897', '299979', '300054', '30009', '300095', '300260', '30046', '30051', '30062', '300807', '300947', '300954', '301038', '301121', '301284', '301285', '301476', '301570', '302327', '302333', '302369', '302400', '302415', '302582', '302583', '302811', '302946', '302962', '302993', '303164', '303188', '303226', '303310', '303398', '303399', '303469', '303480', '303488', '303489', '303491', '303496', '303499', '303511', '303698', '303753', '303828', '303836', '303970', '303991', '304005', '304054', '304056', '304063', '304071', '304092', '304103', '304127', '304275', '304298', '304342', '304479', '304514', '304666', '304729', '304741', '304786', '304815', '304850', '304935', '304947', '304962', '305066', '305083', '305311', '305471', '305494', '305501', '305584', '305589', '305719', '305848', '305854', '305858', '305896', '305897', '305968', '305972', '305999', '306110', '306168', '306330', '306400', '306657', '306659', '306695', '3068', '306862', '306873', '306977', '307217', '307498', '307547', '307715', '307721', '307740', '307794', '307806', '307820', '307829', '307834', '307839', '307919', '30812', '308126', '30818', '308311', '30832', '308336', '30834', '308363', '308366', '308387', '3084', '308406', '308411', '308435', '308482', '308523', '308582', '308607', '3087', '308766', '308900', '3090', '309002', '309031', '309095', '3091', '309164', '309165', '30923', '30927', '30928', '309288', '309389', '30942', '309430', '30944', '309452', '309457', '3096', '3097', '309728', '309859', '309871', '309888', '309900', '309957', '310375', '310616', '310659', '310660', '311071', '311093', '311311', '311414', '311462', '311505', '311508', '311547', '311575', '311604', '311615', '311658', '311721', '311723', '311742', '311764', '311832', '311876', '311901', '312195', '312203', '312303', '312331', '312451', '312777', '312897', '312936', '3131', '313166', '313219', '313504', '313507', '313512', '313554', '313557', '313558', '313575', '313666', '313678', '313913', '313978', '313993', '313994', '3142', '314221', '314246', '314322', '314374', '314423', '314436', '314539', '314586', '314616', '314638', '314675', '314711', '314818', '314988', '315039', '315081', '315101', '315305', '315308', '315309', '315333', '315337', '315338', '315341', '315497', '315532', '315601', '315606', '315689', '315804', '315870', '315882', '3159', '316052', '316102', '316164', '316214', '316327', '316351', '3164', '3166', '316626', '316742', '3169', '3170', '3171', '3172', '317268', '317376', '317382', '3174', '3175', '317715', '3182', '3190', '3195', '3196', '319758', '3198', '3199', '3200', '3201', '320145', '3202', '320267', '3203', '3204', '3205', '320522', '3206', '3207', '320799', '3209', '320995', '3211', '3212', '3213', '3214', '3215', '3216', '3217', '3218', '3219', '3221', '3222', '3223', '3224', '3226', '3227', '3229', '3231', '3232', '3233', '3234', '3235', '3236', '3237', '3239', '326', '328', '3280', '3297', '3298', '3299', '329934', '332221', '332937', '333929', '3344', '337868', '338917', '339344', '3394', '339488', '339559', '340069', '340385', '340784', '3428', '342909', '3431', '343472', '344018', '346389', '347853', '3516', '353088', '353187', '353227', '353305', '360204', '360389', '360482', '360551', '360588', '360610', '360631', '360635', '3607', '360737', '360775', '360858', '360896', '360905', '360960', '360961', '361060', '361095', '361096', '361131', '361400', '361508', '361544', '361576', '361627', '361630', '361668', '361746', '361784', '361801', '361809', '361816', '361944', '361946', '362085', '362106', '362125', '362165', '362176', '362268', '362280', '362286', '362291', '362339', '362391', '362453', '362464', '362530', '362591', '362665', '362675', '362686', '362733', '362741', '362871', '362896', '362925', '362948', '363165', '363185', '363243', '363595', '363632', '363656', '363667', '363672', '363684', '363735', '363831', '364069', '364081', '364140', '364152', '3642', '364418', '364510', '364680', '364706', '364712', '364855', '364883', '364910', '3651', '365299', '365371', '365564', '365744', '365748', '3659', '365900', '3660', '366078', '3661', '366126', '366142', '3662', '366210', '366214', '366229', '3663', '366340', '3664', '3665', '366542', '366598', '366829', '366949', '366951', '366954', '366960', '366964', '366996', '366998', '367', '3670', '367092', '367100', '367106', '367152', '367218', '367264', '367314', '367832', '367846', '367944', '367950', '368057', '368158', '3720', '3725', '3726', '3727', '378435', '380912', '380993', '381319', '381359', '381373', '381463', '381549', '381990', '382066', '382074', '382639', '383491', '385674', '387609', '388112', '388566', '388585', '389058', '389549', '389692', '390010', '390259', '390874', '390992', '391723', '3975', '399489', '399823', '4005', '4009', '401', '4010', '402381', '404281', '405', '406', '406164', '406169', '4084', '4086', '4087', '4088', '4089', '4090', '4091', '4094', '4097', '414065', '4149', '4150', '4205', '4207', '4208', '4209', '4211', '4212', '4222', '4223', '4286', '429', '4297', '430', '4303', '4306', '432731', '4330', '4335', '433938', '434174', '436240', '440097', '442425', '4487', '4488', '4520', '4601', '4602', '4603', '4605', '4609', '4610', '4613', '4617', '4618', '463', '4654', '4656', '466', '4661', '467', '468', '474', '4760', '4761', '4762', '4772', '4773', '4774', '4775', '4776', '4778', '4779', '4780', '4781', '4782', '4783', '4784', '4790', '4791', '4799', '4800', '4802', '4807', '4808', '4821', '4824', '4825', '4849', '4861', '4862', '4899', '4901', '4904', '4929', '494344', '497984', '497985', '497986', '497987', '497988', '498194', '498407', '49854', '498545', '498575', '498607', '498633', '498864', '498918', '498945', '498952', '4990', '499016', '499090', '499146', '499171', '499361', '499362', '499380', '499497', '499510', '499593', '499874', '499900', '499951', '499952', '499964', '500023', '500037', '500048', '500110', '500126', '500129', '500131', '500137', '500156', '500235', '500239', '500538', '500558', '500574', '500818', '500950', '500964', '500981', '500982', '501099', '501145', '5013', '5015', '501506', '5017', '502759', '502886', '502946', '50496', '50524', '50545', '50552', '50554', '50659', '50662', '50674', '5075', '5076', '5077', '5078', '5079', '50794', '50796', '5080', '50804', '5081', '5083', '50862', '5087', '5089', '5090', '50907', '50913', '50914', '50943', '50945', '51043', '51085', '51157', '51176', '51193', '51222', '51230', '51270', '51274', '51341', '51351', '51385', '51450', '51513', '51533', '51621', '5178', '51804', '51886', '5241', '52615', '52679', '52712', '5307', '5308', '5309', '5316', '5324', '5325', '5326', '53314', '53335', '53404', '53415', '53417', '53626', '5396', '53970', '54006', '54123', '54131', '54139', '541457', '54254', '54264', '54267', '54276', '54278', '54284', '54345', '54352', '54367', '54422', '54446', '5449', '5451', '5452', '5453', '5454', '545474', '5455', '5456', '5457', '5458', '54585', '5459', '5460', '54601', '54626', '5463', '5465', '5467', '5468', '54711', '54713', '54738', '54796', '54897', '54937', '550619', '55079', '55274', '55502', '55509', '55553', '55565', '55578', '55634', '55657', '55806', '55810', '55840', '55893', '55897', '55900', '55922', '55927', '56033', '56198', '56218', '56259', '5626', '5629', '56380', '56449', '56458', '56461', '56484', '56490', '56501', '56676', '56711', '56722', '56734', '56751', '56787', '56790', '56805', '56809', '56938', '56956', '56980', '56987', '56995', '57057', '571', '57167', '57215', '57233', '57246', '57343', '57432', '57473', '57592', '57593', '57594', '57615', '57616', '57621', '57623', '57659', '57693', '57765', '57801', '57822', '579', '5813', '5814', '58158', '58180', '58198', '58208', '58495', '58500', '58805', '58820', '58842', '58850', '58851', '58852', '58853', '58921', '58954', '59016', '59057', '59058', '59112', '5914', '5915', '5916', '59269', '59328', '59335', '59336', '59348', '5966', '5970', '5971', '5978', '5989', '5990', '5991', '5992', '5993', '60329', '60349', '60351', '60394', '604', '60446', '60447', '6045', '60462', '60468', '60529', '60563', '60611', '60661', '60685', '6095', '6096', '6097', '619575', '619665', '6239', '6256', '6257', '6258', '6297', '6299', '6304', '630579', '63876', '639', '63973', '63974', '63976', '63977', '63978', '64067', '641339', '64186', '64188', '64288', '64290', '64321', '64332', '64344', '64345', '643609', '64376', '64379', '64406', '64412', '644168', '64441', '64444', '64530', '64572', '646', '64618', '64619', '64628', '64637', '64641', '64651', '6473', '6474', '64764', '64826', '64843', '64864', '64919', '6492', '6493', '6495', '6496', '6498', '65035', '65050', '65100', '65161', '65193', '65199', '653404', '653427', '654496', '6591', '6596', '65986', '66019', '66136', '6615', '66277', '664783', '664799', '6651', '6656', '6657', '6658', '6659', '6660', '6662', '6663', '6664', '66642', '6665', '6666', '6667', '6668', '6670', '6671', '668', '66830', '66867', '6688', '6689', '66953', '67143', '67150', '6720', '6721', '6722', '67255', '6736', '6772', '6773', '6774', '6775', '6776', '6777', '67778', '6778', '679028', '679571', '679701', '679712', '679869', '680117', '680201', '680427', '680620', '680712', '680751', '681092', '681359', '683504', '684085', '685072', '685102', '685360', '685732', '686117', '6862', '687', '68750', '688', '68837', '68842', '6886', '688699', '688822', '688999', '689030', '68910', '689210', '689695', '689788', '6899', '689918', '68992', '689988', '690430', '690820', '6909', '6910', '6911', '6913', '691398', '691556', '691842', '69228', '6925', '69257', '6926', '6927', '6928', '6929', '6932', '6934', '6935', '6936', '6938', '6939', '6940', '6942', '6943', '6945', '69743', '69890', '7003', '7004', '7008', '70127', '7019', '7020', '7021', '7022', '7023', '7024', '7025', '7026', '7027', '7029', '7030', '7041', '7050', '70508', '7067', '70673', '7068', '7071', '70779', '7080', '70998', '7101', '71041', '71137', '71371', '71375', '7157', '71591', '7161', '71702', '71722', '7181', '7182', '71838', '71950', '72057', '72154', '7227', '72465', '72567', '72739', '727857', '727940', '72843', '7287', '7288', '728957', '7291', '7294', '73181', '73191', '73389', '7342', '7376', '7391', '7392', '74007', '74120', '74123', '74164', '7421', '74352', '74434', '74451', '745', '74533', '74561', '7490', '7494', '7528', '7539', '7541', '7543', '7544', '7545', '7546', '7547', '75507', '7552', '7553', '7554', '7555', '7556', '75580', '7566', '7567', '7570', '7571', '7572', '75753', '7584', '7587', '75871', '7589', '7592', '7593', '7594', '7596', '7629', '7634', '76365', '7637', '7639', '7643', '7644', '7678', '7690', '7691', '7692', '7693', '7694', '7695', '7697', '7699', '7702', '7704', '7707', '7709', '7710', '7711', '7712', '7716', '7718', '7727', '7728', '77286', '7730', '7732', '7741', '7743', '7746', '7753', '7755', '7761', '7762', '7764', '7767', '7773', '77771', '7799', '78266', '78284', '7849', '78912', '78968', '78972', '78974', '790969', '79116', '79190', '79191', '79192', '79225', '79237', '79240', '79241', '79245', '79255', '79362', '79365', '79401', '7942', '79431', '79618', '79692', '79733', '7975', '79759', '79800', '79923', '79977', '80034', '8013', '8022', '80317', '80320', '80338', '8061', '80709', '80712', '80714', '80720', '80778', '80859', '80902', '8091', '8092', '8110', '81518', '81524', '81566', '81646', '81647', '81703', '81710', '81717', '81736', '81808', '81812', '81813', '81817', '81819', '8187', '81879', '8193', '81931', '8320', '8328', '83383', '83395', '83396', '83439', '83463', '83474', '83482', '83498', '83574', '83586', '83595', '83618', '83619', '83630', '83632', '83635', '83726', '83741', '83807', '83826', '83855', '83879', '83881', '83925', '83990', '83993', '84017', '8403', '84046', '84107', '84108', '84159', '84295', '84382', '84385', '84410', '84449', '84482', '84504', '84524', '84528', '8456', '84574', '84619', '8462', '8463', '84653', '84654', '84662', '84667', '84699', '84838', '84839', '84878', '84891', '84911', '84969', '8521', '8531', '8538', '85416', '85424', '85434', '8545', '85471', '85489', '85497', '85508', '8553', '8570', '860', '8609', '861', '8626', '864', '8726', '8820', '8848', '8856', '8880', '8928', '8929', '8939', '89884', '90316', '90333', '9095', '9096', '90987', '90993', '91752', '9189', '91975', '9208', '9242', '9314', '9355', '93691', '93730', '93837', '93986', '94187', '94188', '9421', '94222', '94234', '9464', '9480', '9489', '9496', '9516', '9519', '9572', '9575', '9580', '9586', '9592', '9603', '9640', '9705', '9745', '9753', '9774', '9839', '988', '9915', '9925', '9935', '99377', '9970', '9971', '9975', '9988', '12151', '12400', '15901', '15902', '15903', '161882', '17131', '19017', '23414', '4092', '672', '9612')"; <ide> static final String MAMMALIAN_TF_QUERY = "SELECT r.accession, s.value FROM " + <ide> "genes AS g, gene_strings AS s, gene_refs AS r WHERE g.id = s.id AND g.id = r.id " +
Java
apache-2.0
87317266f974b70eda84e7a0d06990282ca510ee
0
NitorCreations/willow,NitorCreations/willow,NitorCreations/willow,NitorCreations/willow,NitorCreations/willow
package com.nitorcreations.willow.utils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.attribute.PosixFilePermission; import java.security.InvalidKeyException; import java.security.Key; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Base64; import java.util.HashSet; import java.util.Map.Entry; import java.util.Set; import javax.crypto.Cipher; import javax.crypto.CipherOutputStream; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class Obfuscator { private final String propertyKey; public Obfuscator() throws IOException { String defaultMaster = System.getProperty("user.home") + File.separator + ".omaster" + File.separator + ".data" + File.pathSeparator + "md5"; String masterPwdLocation = System.getProperty("o.datamaster", defaultMaster); File masterFile = new File(masterPwdLocation); if (!masterFile.exists()) { masterFile.getParentFile().mkdirs(); SecureRandom sr = new SecureRandom(); byte[] key = new byte[128]; sr.nextBytes(key); try (OutputStream out = new FileOutputStream(masterFile)) { out.write(("value=" + Base64.getEncoder().encodeToString(key) + "\n").getBytes(Charset.forName("UTF-8"))); out.flush(); } Set<PosixFilePermission> perms = new HashSet<>(); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_READ); Files.setPosixFilePermissions(masterFile.toPath(), perms); } this.propertyKey = getFileMaster(masterFile); } public Obfuscator(File masterFile) throws IOException { this(getFileMaster(masterFile)); } public Obfuscator(String key) { this.propertyKey = key; } public String encrypt(String value) { return encrypt(propertyKey, value); } public String decrypt(String ciphertext) { return decrypt(propertyKey, ciphertext); } public static void main(String[] args) throws NoSuchAlgorithmException, IOException { if (args.length == 0) return; Obfuscator pwdo = new Obfuscator(); if (args[0].equals("-d")) { for (int i = 1; i < args.length; i++) { System.out.println(pwdo.decrypt(args[i])); } } else { for (String next : args) { System.out.println(pwdo.encrypt(next)); } } } public static String encrypt(String skey, String value) { byte[] bkey = getKeyBytes(skey); Key key; Cipher out; CipherOutputStream cOut; ByteArrayOutputStream bOut; key = new SecretKeySpec(bkey, "AES"); try { out = Cipher.getInstance("AES/ECB/PKCS5Padding"); out.init(Cipher.ENCRYPT_MODE, key); byte[] input = value.getBytes(Charset.forName("UTF-8")); bOut = new ByteArrayOutputStream(); cOut = new CipherOutputStream(bOut, out); cOut.write(input, 0, input.length); cOut.flush(); cOut.close(); return Base64.getEncoder().encodeToString(bOut.toByteArray()); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException e) { e.printStackTrace(); return null; } } public static String decrypt(String skey, String encrypted) { byte[] bkey = getKeyBytes(skey); Key key; Cipher in; CipherOutputStream cIn; ByteArrayOutputStream bIn; key = new SecretKeySpec(bkey, "AES"); try { in = Cipher.getInstance("AES/ECB/PKCS5Padding"); in.init(Cipher.DECRYPT_MODE, key); byte[] input = Base64.getDecoder().decode(encrypted); bIn = new ByteArrayOutputStream(); cIn = new CipherOutputStream(bIn, in); cIn.write(input); cIn.close(); return new String(bIn.toByteArray(), Charset.forName("UTF-8")); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException e) { e.printStackTrace(); return null; } } private static byte[] getKeyBytes(String key) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); byte[] raw = key.getBytes(Charset.forName("UTF-8")); md.update(raw); return md.digest(); } catch (NoSuchAlgorithmException e) { return null; } } public static String getFileMaster(File masterFile) throws IOException { Set<PosixFilePermission> perms = Files.getPosixFilePermissions(masterFile.toPath()); if (perms.contains(PosixFilePermission.GROUP_EXECUTE) || perms.contains(PosixFilePermission.GROUP_WRITE) || perms.contains(PosixFilePermission.GROUP_READ) || perms.contains(PosixFilePermission.OTHERS_EXECUTE) || perms.contains(PosixFilePermission.OTHERS_READ) || perms.contains(PosixFilePermission.OTHERS_WRITE)) { throw new IOException("Master file permissions too wide"); } MergeableProperties p = new MergeableProperties(); try { p.load(new FileInputStream(masterFile)); } catch (IOException e) {} MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) {} if (p.isEmpty()) { byte[] content = Files.readAllBytes(masterFile.toPath()); md.update(content); } else { for (Entry<String, String> next : p.backingEntrySet()) { md.update(next.getKey().getBytes(Charset.forName("UTF-8"))); md.update(next.getValue().getBytes(Charset.forName("UTF-8"))); } } return Base64.getEncoder().encodeToString(md.digest()); } }
willow-utils/src/main/java/com/nitorcreations/willow/utils/Obfuscator.java
package com.nitorcreations.willow.utils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermission; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Permissions; import java.security.SecureRandom; import java.security.Security; import java.util.Base64; import java.util.HashSet; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import javax.crypto.Cipher; import javax.crypto.CipherOutputStream; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class Obfuscator { private final String propertyKey; public Obfuscator() throws IOException { String defaultMaster = System.getProperty("user.home") + File.separator + ".omaster" + File.separator + ".data" + File.pathSeparator + "md5"; String masterPwdLocation = System.getProperty("o.datamaster", defaultMaster); File masterFile = new File(masterPwdLocation); if (!masterFile.exists()) { masterFile.getParentFile().mkdirs(); SecureRandom sr = new SecureRandom(); byte[] key = new byte[128]; sr.nextBytes(key); try (OutputStream out = new FileOutputStream(masterFile)) { out.write(("value=" + Base64.getEncoder().encodeToString(key) + "\n").getBytes(Charset.forName("UTF-8"))); out.flush(); } Set<PosixFilePermission> perms = new HashSet<>(); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_READ); Files.setPosixFilePermissions(masterFile.toPath(), perms); } Set<PosixFilePermission> perms = Files.getPosixFilePermissions(masterFile.toPath()); if (perms.contains(PosixFilePermission.GROUP_EXECUTE) || perms.contains(PosixFilePermission.GROUP_WRITE) || perms.contains(PosixFilePermission.GROUP_READ) || perms.contains(PosixFilePermission.OTHERS_EXECUTE) || perms.contains(PosixFilePermission.OTHERS_READ) || perms.contains(PosixFilePermission.OTHERS_WRITE)) { throw new IOException("Master file permissions too wide"); } MergeableProperties p = new MergeableProperties(); try { p.load(new FileInputStream(masterFile)); } catch (IOException e) {} MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) {} if (p.isEmpty()) { byte[] content = Files.readAllBytes(masterFile.toPath()); md.update(content); } else { for (Entry<String, String> next : p.backingEntrySet()) { md.update(next.getKey().getBytes(Charset.forName("UTF-8"))); md.update(next.getValue().getBytes(Charset.forName("UTF-8"))); } } String key = Base64.getEncoder().encodeToString(md.digest()); this.propertyKey = key; } public Obfuscator(String key) { this.propertyKey = key; } public String encrypt(String value) { return encrypt(propertyKey, value); } public String decrypt(String ciphertext) { return decrypt(propertyKey, ciphertext); } public static void main(String[] args) throws NoSuchAlgorithmException, IOException { if (args.length == 0) return; Obfuscator pwdo = new Obfuscator(); if (args[0].equals("-d")) { for (int i = 1; i < args.length; i++) { System.out.println(pwdo.decrypt(args[i])); } } else { for (String next : args) { System.out.println(pwdo.encrypt(next)); } } } public static String encrypt(String skey, String value) { byte[] bkey = getKeyBytes(skey); Key key; Cipher out; CipherOutputStream cOut; ByteArrayOutputStream bOut; key = new SecretKeySpec(bkey, "AES"); try { out = Cipher.getInstance("AES/ECB/PKCS5Padding"); out.init(Cipher.ENCRYPT_MODE, key); byte[] input = value.getBytes(Charset.forName("UTF-8")); bOut = new ByteArrayOutputStream(); cOut = new CipherOutputStream(bOut, out); cOut.write(input, 0, input.length); cOut.flush(); cOut.close(); return Base64.getEncoder().encodeToString(bOut.toByteArray()); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException e) { e.printStackTrace(); return null; } } public static String decrypt(String skey, String encrypted) { byte[] bkey = getKeyBytes(skey); Key key; Cipher in; CipherOutputStream cIn; ByteArrayOutputStream bIn; key = new SecretKeySpec(bkey, "AES"); try { in = Cipher.getInstance("AES/ECB/PKCS5Padding"); in.init(Cipher.DECRYPT_MODE, key); byte[] input = Base64.getDecoder().decode(encrypted); bIn = new ByteArrayOutputStream(); cIn = new CipherOutputStream(bIn, in); cIn.write(input); cIn.close(); return new String(bIn.toByteArray(), Charset.forName("UTF-8")); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException e) { e.printStackTrace(); return null; } } private static byte[] getKeyBytes(String key) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); byte[] raw = key.getBytes(Charset.forName("UTF-8")); md.update(raw); return md.digest(); } catch (NoSuchAlgorithmException e) { return null; } } }
Moved master password reading into an utility function
willow-utils/src/main/java/com/nitorcreations/willow/utils/Obfuscator.java
Moved master password reading into an utility function
<ide><path>illow-utils/src/main/java/com/nitorcreations/willow/utils/Obfuscator.java <ide> import java.io.OutputStream; <ide> import java.nio.charset.Charset; <ide> import java.nio.file.Files; <del>import java.nio.file.Path; <del>import java.nio.file.Paths; <ide> import java.nio.file.attribute.PosixFilePermission; <del>import java.security.InvalidAlgorithmParameterException; <ide> import java.security.InvalidKeyException; <ide> import java.security.Key; <ide> import java.security.MessageDigest; <ide> import java.security.NoSuchAlgorithmException; <del>import java.security.NoSuchProviderException; <del>import java.security.Permissions; <ide> import java.security.SecureRandom; <del>import java.security.Security; <ide> import java.util.Base64; <ide> import java.util.HashSet; <ide> import java.util.Map.Entry; <del>import java.util.Properties; <ide> import java.util.Set; <ide> <ide> import javax.crypto.Cipher; <ide> perms.add(PosixFilePermission.OWNER_READ); <ide> Files.setPosixFilePermissions(masterFile.toPath(), perms); <ide> } <del> Set<PosixFilePermission> perms = Files.getPosixFilePermissions(masterFile.toPath()); <del> if (perms.contains(PosixFilePermission.GROUP_EXECUTE) || <del> perms.contains(PosixFilePermission.GROUP_WRITE) || <del> perms.contains(PosixFilePermission.GROUP_READ) || <del> perms.contains(PosixFilePermission.OTHERS_EXECUTE) || <del> perms.contains(PosixFilePermission.OTHERS_READ) || <del> perms.contains(PosixFilePermission.OTHERS_WRITE)) { <del> throw new IOException("Master file permissions too wide"); <del> } <del> MergeableProperties p = new MergeableProperties(); <del> try { <del> p.load(new FileInputStream(masterFile)); <del> } catch (IOException e) {} <del> MessageDigest md = null; <del> try { <del> md = MessageDigest.getInstance("MD5"); <del> } catch (NoSuchAlgorithmException e) {} <del> if (p.isEmpty()) { <del> byte[] content = Files.readAllBytes(masterFile.toPath()); <del> md.update(content); <del> } else { <del> for (Entry<String, String> next : p.backingEntrySet()) { <del> md.update(next.getKey().getBytes(Charset.forName("UTF-8"))); <del> md.update(next.getValue().getBytes(Charset.forName("UTF-8"))); <del> } <del> } <del> String key = Base64.getEncoder().encodeToString(md.digest()); <del> this.propertyKey = key; <add> this.propertyKey = getFileMaster(masterFile); <add> } <add> public Obfuscator(File masterFile) throws IOException { <add> this(getFileMaster(masterFile)); <ide> } <ide> public Obfuscator(String key) { <ide> this.propertyKey = key; <ide> return null; <ide> } <ide> } <add> public static String getFileMaster(File masterFile) throws IOException { <add> Set<PosixFilePermission> perms = Files.getPosixFilePermissions(masterFile.toPath()); <add> if (perms.contains(PosixFilePermission.GROUP_EXECUTE) || <add> perms.contains(PosixFilePermission.GROUP_WRITE) || <add> perms.contains(PosixFilePermission.GROUP_READ) || <add> perms.contains(PosixFilePermission.OTHERS_EXECUTE) || <add> perms.contains(PosixFilePermission.OTHERS_READ) || <add> perms.contains(PosixFilePermission.OTHERS_WRITE)) { <add> throw new IOException("Master file permissions too wide"); <add> } <add> MergeableProperties p = new MergeableProperties(); <add> try { <add> p.load(new FileInputStream(masterFile)); <add> } catch (IOException e) {} <add> MessageDigest md = null; <add> try { <add> md = MessageDigest.getInstance("MD5"); <add> } catch (NoSuchAlgorithmException e) {} <add> if (p.isEmpty()) { <add> byte[] content = Files.readAllBytes(masterFile.toPath()); <add> md.update(content); <add> } else { <add> for (Entry<String, String> next : p.backingEntrySet()) { <add> md.update(next.getKey().getBytes(Charset.forName("UTF-8"))); <add> md.update(next.getValue().getBytes(Charset.forName("UTF-8"))); <add> } <add> } <add> return Base64.getEncoder().encodeToString(md.digest()); <add> } <ide> }
Java
agpl-3.0
c5e4c54b322ef991ad8964a59336b248d12d3321
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
6f195028-2e62-11e5-9284-b827eb9e62be
hello.java
6f112506-2e62-11e5-9284-b827eb9e62be
6f195028-2e62-11e5-9284-b827eb9e62be
hello.java
6f195028-2e62-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>6f112506-2e62-11e5-9284-b827eb9e62be <add>6f195028-2e62-11e5-9284-b827eb9e62be
Java
apache-2.0
2839fd1ae00f8bbd52a4b992d9a540eaabb84a70
0
mifeet/LD-FusionTool,mifeet/LD-FusionTool
package cz.cuni.mff.odcleanstore.fusiontool.loaders; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import cz.cuni.mff.odcleanstore.conflictresolution.ResolvedStatement; import cz.cuni.mff.odcleanstore.conflictresolution.impl.ResolvedStatementImpl; import cz.cuni.mff.odcleanstore.conflictresolution.impl.util.SpogComparator; import cz.cuni.mff.odcleanstore.fusiontool.config.ConfigConstants; import cz.cuni.mff.odcleanstore.fusiontool.config.ConfigParameters; import cz.cuni.mff.odcleanstore.fusiontool.config.DataSourceConfig; import cz.cuni.mff.odcleanstore.fusiontool.config.DataSourceConfigImpl; import cz.cuni.mff.odcleanstore.fusiontool.config.EnumDataSourceType; import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.ResourceDescription; import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.UriMapping; import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.urimapping.UriMappingIterable; import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.urimapping.UriMappingIterableImpl; import cz.cuni.mff.odcleanstore.fusiontool.exceptions.ODCSFusionToolException; import cz.cuni.mff.odcleanstore.fusiontool.io.EnumSerializationFormat; import cz.cuni.mff.odcleanstore.fusiontool.loaders.data.AllTriplesFileLoader; import cz.cuni.mff.odcleanstore.fusiontool.loaders.data.AllTriplesLoader; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.openrdf.model.Model; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.impl.TreeModel; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFWriter; import org.openrdf.rio.Rio; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; import static cz.cuni.mff.odcleanstore.fusiontool.testutil.ContextAwareStatementIsEqual.contextAwareStatementIsEqual; import static cz.cuni.mff.odcleanstore.fusiontool.testutil.ODCSFTTestUtils.createHttpStatement; import static cz.cuni.mff.odcleanstore.fusiontool.testutil.ODCSFTTestUtils.createHttpUri; import static cz.cuni.mff.odcleanstore.fusiontool.testutil.ODCSFTTestUtils.createStatement; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; public class ExternalSortingInputLoaderTest { // TODO private static final URI resourceDescriptionProperty = ConfigConstants.RESOURCE_DESCRIPTION_URIS.iterator().next(); private static final ValueFactoryImpl VF = ValueFactoryImpl.getInstance(); public static final SpogComparator SPOG_COMPARATOR = new SpogComparator(); @Rule public TemporaryFolder testDir = new TemporaryFolder(); private AtomicInteger testFileCounter = new AtomicInteger(0); private UriMappingIterable uriMapping; /** A general case of test data */ private Collection<Statement> testInput1 = ImmutableList.of( // triples that map to the same statement createHttpStatement("sa", "pa", "oa", "g1"), createHttpStatement("sb", "pb", "ob", "g1"), // additional triple for the mapped resource createHttpStatement("sa", "p1", "oa", "ga"), // two identical triples createHttpStatement("s1", "p1", "o1", "g1"), createHttpStatement("s1", "p1", "o1", "g1"), // a conflict cluster with three values createHttpStatement("s2", "p2", "o1", "g1"), createHttpStatement("s2", "p2", "o2", "g2"), createHttpStatement("s2", "p2", "o3", "g3"), // resource description with two conflict clusters createHttpStatement("s3", "p1", "o1", "g4"), createHttpStatement("s3", "p2", "o2", "g5"), createHttpStatement("s3", "p2", "o3", "g5"), // resource description with mapped property and object and no named graph createHttpStatement("s4", "pa", "o1"), createHttpStatement("s4", "p1", "oa") ); /** Map of canonical subject -> canonical predicate -> set of statements in conflict cluster for {@link #testInput1} */ private Map<Resource, Map<URI, Set<Statement>>> conflictClustersMap1; private final Collection<Statement> testInput2 = ImmutableList.of( createHttpStatement("s1", "p1", "o1", "g1"), createHttpStatement("x", "y", "z", "g1") ); // FIXME: add corresponding integration test private final Collection<Statement> testInput3 = ImmutableList.of( // Resource description with two dependent resources and one normal triple createHttpStatement("s1", "p1", "o1"), createStatement(createHttpUri("s1"), resourceDescriptionProperty, createHttpUri("dependent1")), createStatement(createHttpUri("s1"), resourceDescriptionProperty, createHttpUri("dependent3")), // Resource description sharing a dependent resource with s1 createStatement(createHttpUri("s3"), resourceDescriptionProperty, createHttpUri("dependent3")), // the dependent resources createHttpStatement("dependent1", "p2", "o2"), createHttpStatement("dependent1", "p3", "o3"), createHttpStatement("dependent3", "p4", "o4"), // extra triples createHttpStatement("s2", "p5", "o5"), createHttpStatement("dependent2-not-really", "p6", "o7") ); /** Map of canonical resource -> set of expected statments in the respective resource description for {@link #testInput3} */ private Map<Resource, TreeSet<Statement>> conflictClusters3; @Before public void setUp() throws Exception { // init URI mapping // map sa, sb -> sx; pa, pb -> px; oa, ob -> ox; ga, gb -> gx UriMappingIterableImpl uriMappingImpl = new UriMappingIterableImpl(ImmutableSet.of( createHttpUri("sx").toString(), createHttpUri("px").toString(), createHttpUri("ox").toString(), createHttpUri("gx").toString())); uriMappingImpl.addLink(createHttpUri("sa").toString(), createHttpUri("sx").toString()); uriMappingImpl.addLink(createHttpUri("sb").toString(), createHttpUri("sx").toString()); uriMappingImpl.addLink(createHttpUri("pa").toString(), createHttpUri("px").toString()); uriMappingImpl.addLink(createHttpUri("pb").toString(), createHttpUri("px").toString()); uriMappingImpl.addLink(createHttpUri("oa").toString(), createHttpUri("ox").toString()); uriMappingImpl.addLink(createHttpUri("ob").toString(), createHttpUri("ox").toString()); uriMappingImpl.addLink(createHttpUri("ga").toString(), createHttpUri("gx").toString()); uriMappingImpl.addLink(createHttpUri("gb").toString(), createHttpUri("gx").toString()); this.uriMapping = uriMappingImpl; // init map of conflict clusters 1 conflictClustersMap1 = createConflictClusterMap(testInput1, uriMapping); // init map of conflict cluster 3 conflictClusters3 = new HashMap<>(); for (Statement statement : testInput3) { Resource canonicalSubject = uriMapping.mapResource(statement.getSubject()); if (!conflictClusters3.containsKey(canonicalSubject)) { conflictClusters3.put(canonicalSubject, new TreeSet<>(SPOG_COMPARATOR)); } conflictClusters3.get(canonicalSubject).add(statement); } Model model3 = new TreeModel(testInput3); for (Statement statement : model3.filter(null, resourceDescriptionProperty, null)) { TreeSet<Statement> conflictCluster = conflictClusters3.get(uriMapping.mapResource(statement.getSubject())); conflictCluster.addAll(model3.filter((Resource) statement.getObject(), null, null)); // we expect no mapping is required } } @Test public void iteratesOverAllStatementsWithoutAppliedUriMapping() throws Exception { // Act SortedSet<Statement> result = new TreeSet<>(SPOG_COMPARATOR); ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput1, false); try { collectResult(inputLoader, result); } finally { inputLoader.close(); } // Assert SortedSet<Statement> expectedStatementsSet = new TreeSet<>(SPOG_COMPARATOR); expectedStatementsSet.addAll(testInput1); assertThat(result.size(), equalTo(expectedStatementsSet.size())); Statement[] expectedStatements = expectedStatementsSet.toArray(new Statement[0]); Statement[] actualStatements = result.toArray(new Statement[0]); for (int i = 0; i < expectedStatements.length; i++) { // compare including named graphs assertThat(actualStatements[i], contextAwareStatementIsEqual(expectedStatements[i])); } } @Test public void nextQuadsReturnsCompleteConflictClusters() throws Exception { // Act List<Collection<Statement>> statementBlocks = new ArrayList<>(); ExternalSortingInputLoader inputLoader = null; try { inputLoader = createExternalSortingInputLoader(testInput1, false); inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { statementBlocks.add(inputLoader.next().getDescribingStatements()); } } finally { inputLoader.close(); } // Assert for (Collection<Statement> block : statementBlocks) { // for each conflict cluster in a block returned by next(), // all quads belonging to this conflict cluster must be present. for (Statement statement : block) { Set<Statement> conflictCluster = conflictClustersMap1 .get(uriMapping.mapResource(statement.getSubject())) .get(uriMapping.mapResource(statement.getPredicate())); boolean blockContainsEntireConflictCluster = block.containsAll(conflictCluster); if (!blockContainsEntireConflictCluster) { fail(String.format("Block %s doesn't contain the entire conflict cluster %s", block, conflictCluster)); } } } } @Test public void nextQuadsReturnsDescriptionOfSingleResource() throws Exception { // Act List<Collection<Statement>> statementBlocks = new ArrayList<>(); ExternalSortingInputLoader inputLoader = null; try { inputLoader = createExternalSortingInputLoader(testInput1, false); inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { statementBlocks.add(inputLoader.next().getDescribingStatements()); } } finally { inputLoader.close(); } // Assert for (Collection<Statement> block : statementBlocks) { assertFalse(block.isEmpty()); Resource firstCanonicalSubject = uriMapping.mapResource(block.iterator().next().getSubject()); for (Statement statement : block) { assertThat(uriMapping.mapResource(statement.getSubject()), equalTo(firstCanonicalSubject)); } } } @Test public void resourceIsDescribedInSingleNextQuadsResult() throws Exception { // Act List<Collection<Statement>> statementBlocks = new ArrayList<>(); ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput1, false); try { inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { statementBlocks.add(inputLoader.next().getDescribingStatements()); } } finally { inputLoader.close(); } // Assert Set<Resource> canonicalSubjectsFromPreviousBlocks = new HashSet<>(); for (Collection<Statement> block : statementBlocks) { Set<Resource> subjectsFromCurrentBlock = new HashSet<>(); for (Statement statement : block) { Resource canonicalSubject = uriMapping.mapResource(statement.getSubject()); assertFalse(canonicalSubjectsFromPreviousBlocks.contains(canonicalSubject)); subjectsFromCurrentBlock.add(canonicalSubject); } canonicalSubjectsFromPreviousBlocks.addAll(subjectsFromCurrentBlock); } } @Test public void worksOnEmptyStatements() throws Exception { // Act & assert ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(Collections.<Statement>emptySet(), false); try { inputLoader.initialize(uriMapping); assertFalse(inputLoader.hasNext()); } finally { inputLoader.close(); } } @Test public void clearsTemporaryFilesWhenClosed() throws Exception { // Act ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput1, false); try { inputLoader.initialize(uriMapping); if (inputLoader.hasNext()) { // call only once inputLoader.next(); } } finally { inputLoader.close(); } // Assert File[] filesInWorkingDir = testDir.getRoot().listFiles(); assertThat(filesInWorkingDir.length, equalTo(1)); // only the input file should remain } @Test public void clearsTemporaryFilesOnError() throws Exception { // Act ExternalSortingInputLoader inputLoader = null; Exception caughtException = null; try { DataSourceConfig dataSource = createFileDataSource(testInput1); File inputFile = new File(dataSource.getParams().get(ConfigParameters.DATA_SOURCE_FILE_PATH)); FileWriter inputFileWriter = new FileWriter(inputFile, true); inputFileWriter.append("xyz;"); inputFileWriter.close(); Set<AllTriplesLoader> dataSources = Collections.singleton( (AllTriplesLoader) new AllTriplesFileLoader(dataSource, ConfigConstants.DEFAULT_FILE_PARSER_CONFIG)); inputLoader = new ExternalSortingInputLoader(dataSources, testDir.getRoot(), ConfigConstants.DEFAULT_FILE_PARSER_CONFIG, Long.MAX_VALUE, false); inputLoader.initialize(uriMapping); if (inputLoader.hasNext()) { // call only once inputLoader.next(); } } catch (Exception e) { caughtException = e; } finally { inputLoader.close(); } // Assert assertThat(caughtException, instanceOf(ODCSFusionToolException.class)); File[] filesInWorkingDir = testDir.getRoot().listFiles(); assertThat(filesInWorkingDir.length, equalTo(1)); // only the input file should remain } @Test public void updateWithResolvedStatementsDoesNotThrowException() throws Exception { // Act ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput1, false); try { inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { Collection<Statement> statements = inputLoader.next().getDescribingStatements(); Statement firstStatement = statements.iterator().next(); ResolvedStatement resolvedStatement = new ResolvedStatementImpl(firstStatement, 0.5, Collections.singleton(firstStatement.getContext())); inputLoader.updateWithResolvedStatements(Collections.singleton(resolvedStatement)); } } finally { inputLoader.close(); } } @Test public void readsMultipleInputFiles() throws Exception { // Act SortedSet<Statement> result = new TreeSet<>(SPOG_COMPARATOR); ExternalSortingInputLoader inputLoader = new ExternalSortingInputLoader( createFileAllTriplesLoader(testInput1, testInput2), testDir.getRoot(), ConfigConstants.DEFAULT_FILE_PARSER_CONFIG, Long.MAX_VALUE, false); try { collectResult(inputLoader, result); } finally { inputLoader.close(); } // Assert SortedSet<Statement> expectedStatementsSet = new TreeSet<>(SPOG_COMPARATOR); expectedStatementsSet.addAll(testInput1); expectedStatementsSet.addAll(testInput2); assertThat(result.size(), equalTo(expectedStatementsSet.size())); Statement[] expectedStatements = expectedStatementsSet.toArray(new Statement[0]); Statement[] actualStatements = result.toArray(new Statement[0]); for (int i = 0; i < expectedStatements.length; i++) { // compare including named graphs assertThat(actualStatements[i], contextAwareStatementIsEqual(expectedStatements[i])); } } @Test public void filtersUnmappedSubjectsWhenOutputMappedSubjectsOnlyIsTrue() throws Exception { // Arrange ArrayList<Statement> statements = new ArrayList<>(); statements.add(createHttpStatement("s1", "p1", "o1", "g1")); statements.add(createHttpStatement("s3", "p1", "o1", "g1")); statements.add(createHttpStatement("s2", "p1", "o1", "g1")); statements.add(createHttpStatement("s4", "p1", "o1", "g1")); UriMappingIterableImpl uriMapping = new UriMappingIterableImpl(ImmutableSet.of( createHttpUri("sx").toString(), createHttpUri("s2").toString())); uriMapping.addLink(createHttpUri("s1").toString(), createHttpUri("sx").toString()); uriMapping.addLink(createHttpUri("s2").toString(), createHttpUri("sy").toString()); // Act SortedSet<Statement> result = new TreeSet<>(SPOG_COMPARATOR); ExternalSortingInputLoader inputLoader = null; try { inputLoader = createExternalSortingInputLoader(statements, true); inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { result.addAll(inputLoader.next().getDescribingStatements()); } } finally { inputLoader.close(); } // Assert SortedSet<Statement> expectedStatementsSet = new TreeSet<>(SPOG_COMPARATOR); expectedStatementsSet.add(createHttpStatement("s1", "p1", "o1", "g1")); expectedStatementsSet.add(createHttpStatement("s2", "p1", "o1", "g1")); assertThat(result.size(), equalTo(expectedStatementsSet.size())); Statement[] expectedStatements = expectedStatementsSet.toArray(new Statement[0]); Statement[] actualStatements = result.toArray(new Statement[0]); for (int i = 0; i < expectedStatements.length; i++) { assertThat(actualStatements[i], contextAwareStatementIsEqual(expectedStatements[i])); } } @Test public void iteratesOverAllStatementsWithDependentResources() throws Exception { // Act SortedSet<Statement> result = new TreeSet<>(SPOG_COMPARATOR); ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput3, false); try { collectResult(inputLoader, result); } finally { inputLoader.close(); } // Assert SortedSet<Statement> expectedStatementsSet = new TreeSet<>(SPOG_COMPARATOR); expectedStatementsSet.addAll(testInput3); assertThat(result.size(), equalTo(expectedStatementsSet.size())); Statement[] expectedStatements = expectedStatementsSet.toArray(new Statement[0]); Statement[] actualStatements = result.toArray(new Statement[0]); for (int i = 0; i < expectedStatements.length; i++) { // compare including named graphs assertThat(actualStatements[i], contextAwareStatementIsEqual(expectedStatements[i])); } } @Test public void includesCorrectDependentResourcesInResourceDescriptions() throws Exception { // Arrange Map<Resource, TreeSet<Statement>> result; ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput3, false); // Act try { result = collectResourceDescriptions(inputLoader); } finally { inputLoader.close(); } // Assert assertThat(result.size(), is(conflictClusters3.size())); for (Map.Entry<Resource, TreeSet<Statement>> entry : conflictClusters3.entrySet()) { Statement[] expectedStatements = entry.getValue().toArray(new Statement[0]); Statement[] actualStatements = result.get(entry.getKey()).toArray(new Statement[0]); String errorMessage = "Statements for resource " + entry.getKey() + " do not match"; assertThat(errorMessage, actualStatements.length, is(expectedStatements.length)); for (int i = 0; i < expectedStatements.length; i++) { assertThat(errorMessage, actualStatements[i], contextAwareStatementIsEqual(expectedStatements[i])); } } } @Test public void handlesLiteralsAsValuesOfDescriptionProperties() throws Exception { // Arrange URI resource = createHttpUri("s1"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("s1", "p1", "o1"), createStatement(resource, resourceDescriptionProperty, createHttpUri("dependent1")), VF.createStatement(resource, resourceDescriptionProperty, VF.createLiteral("a")), createHttpStatement("dependent1", "p2", "o2")); // Act ResourceDescription result = null; ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput, false); try { inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { ResourceDescription resourceDescription = inputLoader.next(); if (resourceDescription.getResource().equals(resource)) { result = resourceDescription; } } } finally { inputLoader.close(); } // Assert assertThat(result, notNullValue()); System.out.println(result.getDescribingStatements()); assertThat(result.getDescribingStatements().size(), is(testInput.size())); } @Test public void includesCorrectDependentResourcesWhenDescriptionPropertyIsMapped() throws Exception { // Arrange URI mappedDescriptionProperty = createHttpUri("mappedDescriptionProperty"); URI resource = createHttpUri("s1"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("s1", "p1", "o1"), createStatement(resource, mappedDescriptionProperty, createHttpUri("dependent1")), createHttpStatement("dependent1", "p2", "o2")); UriMappingIterableImpl propertyUriMapping = new UriMappingIterableImpl(ImmutableSet.of(resourceDescriptionProperty.stringValue())); propertyUriMapping.addLink(mappedDescriptionProperty, resourceDescriptionProperty); // Act ResourceDescription result = null; ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput, false); try { inputLoader.initialize(propertyUriMapping); while (inputLoader.hasNext()) { ResourceDescription resourceDescription = inputLoader.next(); if (resourceDescription.getResource().equals(resource)) { result = resourceDescription; } } } finally { inputLoader.close(); } // Assert assertThat(result, notNullValue()); System.out.println(result.getDescribingStatements()); assertThat(result.getDescribingStatements().size(), is(testInput.size())); } @Ignore @Test public void mergesFilesTogetherWhenOneUriIsPrefixOfAnother() throws Exception { // Arrange ImmutableList<Statement> testInput = ImmutableList.of( createHttpStatement("prefix/dependent", "p", "o"), createHttpStatement("prefix", "a", "o"), createStatement(createHttpUri("prefix"), resourceDescriptionProperty, createHttpUri("prefix/dependent"))); ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput, false); Map<Resource, Collection<Statement>> expectedResult = new HashMap<>(); expectedResult.put(createHttpUri("prefix/dependent"), ImmutableList.of(createHttpStatement("prefix/dependent", "p", "o", null))); expectedResult.put(createHttpUri("prefix"), ImmutableList.of( createHttpStatement("prefix/dependent", "p", "o"), createHttpStatement("prefix", "a", "o"), VF.createStatement(createHttpUri("prefix"), resourceDescriptionProperty, createHttpUri("prefix/dependent")))); Map<Resource, TreeSet<Statement>> result; // Act try { result = collectResourceDescriptions(inputLoader); } finally { inputLoader.close(); } // Assert assertThat(result.size(), is(expectedResult.size())); for (Map.Entry<Resource, Collection<Statement>> entry : expectedResult.entrySet()) { Matcher<Statement>[] expectedStatements = toContextAwareEqualMatchers(entry.getValue()); Collection<Statement> actualStatements = result.get(entry.getKey()); String errorMessage = "Statements for resource " + entry.getKey() + " do not match"; assertThat(errorMessage, actualStatements, Matchers.containsInAnyOrder(expectedStatements)); } } private Matcher<Statement>[] toContextAwareEqualMatchers(Collection<Statement> value) { Matcher<Statement>[] result = new Matcher[value.size()]; int i = 0; for (Statement statement : value) { result[i++] = contextAwareStatementIsEqual(statement); } return result; } private Map<Resource, TreeSet<Statement>> collectResourceDescriptions(ExternalSortingInputLoader inputLoader) throws ODCSFusionToolException { Map<Resource, TreeSet<Statement>> result = new HashMap<>(); inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { ResourceDescription resourceDescription = inputLoader.next(); Collection<Statement> cluster = resourceDescription.getDescribingStatements(); TreeSet<Statement> statements = new TreeSet<>(SPOG_COMPARATOR); statements.addAll(cluster); result.put(resourceDescription.getResource(), statements); } return result; } private ExternalSortingInputLoader createExternalSortingInputLoader(Collection<Statement> testInput, boolean outputMappedSubjectsOnly) throws IOException, RDFHandlerException { return new ExternalSortingInputLoader( createFileAllTriplesLoader(testInput), testDir.getRoot(), ConfigConstants.DEFAULT_FILE_PARSER_CONFIG, Long.MAX_VALUE, outputMappedSubjectsOnly); } private Collection<AllTriplesLoader> createFileAllTriplesLoader(Collection<Statement>... sourceStatements) throws IOException, RDFHandlerException { if (sourceStatements.length == 1) { DataSourceConfig dataSourceConfig = createFileDataSource(sourceStatements[0]); return Collections.singleton((AllTriplesLoader) new AllTriplesFileLoader(dataSourceConfig, ConfigConstants.DEFAULT_FILE_PARSER_CONFIG)); } ArrayList<AllTriplesLoader> result = new ArrayList<>(); for (Collection<Statement> statements : sourceStatements) { DataSourceConfig dataSourceConfig = createFileDataSource(statements); result.add(new AllTriplesFileLoader(dataSourceConfig, ConfigConstants.DEFAULT_FILE_PARSER_CONFIG)); } return result; } private DataSourceConfig createFileDataSource(Collection<Statement> statements) throws IOException, RDFHandlerException { DataSourceConfigImpl result = new DataSourceConfigImpl( EnumDataSourceType.FILE, "test-input-file" + testFileCounter.getAndIncrement() + ".trig"); EnumSerializationFormat format = EnumSerializationFormat.TRIG; File inputFile = createInputFile(statements, format.toSesameFormat()); result.getParams().put(ConfigParameters.DATA_SOURCE_FILE_PATH, inputFile.getAbsolutePath()); result.getParams().put(ConfigParameters.DATA_SOURCE_FILE_FORMAT, format.name()); return result; } private File createInputFile(Collection<Statement> statements, RDFFormat format) throws IOException, RDFHandlerException { File inputFile = testDir.newFile(); FileOutputStream outputStream = new FileOutputStream(inputFile); RDFWriter rdfWriter = Rio.createWriter(format, outputStream); rdfWriter.startRDF(); rdfWriter.handleComment("Test input file"); for (Statement statement : statements) { rdfWriter.handleStatement(statement); } rdfWriter.endRDF(); outputStream.close(); return inputFile; } private void collectResult(ExternalSortingInputLoader inputLoader, Set<Statement> result) throws ODCSFusionToolException { inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { result.addAll(inputLoader.next().getDescribingStatements()); } } private static Map<Resource, Map<URI, Set<Statement>>> createConflictClusterMap(Collection<Statement> statements, UriMapping uriMapping) { Map<Resource, Map<URI, Set<Statement>>> result = new HashMap<>(); for (Statement st : statements) { Resource canonicalSubject = uriMapping.mapResource(st.getSubject()); Map<URI, Set<Statement>> subjectRecord = result.get(canonicalSubject); if (subjectRecord == null) { subjectRecord = new HashMap<>(); result.put(canonicalSubject, subjectRecord); } URI canonicalPredicate = (URI) uriMapping.mapResource(st.getPredicate()); Set<Statement> predicateRecord = subjectRecord.get(canonicalPredicate); if (predicateRecord == null) { predicateRecord = new HashSet<>(); subjectRecord.put(canonicalPredicate, predicateRecord); } predicateRecord.add(st); } return result; } }
sources/odcsft-application/src/test/java/cz/cuni/mff/odcleanstore/fusiontool/loaders/ExternalSortingInputLoaderTest.java
package cz.cuni.mff.odcleanstore.fusiontool.loaders; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import cz.cuni.mff.odcleanstore.conflictresolution.ResolvedStatement; import cz.cuni.mff.odcleanstore.conflictresolution.impl.ResolvedStatementImpl; import cz.cuni.mff.odcleanstore.conflictresolution.impl.util.SpogComparator; import cz.cuni.mff.odcleanstore.fusiontool.config.ConfigConstants; import cz.cuni.mff.odcleanstore.fusiontool.config.ConfigParameters; import cz.cuni.mff.odcleanstore.fusiontool.config.DataSourceConfig; import cz.cuni.mff.odcleanstore.fusiontool.config.DataSourceConfigImpl; import cz.cuni.mff.odcleanstore.fusiontool.config.EnumDataSourceType; import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.ResourceDescription; import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.UriMapping; import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.urimapping.UriMappingIterable; import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.urimapping.UriMappingIterableImpl; import cz.cuni.mff.odcleanstore.fusiontool.exceptions.ODCSFusionToolException; import cz.cuni.mff.odcleanstore.fusiontool.io.EnumSerializationFormat; import cz.cuni.mff.odcleanstore.fusiontool.loaders.data.AllTriplesFileLoader; import cz.cuni.mff.odcleanstore.fusiontool.loaders.data.AllTriplesLoader; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.openrdf.model.Model; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.impl.TreeModel; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFWriter; import org.openrdf.rio.Rio; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; import static cz.cuni.mff.odcleanstore.fusiontool.testutil.ContextAwareStatementIsEqual.contextAwareStatementIsEqual; import static cz.cuni.mff.odcleanstore.fusiontool.testutil.ODCSFTTestUtils.createHttpStatement; import static cz.cuni.mff.odcleanstore.fusiontool.testutil.ODCSFTTestUtils.createHttpUri; import static cz.cuni.mff.odcleanstore.fusiontool.testutil.ODCSFTTestUtils.createStatement; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; public class ExternalSortingInputLoaderTest { // TODO private static final URI resourceDescriptionProperty = ConfigConstants.RESOURCE_DESCRIPTION_URIS.iterator().next(); private static final ValueFactoryImpl VF = ValueFactoryImpl.getInstance(); public static final SpogComparator SPOG_COMPARATOR = new SpogComparator(); @Rule public TemporaryFolder testDir = new TemporaryFolder(); private AtomicInteger testFileCounter = new AtomicInteger(0); private UriMappingIterable uriMapping; /** A general case of test data */ private Collection<Statement> testInput1 = ImmutableList.of( // triples that map to the same statement createHttpStatement("sa", "pa", "oa", "g1"), createHttpStatement("sb", "pb", "ob", "g1"), // additional triple for the mapped resource createHttpStatement("sa", "p1", "oa", "ga"), // two identical triples createHttpStatement("s1", "p1", "o1", "g1"), createHttpStatement("s1", "p1", "o1", "g1"), // a conflict cluster with three values createHttpStatement("s2", "p2", "o1", "g1"), createHttpStatement("s2", "p2", "o2", "g2"), createHttpStatement("s2", "p2", "o3", "g3"), // resource description with two conflict clusters createHttpStatement("s3", "p1", "o1", "g4"), createHttpStatement("s3", "p2", "o2", "g5"), createHttpStatement("s3", "p2", "o3", "g5"), // resource description with mapped property and object and no named graph createHttpStatement("s4", "pa", "o1"), createHttpStatement("s4", "p1", "oa") ); /** Map of canonical subject -> canonical predicate -> set of statements in conflict cluster for {@link #testInput1} */ private Map<Resource, Map<URI, Set<Statement>>> conflictClustersMap1; private Collection<Statement> testInput2 = ImmutableList.of( createHttpStatement("s1", "p1", "o1", "g1"), createHttpStatement("x", "y", "z", "g1") ); // FIXME: add corresponding integration test private Collection<Statement> testInput3 = ImmutableList.of( // Resource description with two dependent resources and one normal triple createHttpStatement("s1", "p1", "o1"), createStatement(createHttpUri("s1"), resourceDescriptionProperty, createHttpUri("dependent1")), createStatement(createHttpUri("s1"), resourceDescriptionProperty, createHttpUri("dependent3")), // Resource description sharing a dependent resource with s1 createStatement(createHttpUri("s3"), resourceDescriptionProperty, createHttpUri("dependent3")), // the dependent resources createHttpStatement("dependent1", "p2", "o2"), createHttpStatement("dependent1", "p3", "o3"), createHttpStatement("dependent3", "p4", "o4"), // extra triples createHttpStatement("s2", "p5", "o5"), createHttpStatement("dependent2-not-really", "p6", "o7") ); /** Map of canonical resource -> set of expected statments in the respective resource description for {@link #testInput3} */ private Map<Resource, TreeSet<Statement>> conflictClusters3; @Before public void setUp() throws Exception { // init URI mapping // map sa, sb -> sx; pa, pb -> px; oa, ob -> ox; ga, gb -> gx UriMappingIterableImpl uriMappingImpl = new UriMappingIterableImpl(ImmutableSet.of( createHttpUri("sx").toString(), createHttpUri("px").toString(), createHttpUri("ox").toString(), createHttpUri("gx").toString())); uriMappingImpl.addLink(createHttpUri("sa").toString(), createHttpUri("sx").toString()); uriMappingImpl.addLink(createHttpUri("sb").toString(), createHttpUri("sx").toString()); uriMappingImpl.addLink(createHttpUri("pa").toString(), createHttpUri("px").toString()); uriMappingImpl.addLink(createHttpUri("pb").toString(), createHttpUri("px").toString()); uriMappingImpl.addLink(createHttpUri("oa").toString(), createHttpUri("ox").toString()); uriMappingImpl.addLink(createHttpUri("ob").toString(), createHttpUri("ox").toString()); uriMappingImpl.addLink(createHttpUri("ga").toString(), createHttpUri("gx").toString()); uriMappingImpl.addLink(createHttpUri("gb").toString(), createHttpUri("gx").toString()); this.uriMapping = uriMappingImpl; // init map of conflict clusters 1 conflictClustersMap1 = createConflictClusterMap(testInput1, uriMapping); // init map of conflict cluster 3 conflictClusters3 = new HashMap<>(); for (Statement statement : testInput3) { Resource canonicalSubject = uriMapping.mapResource(statement.getSubject()); if (!conflictClusters3.containsKey(canonicalSubject)) { conflictClusters3.put(canonicalSubject, new TreeSet<>(SPOG_COMPARATOR)); } conflictClusters3.get(canonicalSubject).add(statement); } Model model3 = new TreeModel(testInput3); for (Statement statement : model3.filter(null, resourceDescriptionProperty, null)) { TreeSet<Statement> conflictCluster = conflictClusters3.get(uriMapping.mapResource(statement.getSubject())); conflictCluster.addAll(model3.filter((Resource) statement.getObject(), null, null)); // we expect no mapping is required } } @Test public void iteratesOverAllStatementsWithoutAppliedUriMapping() throws Exception { // Act SortedSet<Statement> result = new TreeSet<>(SPOG_COMPARATOR); ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput1, false); try { collectResult(inputLoader, result); } finally { inputLoader.close(); } // Assert SortedSet<Statement> expectedStatementsSet = new TreeSet<>(SPOG_COMPARATOR); expectedStatementsSet.addAll(testInput1); assertThat(result.size(), equalTo(expectedStatementsSet.size())); Statement[] expectedStatements = expectedStatementsSet.toArray(new Statement[0]); Statement[] actualStatements = result.toArray(new Statement[0]); for (int i = 0; i < expectedStatements.length; i++) { // compare including named graphs assertThat(actualStatements[i], contextAwareStatementIsEqual(expectedStatements[i])); } } @Test public void nextQuadsReturnsCompleteConflictClusters() throws Exception { // Act List<Collection<Statement>> statementBlocks = new ArrayList<>(); ExternalSortingInputLoader inputLoader = null; try { inputLoader = createExternalSortingInputLoader(testInput1, false); inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { statementBlocks.add(inputLoader.next().getDescribingStatements()); } } finally { inputLoader.close(); } // Assert for (Collection<Statement> block : statementBlocks) { // for each conflict cluster in a block returned by next(), // all quads belonging to this conflict cluster must be present. for (Statement statement : block) { Set<Statement> conflictCluster = conflictClustersMap1 .get(uriMapping.mapResource(statement.getSubject())) .get(uriMapping.mapResource(statement.getPredicate())); boolean blockContainsEntireConflictCluster = block.containsAll(conflictCluster); if (!blockContainsEntireConflictCluster) { fail(String.format("Block %s doesn't contain the entire conflict cluster %s", block, conflictCluster)); } } } } @Test public void nextQuadsReturnsDescriptionOfSingleResource() throws Exception { // Act List<Collection<Statement>> statementBlocks = new ArrayList<>(); ExternalSortingInputLoader inputLoader = null; try { inputLoader = createExternalSortingInputLoader(testInput1, false); inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { statementBlocks.add(inputLoader.next().getDescribingStatements()); } } finally { inputLoader.close(); } // Assert for (Collection<Statement> block : statementBlocks) { assertFalse(block.isEmpty()); Resource firstCanonicalSubject = uriMapping.mapResource(block.iterator().next().getSubject()); for (Statement statement : block) { assertThat(uriMapping.mapResource(statement.getSubject()), equalTo(firstCanonicalSubject)); } } } @Test public void resourceIsDescribedInSingleNextQuadsResult() throws Exception { // Act List<Collection<Statement>> statementBlocks = new ArrayList<>(); ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput1, false); try { inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { statementBlocks.add(inputLoader.next().getDescribingStatements()); } } finally { inputLoader.close(); } // Assert Set<Resource> canonicalSubjectsFromPreviousBlocks = new HashSet<>(); for (Collection<Statement> block : statementBlocks) { Set<Resource> subjectsFromCurrentBlock = new HashSet<>(); for (Statement statement : block) { Resource canonicalSubject = uriMapping.mapResource(statement.getSubject()); assertFalse(canonicalSubjectsFromPreviousBlocks.contains(canonicalSubject)); subjectsFromCurrentBlock.add(canonicalSubject); } canonicalSubjectsFromPreviousBlocks.addAll(subjectsFromCurrentBlock); } } @Test public void worksOnEmptyStatements() throws Exception { // Act & assert ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(Collections.<Statement>emptySet(), false); try { inputLoader.initialize(uriMapping); assertFalse(inputLoader.hasNext()); } finally { inputLoader.close(); } } @Test public void clearsTemporaryFilesWhenClosed() throws Exception { // Act ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput1, false); try { inputLoader.initialize(uriMapping); if (inputLoader.hasNext()) { // call only once inputLoader.next(); } } finally { inputLoader.close(); } // Assert File[] filesInWorkingDir = testDir.getRoot().listFiles(); assertThat(filesInWorkingDir.length, equalTo(1)); // only the input file should remain } @Test public void clearsTemporaryFilesOnError() throws Exception { // Act ExternalSortingInputLoader inputLoader = null; Exception caughtException = null; try { DataSourceConfig dataSource = createFileDataSource(testInput1); File inputFile = new File(dataSource.getParams().get(ConfigParameters.DATA_SOURCE_FILE_PATH)); FileWriter inputFileWriter = new FileWriter(inputFile, true); inputFileWriter.append("xyz;"); inputFileWriter.close(); Set<AllTriplesLoader> dataSources = Collections.singleton( (AllTriplesLoader) new AllTriplesFileLoader(dataSource, ConfigConstants.DEFAULT_FILE_PARSER_CONFIG)); inputLoader = new ExternalSortingInputLoader(dataSources, testDir.getRoot(), ConfigConstants.DEFAULT_FILE_PARSER_CONFIG, Long.MAX_VALUE, false); inputLoader.initialize(uriMapping); if (inputLoader.hasNext()) { // call only once inputLoader.next(); } } catch (Exception e) { caughtException = e; } finally { inputLoader.close(); } // Assert assertThat(caughtException, instanceOf(ODCSFusionToolException.class)); File[] filesInWorkingDir = testDir.getRoot().listFiles(); assertThat(filesInWorkingDir.length, equalTo(1)); // only the input file should remain } @Test public void updateWithResolvedStatementsDoesNotThrowException() throws Exception { // Act ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput1, false); try { inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { Collection<Statement> statements = inputLoader.next().getDescribingStatements(); Statement firstStatement = statements.iterator().next(); ResolvedStatement resolvedStatement = new ResolvedStatementImpl(firstStatement, 0.5, Collections.singleton(firstStatement.getContext())); inputLoader.updateWithResolvedStatements(Collections.singleton(resolvedStatement)); } } finally { inputLoader.close(); } } @Test public void readsMultipleInputFiles() throws Exception { // Act SortedSet<Statement> result = new TreeSet<>(SPOG_COMPARATOR); ExternalSortingInputLoader inputLoader = new ExternalSortingInputLoader( createFileAllTriplesLoader(testInput1, testInput2), testDir.getRoot(), ConfigConstants.DEFAULT_FILE_PARSER_CONFIG, Long.MAX_VALUE, false); try { collectResult(inputLoader, result); } finally { inputLoader.close(); } // Assert SortedSet<Statement> expectedStatementsSet = new TreeSet<>(SPOG_COMPARATOR); expectedStatementsSet.addAll(testInput1); expectedStatementsSet.addAll(testInput2); assertThat(result.size(), equalTo(expectedStatementsSet.size())); Statement[] expectedStatements = expectedStatementsSet.toArray(new Statement[0]); Statement[] actualStatements = result.toArray(new Statement[0]); for (int i = 0; i < expectedStatements.length; i++) { // compare including named graphs assertThat(actualStatements[i], contextAwareStatementIsEqual(expectedStatements[i])); } } @Test public void filtersUnmappedSubjectsWhenOutputMappedSubjectsOnlyIsTrue() throws Exception { // Arrange ArrayList<Statement> statements = new ArrayList<>(); statements.add(createHttpStatement("s1", "p1", "o1", "g1")); statements.add(createHttpStatement("s3", "p1", "o1", "g1")); statements.add(createHttpStatement("s2", "p1", "o1", "g1")); statements.add(createHttpStatement("s4", "p1", "o1", "g1")); UriMappingIterableImpl uriMapping = new UriMappingIterableImpl(ImmutableSet.of( createHttpUri("sx").toString(), createHttpUri("s2").toString())); uriMapping.addLink(createHttpUri("s1").toString(), createHttpUri("sx").toString()); uriMapping.addLink(createHttpUri("s2").toString(), createHttpUri("sy").toString()); // Act SortedSet<Statement> result = new TreeSet<>(SPOG_COMPARATOR); ExternalSortingInputLoader inputLoader = null; try { inputLoader = createExternalSortingInputLoader(statements, true); inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { result.addAll(inputLoader.next().getDescribingStatements()); } } finally { inputLoader.close(); } // Assert SortedSet<Statement> expectedStatementsSet = new TreeSet<>(SPOG_COMPARATOR); expectedStatementsSet.add(createHttpStatement("s1", "p1", "o1", "g1")); expectedStatementsSet.add(createHttpStatement("s2", "p1", "o1", "g1")); assertThat(result.size(), equalTo(expectedStatementsSet.size())); Statement[] expectedStatements = expectedStatementsSet.toArray(new Statement[0]); Statement[] actualStatements = result.toArray(new Statement[0]); for (int i = 0; i < expectedStatements.length; i++) { assertThat(actualStatements[i], contextAwareStatementIsEqual(expectedStatements[i])); } } @Test public void iteratesOverAllStatementsWithDependentResources() throws Exception { // Act SortedSet<Statement> result = new TreeSet<>(SPOG_COMPARATOR); ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput3, false); try { collectResult(inputLoader, result); } finally { inputLoader.close(); } // Assert SortedSet<Statement> expectedStatementsSet = new TreeSet<>(SPOG_COMPARATOR); expectedStatementsSet.addAll(testInput3); assertThat(result.size(), equalTo(expectedStatementsSet.size())); Statement[] expectedStatements = expectedStatementsSet.toArray(new Statement[0]); Statement[] actualStatements = result.toArray(new Statement[0]); for (int i = 0; i < expectedStatements.length; i++) { // compare including named graphs assertThat(actualStatements[i], contextAwareStatementIsEqual(expectedStatements[i])); } } @Test public void includesCorrectDependentResourcesInResourceDescriptions() throws Exception { // Act Map<Resource, TreeSet<Statement>> result = new HashMap<>(); ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput3, false); try { inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { ResourceDescription resourceDescription = inputLoader.next(); Collection<Statement> cluster = resourceDescription.getDescribingStatements(); TreeSet<Statement> statements = new TreeSet<>(SPOG_COMPARATOR); statements.addAll(cluster); result.put(resourceDescription.getResource(), statements); } } finally { inputLoader.close(); } // Assert assertThat(result.size(), is(conflictClusters3.size())); for (Map.Entry<Resource, TreeSet<Statement>> entry : conflictClusters3.entrySet()) { Statement[] expectedStatements = entry.getValue().toArray(new Statement[0]); Statement[] actualStatements = result.get(entry.getKey()).toArray(new Statement[0]); String errorMessage = "Statements for resource " + entry.getKey() + " do not match"; assertThat(errorMessage, actualStatements.length, is(expectedStatements.length)); for (int i = 0; i < expectedStatements.length; i++) { assertThat(errorMessage, actualStatements[i], contextAwareStatementIsEqual(expectedStatements[i])); } } } @Test public void handlesLiteralsAsValuesOfDescriptionProperties() throws Exception { // Arrange URI resource = createHttpUri("s1"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("s1", "p1", "o1"), createStatement(resource, resourceDescriptionProperty, createHttpUri("dependent1")), VF.createStatement(resource, resourceDescriptionProperty, VF.createLiteral("a")), createHttpStatement("dependent1", "p2", "o2")); // Act ResourceDescription result = null; ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput, false); try { inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { ResourceDescription resourceDescription = inputLoader.next(); if (resourceDescription.getResource().equals(resource)) { result = resourceDescription; } } } finally { inputLoader.close(); } // Assert assertThat(result, notNullValue()); System.out.println(result.getDescribingStatements()); assertThat(result.getDescribingStatements().size(), is(testInput.size())); } @Test public void includesCorrectDependentResourcesWhenDescriptionPropertyIsMapped() throws Exception { // Arrange URI mappedDescriptionProperty = createHttpUri("mappedDescriptionProperty"); URI resource = createHttpUri("s1"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("s1", "p1", "o1"), createStatement(resource, mappedDescriptionProperty, createHttpUri("dependent1")), createHttpStatement("dependent1", "p2", "o2")); UriMappingIterableImpl propertyUriMapping = new UriMappingIterableImpl(ImmutableSet.of(resourceDescriptionProperty.stringValue())); propertyUriMapping.addLink(mappedDescriptionProperty, resourceDescriptionProperty); // Act ResourceDescription result = null; ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput, false); try { inputLoader.initialize(propertyUriMapping); while (inputLoader.hasNext()) { ResourceDescription resourceDescription = inputLoader.next(); if (resourceDescription.getResource().equals(resource)) { result = resourceDescription; } } } finally { inputLoader.close(); } // Assert assertThat(result, notNullValue()); System.out.println(result.getDescribingStatements()); assertThat(result.getDescribingStatements().size(), is(testInput.size())); } private ExternalSortingInputLoader createExternalSortingInputLoader(Collection<Statement> testInput, boolean outputMappedSubjectsOnly) throws IOException, RDFHandlerException { return new ExternalSortingInputLoader( createFileAllTriplesLoader(testInput), testDir.getRoot(), ConfigConstants.DEFAULT_FILE_PARSER_CONFIG, Long.MAX_VALUE, outputMappedSubjectsOnly); } private Collection<AllTriplesLoader> createFileAllTriplesLoader(Collection<Statement>... sourceStatements) throws IOException, RDFHandlerException { if (sourceStatements.length == 1) { DataSourceConfig dataSourceConfig = createFileDataSource(sourceStatements[0]); return Collections.singleton((AllTriplesLoader) new AllTriplesFileLoader(dataSourceConfig, ConfigConstants.DEFAULT_FILE_PARSER_CONFIG)); } ArrayList<AllTriplesLoader> result = new ArrayList<>(); for (Collection<Statement> statements : sourceStatements) { DataSourceConfig dataSourceConfig = createFileDataSource(statements); result.add(new AllTriplesFileLoader(dataSourceConfig, ConfigConstants.DEFAULT_FILE_PARSER_CONFIG)); } return result; } private DataSourceConfig createFileDataSource(Collection<Statement> statements) throws IOException, RDFHandlerException { DataSourceConfigImpl result = new DataSourceConfigImpl( EnumDataSourceType.FILE, "test-input-file" + testFileCounter.getAndIncrement() + ".trig"); EnumSerializationFormat format = EnumSerializationFormat.TRIG; File inputFile = createInputFile(statements, format.toSesameFormat()); result.getParams().put(ConfigParameters.DATA_SOURCE_FILE_PATH, inputFile.getAbsolutePath()); result.getParams().put(ConfigParameters.DATA_SOURCE_FILE_FORMAT, format.name()); return result; } private File createInputFile(Collection<Statement> statements, RDFFormat format) throws IOException, RDFHandlerException { File inputFile = testDir.newFile(); FileOutputStream outputStream = new FileOutputStream(inputFile); RDFWriter rdfWriter = Rio.createWriter(format, outputStream); rdfWriter.startRDF(); rdfWriter.handleComment("Test input file"); for (Statement statement : statements) { rdfWriter.handleStatement(statement); } rdfWriter.endRDF(); outputStream.close(); return inputFile; } private void collectResult(ExternalSortingInputLoader inputLoader, Set<Statement> result) throws ODCSFusionToolException { inputLoader.initialize(uriMapping); while (inputLoader.hasNext()) { result.addAll(inputLoader.next().getDescribingStatements()); } } private static Map<Resource, Map<URI, Set<Statement>>> createConflictClusterMap(Collection<Statement> statements, UriMapping uriMapping) { Map<Resource, Map<URI, Set<Statement>>> result = new HashMap<>(); for (Statement st : statements) { Resource canonicalSubject = uriMapping.mapResource(st.getSubject()); Map<URI, Set<Statement>> subjectRecord = result.get(canonicalSubject); if (subjectRecord == null) { subjectRecord = new HashMap<>(); result.put(canonicalSubject, subjectRecord); } URI canonicalPredicate = (URI) uriMapping.mapResource(st.getPredicate()); Set<Statement> predicateRecord = subjectRecord.get(canonicalPredicate); if (predicateRecord == null) { predicateRecord = new HashSet<>(); subjectRecord.put(canonicalPredicate, predicateRecord); } predicateRecord.add(st); } return result; } }
test for incorrect comparison when external sorting
sources/odcsft-application/src/test/java/cz/cuni/mff/odcleanstore/fusiontool/loaders/ExternalSortingInputLoaderTest.java
test for incorrect comparison when external sorting
<ide><path>ources/odcsft-application/src/test/java/cz/cuni/mff/odcleanstore/fusiontool/loaders/ExternalSortingInputLoaderTest.java <ide> import cz.cuni.mff.odcleanstore.fusiontool.io.EnumSerializationFormat; <ide> import cz.cuni.mff.odcleanstore.fusiontool.loaders.data.AllTriplesFileLoader; <ide> import cz.cuni.mff.odcleanstore.fusiontool.loaders.data.AllTriplesLoader; <add>import org.hamcrest.Matcher; <add>import org.hamcrest.Matchers; <ide> import org.junit.Before; <add>import org.junit.Ignore; <ide> import org.junit.Rule; <ide> import org.junit.Test; <ide> import org.junit.rules.TemporaryFolder; <ide> /** Map of canonical subject -> canonical predicate -> set of statements in conflict cluster for {@link #testInput1} */ <ide> private Map<Resource, Map<URI, Set<Statement>>> conflictClustersMap1; <ide> <del> private Collection<Statement> testInput2 = ImmutableList.of( <add> private final Collection<Statement> testInput2 = ImmutableList.of( <ide> createHttpStatement("s1", "p1", "o1", "g1"), <ide> createHttpStatement("x", "y", "z", "g1") <ide> ); <ide> <ide> // FIXME: add corresponding integration test <del> private Collection<Statement> testInput3 = ImmutableList.of( <add> private final Collection<Statement> testInput3 = ImmutableList.of( <ide> // Resource description with two dependent resources and one normal triple <ide> createHttpStatement("s1", "p1", "o1"), <ide> createStatement(createHttpUri("s1"), resourceDescriptionProperty, createHttpUri("dependent1")), <ide> <ide> @Test <ide> public void includesCorrectDependentResourcesInResourceDescriptions() throws Exception { <del> // Act <del> Map<Resource, TreeSet<Statement>> result = new HashMap<>(); <add> // Arrange <add> Map<Resource, TreeSet<Statement>> result; <ide> ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput3, false); <del> try { <del> inputLoader.initialize(uriMapping); <del> while (inputLoader.hasNext()) { <del> ResourceDescription resourceDescription = inputLoader.next(); <del> Collection<Statement> cluster = resourceDescription.getDescribingStatements(); <del> TreeSet<Statement> statements = new TreeSet<>(SPOG_COMPARATOR); <del> statements.addAll(cluster); <del> result.put(resourceDescription.getResource(), statements); <del> } <add> <add> // Act <add> try { <add> result = collectResourceDescriptions(inputLoader); <ide> } finally { <ide> inputLoader.close(); <ide> } <ide> assertThat(result.getDescribingStatements().size(), is(testInput.size())); <ide> } <ide> <add> @Ignore <add> @Test <add> public void mergesFilesTogetherWhenOneUriIsPrefixOfAnother() throws Exception { <add> // Arrange <add> ImmutableList<Statement> testInput = ImmutableList.of( <add> createHttpStatement("prefix/dependent", "p", "o"), <add> createHttpStatement("prefix", "a", "o"), <add> createStatement(createHttpUri("prefix"), resourceDescriptionProperty, createHttpUri("prefix/dependent"))); <add> ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput, false); <add> Map<Resource, Collection<Statement>> expectedResult = new HashMap<>(); <add> expectedResult.put(createHttpUri("prefix/dependent"), ImmutableList.of(createHttpStatement("prefix/dependent", "p", "o", null))); <add> expectedResult.put(createHttpUri("prefix"), ImmutableList.of( <add> createHttpStatement("prefix/dependent", "p", "o"), <add> createHttpStatement("prefix", "a", "o"), <add> VF.createStatement(createHttpUri("prefix"), resourceDescriptionProperty, createHttpUri("prefix/dependent")))); <add> Map<Resource, TreeSet<Statement>> result; <add> <add> // Act <add> try { <add> result = collectResourceDescriptions(inputLoader); <add> } finally { <add> inputLoader.close(); <add> } <add> <add> // Assert <add> assertThat(result.size(), is(expectedResult.size())); <add> for (Map.Entry<Resource, Collection<Statement>> entry : expectedResult.entrySet()) { <add> Matcher<Statement>[] expectedStatements = toContextAwareEqualMatchers(entry.getValue()); <add> Collection<Statement> actualStatements = result.get(entry.getKey()); <add> String errorMessage = "Statements for resource " + entry.getKey() + " do not match"; <add> assertThat(errorMessage, actualStatements, Matchers.containsInAnyOrder(expectedStatements)); <add> } <add> } <add> <add> private Matcher<Statement>[] toContextAwareEqualMatchers(Collection<Statement> value) { <add> Matcher<Statement>[] result = new Matcher[value.size()]; <add> int i = 0; <add> for (Statement statement : value) { <add> result[i++] = contextAwareStatementIsEqual(statement); <add> } <add> return result; <add> } <add> <add> private Map<Resource, TreeSet<Statement>> collectResourceDescriptions(ExternalSortingInputLoader inputLoader) throws ODCSFusionToolException { <add> Map<Resource, TreeSet<Statement>> result = new HashMap<>(); <add> inputLoader.initialize(uriMapping); <add> while (inputLoader.hasNext()) { <add> ResourceDescription resourceDescription = inputLoader.next(); <add> Collection<Statement> cluster = resourceDescription.getDescribingStatements(); <add> TreeSet<Statement> statements = new TreeSet<>(SPOG_COMPARATOR); <add> statements.addAll(cluster); <add> result.put(resourceDescription.getResource(), statements); <add> } <add> return result; <add> } <add> <ide> <ide> private ExternalSortingInputLoader createExternalSortingInputLoader(Collection<Statement> testInput, boolean outputMappedSubjectsOnly) throws IOException, RDFHandlerException { <ide> return new ExternalSortingInputLoader(
JavaScript
apache-2.0
c992198204a7f5a8b5a9dc293d6277b4f93a3de4
0
VikramTiwari/gcloud-node,SimpleEmotion/gcloud-node,callmehiphop/gcloud-node-ghpages,blowmage/gcloud-node,nemo/gcloud-node,chrishiestand/gcloud-node,pcostell/gcloud-node,t9nf/gcloud-node,GoogleCloudPlatform/gcloud-node,ofrobots/google-cloud-node,savethefails/gcloud-node,stephenplusplus/gcloud-node-bigquery-debug,authbox-lib/gcloud-node,savethefails/gcloud-node,VikramTiwari/gcloud-node,callmehiphop/gcloud-node,blowmage/gcloud-node,GoogleCloudPlatform/gcloud-node,jcking/google-cloud-node,phw/gcloud-node,pcostell/gcloud-node,tcrognon/google-cloud-node,stephenplusplus/gcloud-node,jonparrott/gcloud-node,stephenplusplus/gcloud-node-bigquery-debug,ofrobots/google-cloud-node,stephenplusplus/gcloud-node,authbox-lib/gcloud-node,Muffasa/gcloud-node,mziccard/gcloud-node,pcostell/gcloud-node,t9nf/gcloud-node,authbox-lib/gcloud-node,anandsuresh/gcloud-node,googleapis/google-cloud-node,googleapis/google-cloud-node,jcking/google-cloud-node,anandsuresh/gcloud-node,jonparrott/gcloud-node,nemo/gcloud-node,Muffasa/gcloud-node,jcking/google-cloud-node,jmptrader/gcloud-node,savethefails/gcloud-node,callmehiphop/gcloud-node-ghpages,jmptrader/gcloud-node,chrishiestand/gcloud-node,googleapis/google-cloud-node,nemo/gcloud-node,Muffasa/gcloud-node,SimpleEmotion/gcloud-node,googleapis/google-cloud-node,callmehiphop/gcloud-node,jgeewax/gcloud-node,jgeewax/gcloud-node,stephenplusplus/gcloud-node,VikramTiwari/gcloud-node,tcrognon/google-cloud-node,mziccard/gcloud-node,ofrobots/google-cloud-node,chrishiestand/gcloud-node,GoogleCloudPlatform/gcloud-node,t9nf/gcloud-node,phw/gcloud-node,SimpleEmotion/gcloud-node
angular .module('gcloud.docs', ['ngRoute', 'hljs', 'config']) .config(function($routeProvider, versions) { 'use strict'; function filterDocJson($sce, version) { // Transform JSON response to remove extraneous objects. function formatHtml(str) { return str .replace(/\s+/g, ' ') .replace(/<br *\/*>/g, ' ') .replace(/`([^`]*)`/g, '<code>$1</code>'); } function formatComments(str) { var matched = 0; var paragraphComments = /\/\/-+((\n|\r|.)*?(\/\/-))/g; if (!paragraphComments.test(str)) { return '<div hljs language="javascript">\n' + str + '</div>'; } str = str.replace(paragraphComments, function(match, block) { return '' + (++matched > 1 ? '</div>' : '') + '<p>' + formatHtml(detectLinks(detectModules( block.trim() .replace(/\/\/-*\s*/g, '\n') .replace(/\n\n/g, '\n') .replace(/(\w)\n(\w)/g, '$1 $2') .replace(/\n\n/g, '</p><p>') ))) + '</p>' + '<div hljs language="javascript">'; }); str = str.replace(/(<div[^>]*>)\n+/g, '$1\n'); str = str.replace(/\n<\/div>/g, '</div>'); return str; } function detectLinks(str) { var regex = { withCode: /{@linkcode <a href="([^\"]*)">([^<]*)<\/a>/g, withTitle: /\[([^\]]*)]{@link <a href="([^}]*)}">[^}]*}<\/a>/g, withoutTitle: /{@link <a href="([^}]*)}">[^}]*}<\/a>/g }; var a = document.createElement('a'); return str .replace(regex.withTitle, function(match, title, link) { a.href = link; a.innerText = title; return a.outerHTML; }) .replace(regex.withoutTitle, function(match, link) { a.href = link; a.innerText = link.replace(/^http\s*:\/\//, ''); return a.outerHTML; }) .replace(regex.withCode, function(match, link, text) { a.href = link; a.innerText = text; return '<code>' + a.outerHTML + '</code>'; }); } function detectModules(str) { var regex = { see: /{*module:([^}]*)}*/g }; var a = document.createElement('a'); return str.replace(regex.see, function(match, module) { var path = module; if (path.indexOf('#') > -1) { path = path.split('#').map(function(part, index, parts) { if (index < parts.length - 1) { return part + '/'; } else { return '?method=' + part; } }).join(''); } a.href = '#/docs/' + version + '/' + path; a.innerText = module; return a.outerHTML; }); } function reduceModules(acc, type, index, types) { var CUSTOM_TYPES = ['query', 'dataset', 'transaction']; if (CUSTOM_TYPES.indexOf(type.toLowerCase()) > -1) { if (types[index - 1]) { type = types[index - 1] + '/' + type; delete types[index - 1]; } } acc.push(detectModules(type)); return acc; } return function(data) { return data.data .filter(function(obj) { return obj.isPrivate === false && obj.ignore === false; }) .map(function(obj) { return { data: obj, name: obj.ctx.name, constructor: obj.tags.some(function(tag) { return tag.type === 'constructor'; }), mixes: obj.tags.filter(function(tag) { return tag.type === 'mixes'; }), description: $sce.trustAsHtml( formatHtml(detectLinks(detectModules(obj.description.full)))), params: obj.tags.filter(function(tag) { return tag.type === 'param'; }) .map(function(tag) { tag.description = $sce.trustAsHtml( formatHtml(tag.description.replace(/^- /, ''))); tag.types = $sce.trustAsHtml(tag.types.reduceRight( reduceModules, []).join(', ')); tag.optional = tag.types.toString().substr(-1) === '='; return tag; }), returns: obj.tags.filter(function(tag) { return tag.type === 'return'; }) .map(function(tag) { return $sce.trustAsHtml( tag.types.reduceRight(reduceModules, [])[0]); })[0], example: obj.tags.filter(function(tag) { return tag.type === 'example'; }) .map(function(tag) { return $sce.trustAsHtml(formatComments(tag.string)); })[0] }; }) .sort(compareMethods); }; } function getMixIns($sce, $q, $http, version, baseUrl) { return function(data) { var methodWithMixIns = data.filter(function(method) { return method.mixes; })[0]; if (!methodWithMixIns) { return data; } return $q .all(getMixInMethods(methodWithMixIns)) .then(combineMixInMethods(data)); }; function getMixInMethods(method) { return method.mixes.map(function (module) { module = module.string.trim().replace('module:', ''); return $http.get(baseUrl + '/' + module + '.json') .then(filterDocJson($sce, version)) .then(function(mixInData) { return mixInData.filter(function(method) { return !method.constructor; }); }); }); } function combineMixInMethods(data) { return function(mixInData) { return mixInData .reduce(function(acc, mixInMethods) { acc = acc.concat(mixInMethods); return acc; }, data) .sort(compareMethods); }; } } function setSingleMethod(method) { return function(methods) { if (method && methods.some(function(methodObj) { return methodObj.name === method; })) { methods.singleMethod = method; } return methods; }; } function getMethods($http, $route, $sce, $q, $location) { var version = $route.current.params.version; var module = $route.current.params.module; var cl = $route.current.params.class; var path = ['json', version]; if (!module && !cl) { path.push('index.json'); } else if (module && !cl) { path.push(module); path.push('index.json'); } else if (module && cl) { path.push(module); path.push(cl + '.json'); } return $http.get(path.join('/')) .then(filterDocJson($sce, version)) .then(getMixIns($sce, $q, $http, version, 'json/' + version)) .then(setSingleMethod($location.search().method)); } function compareMethods(a, b) { return a.constructor ? -1: a.name > b.name; } function getLinks($route, getLinks) { return getLinks($route.current.params.version); } $routeProvider .when('/docs', { redirectTo: '/docs/' + versions[0] }) .when('/docs/history', { controller: 'HistoryCtrl', templateUrl: 'components/docs/docs.html' }) .when('/docs/:version', { controller: 'DocsCtrl', templateUrl: 'components/docs/docs.html', resolve: { methods: getMethods, links: getLinks } }) .when('/docs/:version/:module', { controller: 'DocsCtrl', templateUrl: 'components/docs/docs.html', resolve: { methods: getMethods, links: getLinks } }) .when('/docs/:version/:module/:class', { controller: 'DocsCtrl', templateUrl: 'components/docs/docs.html', resolve: { methods: getMethods, links: getLinks } }); }) .run(function($location, $route, $rootScope, versions) { 'use strict'; $rootScope.$on('$routeChangeStart', function(event, route) { var url = $location.path(); if (url.indexOf('/docs/') === -1 || (!route.params || !route.params.version)) { // This isn't a `docs` route or it's not one that expects a version. // No need to re-direct request. return; } if (versions.indexOf(route.params.version) === -1) { // No version specified where one was expected. // Route to same url with latest version prepended. event.preventDefault(); $route.reload(); $location.path(url.replace('docs/', 'docs/' + versions[0] + '/')); } }); }) .controller('DocsCtrl', function($location, $scope, $routeParams, methods, $http, links, versions) { 'use strict'; $scope.isActiveUrl = function(url) { var active = $location.path() .replace('/' + methods.singleMethod, '') .replace('/' + $scope.version, ''); url = url.replace('#', '').replace('/' + $scope.version, ''); return active === url; }; $scope.isActiveDoc = function(doc) { return doc.toLowerCase() === $routeParams.module; }; $scope.pageTitle = 'Node.js'; $scope.showReference = true; $scope.activeUrl = '#' + $location.path(); $scope.singleMethod = methods.singleMethod; $scope.module = $routeParams.module; $scope.methods = methods; $scope.version = $routeParams.version; $scope.isLatestVersion = $scope.version == versions[0]; $scope.versions = versions; $scope.links = links; }) .controller('HistoryCtrl', function($scope, versions) { 'use strict'; $scope.pageTitle = 'Node.js Docs Versions'; $scope.showHistory = true; $scope.versions = versions; });
docs/components/docs/docs.js
angular .module('gcloud.docs', ['ngRoute', 'hljs', 'config']) .config(function($routeProvider, versions) { 'use strict'; function filterDocJson($sce, version) { // Transform JSON response to remove extraneous objects. function formatHtml(str) { return str .replace(/\s+/g, ' ') .replace(/<br *\/*>/g, ' ') .replace(/`([^`]*)`/g, '<code>$1</code>'); } function formatComments(str) { var matched = 0; var paragraphComments = /\/\/-+((\n|\r|.)*?(\/\/-))/g; if (!paragraphComments.test(str)) { return '<div hljs language="javascript">\n' + str + '</div>'; } str = str.replace(paragraphComments, function(match, block) { return '' + (++matched > 1 ? '</div>' : '') + '<p>' + formatHtml(detectLinks(detectModules( block.trim() .replace(/\/\/-*\s*/g, '\n') .replace(/\n\n/g, '\n') .replace(/(\w)\n(\w)/g, '$1 $2') .replace(/\n\n/g, '</p><p>') ))) + '</p>' + '<div hljs language="javascript">'; }); str = str.replace(/(<div[^>]*>)\n+/g, '$1\n'); str = str.replace(/\n<\/div>/g, '</div>'); return str; } function detectLinks(str) { var regex = { withCode: /{@linkcode <a href="([^\"]*)">([^<]*)<\/a>/g, withTitle: /\[([^\]]*)]{@link <a href="([^}]*)}">[^}]*}<\/a>/g, withoutTitle: /{@link <a href="([^}]*)}">[^}]*}<\/a>/g }; var a = document.createElement('a'); return str .replace(regex.withTitle, function(match, title, link) { a.href = link; a.innerText = title; return a.outerHTML; }) .replace(regex.withoutTitle, function(match, link) { a.href = link; a.innerText = link.replace(/^http\s*:\/\//, ''); return a.outerHTML; }) .replace(regex.withCode, function(match, link, text) { a.href = link; a.innerText = text; return '<code>' + a.outerHTML + '</code>'; }); } function detectModules(str) { var regex = { see: /{*module:([^}]*)}*/g }; var a = document.createElement('a'); return str.replace(regex.see, function(match, module) { var path = module; if (path.indexOf('#') > -1) { path = path.split('#').map(function(part, index, parts) { if (index < parts.length - 1) { return part + '/'; } else { return '?method=' + part; } }).join(''); } a.href = '#/docs/' + version + '/' + path; a.innerText = module; return a.outerHTML; }); } function reduceModules(acc, type, index, types) { var CUSTOM_TYPES = ['query', 'dataset', 'transaction']; if (CUSTOM_TYPES.indexOf(type.toLowerCase()) > -1) { if (types[index - 1]) { type = types[index - 1] + '/' + type; delete types[index - 1]; } } acc.push(detectModules(type)); return acc; } return function(data) { return data.data .filter(function(obj) { return obj.isPrivate === false && obj.ignore === false; }) .map(function(obj) { return { data: obj, name: obj.ctx.name, constructor: obj.tags.some(function(tag) { return tag.type === 'constructor'; }), mixes: obj.tags.filter(function(tag) { return tag.type === 'mixes'; }), description: $sce.trustAsHtml( formatHtml(detectLinks(detectModules(obj.description.full)))), params: obj.tags.filter(function(tag) { return tag.type === 'param'; }) .map(function(tag) { tag.description = $sce.trustAsHtml( formatHtml(tag.description.replace(/^- /, ''))); tag.types = $sce.trustAsHtml(tag.types.reduceRight( reduceModules, []).join(', ')); tag.optional = tag.types.toString().substr(-1) === '='; return tag; }), returns: obj.tags.filter(function(tag) { return tag.type === 'return'; }) .map(function(tag) { return $sce.trustAsHtml( tag.types.reduceRight(reduceModules, [])[0]); })[0], example: obj.tags.filter(function(tag) { return tag.type === 'example'; }) .map(function(tag) { return $sce.trustAsHtml(formatComments(tag.string)); })[0] }; }) .sort(function(a, b) { return a.constructor ? -1: a.name > b.name; }); }; } function getMixIns($sce, $q, $http, version, baseUrl) { return function(data) { var methodWithMixIns = data.filter(function(method) { return method.mixes; })[0]; if (!methodWithMixIns) { return data; } return $q .all(getMixInMethods(methodWithMixIns)) .then(combineMixInMethods(data)); }; function getMixInMethods(method) { return method.mixes.map(function (module) { module = module.string.trim().replace('module:', ''); return $http.get(baseUrl + '/' + module + '.json') .then(filterDocJson($sce, version)) .then(function(mixInData) { return mixInData.filter(function(method) { return !method.constructor; }); }); }); } function combineMixInMethods(data) { return function(mixInData) { return mixInData .reduce(function(acc, mixInMethods) { acc = acc.concat(mixInMethods); return acc; }, data) .sort(function(a, b) { return a.name > b.name; }); }; } } function setSingleMethod(method) { return function(methods) { if (method && methods.some(function(methodObj) { return methodObj.name === method; })) { methods.singleMethod = method; } return methods; }; } function getMethods($http, $route, $sce, $q, $location) { var version = $route.current.params.version; var module = $route.current.params.module; var cl = $route.current.params.class; var path = ['json', version]; if (!module && !cl) { path.push('index.json'); } else if (module && !cl) { path.push(module); path.push('index.json'); } else if (module && cl) { path.push(module); path.push(cl + '.json'); } return $http.get(path.join('/')) .then(filterDocJson($sce, version)) .then(getMixIns($sce, $q, $http, version, 'json/' + version)) .then(setSingleMethod($location.search().method)); } function getLinks($route, getLinks) { return getLinks($route.current.params.version); } $routeProvider .when('/docs', { redirectTo: '/docs/' + versions[0] }) .when('/docs/history', { controller: 'HistoryCtrl', templateUrl: 'components/docs/docs.html' }) .when('/docs/:version', { controller: 'DocsCtrl', templateUrl: 'components/docs/docs.html', resolve: { methods: getMethods, links: getLinks } }) .when('/docs/:version/:module', { controller: 'DocsCtrl', templateUrl: 'components/docs/docs.html', resolve: { methods: getMethods, links: getLinks } }) .when('/docs/:version/:module/:class', { controller: 'DocsCtrl', templateUrl: 'components/docs/docs.html', resolve: { methods: getMethods, links: getLinks } }); }) .run(function($location, $route, $rootScope, versions) { 'use strict'; $rootScope.$on('$routeChangeStart', function(event, route) { var url = $location.path(); if (url.indexOf('/docs/') === -1 || (!route.params || !route.params.version)) { // This isn't a `docs` route or it's not one that expects a version. // No need to re-direct request. return; } if (versions.indexOf(route.params.version) === -1) { // No version specified where one was expected. // Route to same url with latest version prepended. event.preventDefault(); $route.reload(); $location.path(url.replace('docs/', 'docs/' + versions[0] + '/')); } }); }) .controller('DocsCtrl', function($location, $scope, $routeParams, methods, $http, links, versions) { 'use strict'; $scope.isActiveUrl = function(url) { var active = $location.path() .replace('/' + methods.singleMethod, '') .replace('/' + $scope.version, ''); url = url.replace('#', '').replace('/' + $scope.version, ''); return active === url; }; $scope.isActiveDoc = function(doc) { return doc.toLowerCase() === $routeParams.module; }; $scope.pageTitle = 'Node.js'; $scope.showReference = true; $scope.activeUrl = '#' + $location.path(); $scope.singleMethod = methods.singleMethod; $scope.module = $routeParams.module; $scope.methods = methods; $scope.version = $routeParams.version; $scope.isLatestVersion = $scope.version == versions[0]; $scope.versions = versions; $scope.links = links; }) .controller('HistoryCtrl', function($scope, versions) { 'use strict'; $scope.pageTitle = 'Node.js Docs Versions'; $scope.showHistory = true; $scope.versions = versions; });
docs: fixes #260 - give method sorting preferential treatment to ctors
docs/components/docs/docs.js
docs: fixes #260 - give method sorting preferential treatment to ctors
<ide><path>ocs/components/docs/docs.js <ide> })[0] <ide> }; <ide> }) <del> .sort(function(a, b) { <del> return a.constructor ? -1: a.name > b.name; <del> }); <add> .sort(compareMethods); <ide> }; <ide> } <ide> <ide> acc = acc.concat(mixInMethods); <ide> return acc; <ide> }, data) <del> .sort(function(a, b) { <del> return a.name > b.name; <del> }); <add> .sort(compareMethods); <ide> }; <ide> } <ide> } <ide> .then(setSingleMethod($location.search().method)); <ide> } <ide> <add> function compareMethods(a, b) { <add> return a.constructor ? -1: a.name > b.name; <add> } <add> <ide> function getLinks($route, getLinks) { <ide> return getLinks($route.current.params.version); <ide> }
JavaScript
agpl-3.0
206a2ed7258b3a6042b7a3fe633765cbba1cc312
0
axelor/axelor-development-kit,axelor/axelor-development-kit,axelor/axelor-development-kit,axelor/axelor-development-kit
/* * Axelor Business Solutions * * Copyright (C) 2005-2016 Axelor (<http://axelor.com>). * * 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/>. */ (function(){ /* global d3: true, nv: true, D3Funnel: true, RadarChart: true, GaugeChart: true */ "use strict"; var ui = angular.module('axelor.ui'); ui.ChartCtrl = ChartCtrl; ui.ChartCtrl.$inject = ['$scope', '$element', '$http']; function ChartCtrl($scope, $element, $http) { var views = $scope._views; var view = $scope.view = views.chart; var viewChart = null; var searchScope = null; var loading = false; var unwatch = null; function refresh() { if (viewChart && searchScope && $scope.searchFields && !searchScope.isValid()) { return; } var context = $scope._context || {}; if ($scope.getContext) { context = _.extend({}, $scope.getContext(), context); if ($scope.onSave && !context.id) { // if embedded inside form view if (viewChart) { $scope.render(_.omit(viewChart, 'dataset')); } return; } } context = _.extend({}, context, (searchScope||{}).record, { _domainAction: $scope._viewAction }); loading = true; var params = { data: context }; if (viewChart) { params.fields = ['dataset']; } return $http.post('ws/meta/chart/' + view.name, params).then(function(response) { var res = response.data; var data = res.data; var isInitial = viewChart === null; if (viewChart === null) { viewChart = data; } else { data = _.extend({}, viewChart, data); } if ($scope.searchFields === undefined && data.search) { $scope.searchFields = data.search; $scope.searchInit = data.onInit; } else { $scope.render(data); if (isInitial) { refresh(); // force loading data } } loading = false; }, function () { loading = false; }); } $scope.setSearchScope = function (formScope) { searchScope = formScope; }; $scope.onRefresh = function(force) { if (unwatch || loading) { return; } // in case of onInit if ($scope.searchInit && !(searchScope||{}).record && !force) { return; } unwatch = $scope.$watch(function () { if ($element.is(":hidden")) { return; } unwatch(); unwatch = null; refresh(); }); }; $scope.render = function(data) { }; // refresh to load chart $scope.onRefresh(); } ChartFormCtrl.$inject = ['$scope', '$element', 'ViewService', 'DataSource']; function ChartFormCtrl($scope, $element, ViewService, DataSource) { $scope._dataSource = DataSource.create('com.axelor.meta.db.MetaView'); ui.FormViewCtrl.call(this, $scope, $element); $scope.setEditable(); $scope.setSearchScope($scope); function fixFields(fields) { _.each(fields, function(field){ if (field.type == 'reference') { field.type = 'MANY_TO_ONE'; field.canNew = false; field.canEdit = false; } if (field.type) field.type = field.type.toUpperCase(); else field.type = 'STRING'; }); return fields; } var unwatch = $scope.$watch('searchFields', function (fields) { if (!fields) { return; } unwatch(); var meta = { fields: fixFields(fields) }; var view = { type: 'form', items: [{ type: 'panel', noframe: true, items: _.map(meta.fields, function (item) { return _.extend({}, item, { showTitle: false, placeholder: item.title || item.autoTitle }); }) }] }; ViewService.process(meta, view); view.onLoad = $scope.searchInit; $scope.fields = meta.fields; $scope.schema = view; $scope.schema.loaded = true; var interval; function reload() { $scope.$parent.onRefresh(); $scope.applyLater(); } function delayedReload() { clearTimeout(interval); interval = setTimeout(reload, 500); } function onNewOrEdit() { if ($scope.$events.onLoad) { $scope.$events.onLoad().then(delayedReload); } } $scope.$on('on:new', onNewOrEdit); $scope.$on('on:edit', onNewOrEdit); $scope.$watch('record', function (record) { if (interval === undefined) { interval = null; return; } if ($scope.isValid()) delayedReload(); }, true); $scope.$watch('$events.onLoad', function (handler) { if (handler) { handler().then(delayedReload); } }); }); } function $conv(value) { if (!value) return 0; if (_.isNumber(value)) return value; if (/^(-)?\d+(\.\d+)?$/.test(value)) { return +value; } return value; } function applyXY(chart, data) { var type = data.xType; chart.y(function (d) { return d.y; }); if (type == "date") { return chart.x(function (d) { return moment(d.x).toDate(); }); } return chart.x(function (d) { return d.x; }); } var color_shades = [ d3.scale.category10().range(), // no shades d3.scale.category20().range(), // 2 shades d3.scale.category20b().range() // 4 shades ]; function colors(color, shades, type) { if (color) { var n = +(shades) || 4; var rest = color_shades[n-1]; return _.flatten(color.split(',').map(function (c) { return _.first(_.range(0, n + 1).map(d3.scale.linear().domain([0, n + 1]).range([c, 'white'])), n); }).concat(rest)); } return type == 'pie' ? d3.scale.category10().range() : d3.scale.category20().range(); } var CHARTS = {}; function PlusData(series, data) { var result = _.chain(data.dataset) .groupBy(data.xAxis) .map(function (group, name) { var value = 0; _.each(group, function (item) { value += $conv(item[series.key]); }); return { x: name, y: value }; }).value(); return result; } function PlotData(series, data) { var ticks = _.chain(data.dataset).pluck(data.xAxis).unique().value(); var groupBy = series.groupBy; var datum = []; _.chain(data.dataset).groupBy(groupBy) .map(function (group, groupName) { var name = groupBy ? groupName : null; var values = _.map(group, function (item) { var x = $conv(item[data.xAxis]) || 0; var y = $conv(item[series.key] || name || 0); return { x: x, y: y }; }); var my = _.pluck(values, 'x'); var missing = _.difference(ticks, my); if (ticks.length === missing.length) { return; } _.each(missing, function(x) { values.push({ x: x, y: 0 }); }); values = _.sortBy(values, 'x'); datum.push({ key: name || series.title, type: series.type, values: values }); }); return datum; } function PieChart(scope, element, data) { var series = _.first(data.series); var datum = PlusData(series, data); var config = data.config || {}; var chart = nv.models.pieChart() .showLabels(false) .height(null) .width(null) .x(function(d) { return d.x; }) .y(function(d) { return d.y; }); if (series.type === "donut") { chart.donut(true) .donutRatio(0.40); } if (_.toBoolean(config.percent)) { chart.showLabels(true) .labelType("percent") .labelThreshold(0.05); } d3.select(element[0]) .datum(datum) .transition().duration(1200).call(chart); return chart; } CHARTS.pie = PieChart; CHARTS.donut = PieChart; function DBarChart(scope, element, data) { var series = _.first(data.series); var datum = PlusData(series, data); datum = [{ key: data.title, values: datum }]; var chart = nv.models.discreteBarChart() .x(function(d) { return d.x; }) .y(function(d) { return d.y; }) .staggerLabels(true) .showValues(true); d3.select(element[0]) .datum(datum) .transition().duration(500).call(chart); return chart; } function BarChart(scope, element, data) { var series = _.first(data.series); var datum = PlotData(series, data); var chart = nv.models.multiBarChart() .reduceXTicks(false); chart.multibar.hideable(true); chart.stacked(data.stacked); d3.select(element[0]) .datum(datum) .transition().duration(500).call(chart); return chart; } function HBarChart(scope, element, data) { var series = _.first(data.series); var datum = PlotData(series, data); var chart = nv.models.multiBarHorizontalChart(); chart.stacked(data.stacked); d3.select(element[0]) .datum(datum) .transition().duration(500).call(chart); return chart; } function FunnelChart(scope, element, data) { if(!data.dataset){ return; } var chart = new D3Funnel(element[0]); var w = element.width(); var h = element.height(); var config = _.extend({}, data.config); var props = { fillType: 'gradient', hoverEffects: true, dynamicArea: true, animation: 200}; if(config.width){ props.width = w*config.width/100; } if(config.height){ props.height = h*config.height/100; } var series = _.first(data.series) || {}; var opts = []; _.each(data.dataset, function(dat){ opts.push([dat[data.xAxis],($conv(dat[series.key])||0)]); }); chart.draw(opts, props); chart.update = function(){}; return chart; } CHARTS.bar = BarChart; CHARTS.dbar = DBarChart; CHARTS.hbar = HBarChart; CHARTS.funnel = FunnelChart; function LineChart(scope, element, data) { var series = _.first(data.series); var datum = PlotData(series, data); var chart = nv.models.lineChart() .showLegend(true) .showYAxis(true) .showXAxis(true); applyXY(chart, data); d3.select(element[0]) .datum(datum) .transition().duration(500).call(chart); return chart; } function AreaChart(scope, element, data) { var series = _.first(data.series); var datum = PlotData(series, data); var chart = nv.models.stackedAreaChart(); applyXY(chart, data); d3.select(element[0]) .datum(datum) .transition().duration(500).call(chart); return chart; } CHARTS.line = LineChart; CHARTS.area = AreaChart; function RadarCharter(scope, element, data) { var result = _.map(data.dataset, function(item) { return _.map(data.series, function(s) { var title = s.title || s.key, value = item[s.key]; return { axis: title, value: $conv(value) || 0 }; }); }); var id = _.uniqueId('_radarChart'), parent = element.parent(); parent.attr('id', id) .addClass('radar-chart') .empty(); var size = Math.min(parent.innerWidth(), parent.innerHeight()); RadarChart.draw('#'+id, result, { w: size, h: size }); parent.children('svg') .css('width', 'auto') .css('margin', 'auto') .css('margin-top', 10); return null; } function GaugeCharter(scope, element, data) { var config = data.config, min = +(config.min) || 0, max = +(config.max) || 100, value = 0; var item = _.first(data.dataset), series = _.first(data.series), key = series.key || data.xAxis; if (item) { value = item[key] || value; } var w = element.width(); var h = element.height(); var parent = element.hide().parent(); parent.children('svg').remove(); parent.append(element); var chart = GaugeChart(parent[0], { size: 300, clipWidth: 300, clipHeight: h, ringWidth: 60, minValue: min, maxValue: max, transitionMs: 4000 }); chart.render(); chart.update(value); parent.children('svg:last') .css('display', 'block') .css('width', 'auto') .css('margin', 'auto') .css('margin-top', 0); } function TextChart(scope, element, data) { var config = _.extend({ strong: true, shadow: false, fontSize: 22 }, data.config); var values = _.first(data.dataset) || {}; var series = _.first(data.series) || {}; var value = values[series.key]; if (config.format) { value = _t(config.format, value); } var svg = d3.select(element.empty()[0]); var text = svg.append("svg:text") .attr("x", "50%") .attr("y", "50%") .attr("dy", ".3em") .attr("text-anchor", "middle") .text(value); if (config.color) text.attr("fill", config.color); if (config.fontSize) text.style("font-size", config.fontSize); if (_.toBoolean(config.strong)) text.style("font-weight", "bold"); if (_.toBoolean(config.shadow)) text.style("text-shadow", "0 1px 2px rgba(0, 0, 0, .5)"); } CHARTS.text = TextChart; CHARTS.radar = RadarCharter; CHARTS.gauge = GaugeCharter; function Chart(scope, element, data) { var type = null; var config = data.config || {}; for(var i = 0 ; i < data.series.length ; i++) { type = data.series[i].type; if (type === "bar" && !data.series[i].groupBy) type = "dbar"; if (type === "pie" || type === "dbar" || type === "radar" || type === "gauge") { break; } } if (type === "pie" && data.series.length > 1) { return; } if (type !== "radar" && data.series.length > 1) { type = "multi"; } element.off('adjustSize').empty(); nv.addGraph(function generate() { var noData = _t('No records found.'); if (data.dataset && data.dataset.stacktrace) { noData = data.dataset.message; data.dataset = []; } var maker = CHARTS[type] || CHARTS.bar || function () {}; var chart = maker(scope, element, data); if (!chart) { return; } if (chart.color) { chart.color(colors(config.colors, config.shades, type)); } if (chart.noData) { chart.noData(noData); } if(chart.controlLabels) { chart.controlLabels({ grouped: _t('Grouped'), stacked: _t('Stacked'), stream: _t('Stream'), expanded: _t('Expanded'), stack_percent: _t('Stack %') }); } var tickFormats = { "date" : function (d) { var f = config.xFormat; return moment(d).format(f || 'YYYY-MM-DD'); }, "month" : function(d) { var v = "" + d; var f = config.xFormat; if (v.indexOf(".") > -1) return ""; if (_.isString(d) && /^(\d+)$/.test(d)) { d = parseInt(d); } if (_.isNumber(d)) { return moment([moment().year(), d - 1, 1]).format(f || "MMM"); } if (_.isString(d) && d.indexOf('-') > 0) { return moment(d).format(f || 'MMM, YYYY'); } return d; }, "year" : function(d) { return moment([moment().year(), d - 1, 1]).format("YYYY"); }, "number": d3.format(',f'), "decimal": d3.format(',.1f'), "text": function(d) { return d; } }; var tickFormat = tickFormats[data.xType]; if (chart.xAxis && tickFormat) { chart.xAxis .rotateLabels(-45) .tickFormat(tickFormat); } if (chart.yAxis && data.yTitle) { chart.yAxis.axisLabel(data.yTitle); } var margin = null; ['top', 'left', 'bottom', 'right'].forEach(function (side) { var key = 'margin-' + side; var val = parseInt(config[key]); if (val) { (margin||(margin={}))[side] = val; } }); if (chart.margin && margin) { chart.margin(margin); } var lastWidth = 0; var lastHeight = 0; function adjust() { if (!element[0] || element.parent().is(":hidden")) { return; } var rect = element[0].getBoundingClientRect(); var w = rect.width, h = rect.height; if (w === lastWidth && h === lastHeight) { return; } lastWidth = w; lastHeight = h; chart.update(); } element.on('adjustSize', _.debounce(adjust, 100)); setTimeout(chart.update, 10); return chart; }); } var directiveFn = function(){ return { controller: ChartCtrl, link: function(scope, element, attrs) { var svg = element.children('svg'); var form = element.children('.chart-controls'); scope.render = function(data) { if (element.is(":hidden")) { return; } setTimeout(function () { svg.height(element.height() - form.height()).width('100%'); if (!scope.dashlet || !scope.dashlet.title) { scope.title = data.title; } Chart(scope, svg, data); return; }); }; function onNewOrEdit() { if (scope.searchInit && scope.searchFields) { return; } scope.onRefresh(true); } scope.$on('on:new', onNewOrEdit); scope.$on('on:edit', onNewOrEdit); }, replace: true, template: '<div class="chart-container" style="background-color: white; ">'+ '<div ui-chart-form></div>'+ '<svg></svg>'+ '</div>' }; }; ui.directive('uiChartForm', function () { return { scope: true, controller: ChartFormCtrl, link: function (scope, element, attrs, ctrls) { }, replace: true, template: "<div class='chart-controls'>" + "<div ui-view-form x-handler='this'></div>" + "</div>" }; }); ui.directive('uiViewChart', directiveFn); ui.directive('uiPortletChart', directiveFn); })();
axelor-web/src/main/webapp/js/view/view.chart.js
/* * Axelor Business Solutions * * Copyright (C) 2005-2016 Axelor (<http://axelor.com>). * * 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/>. */ (function(){ /* global d3: true, nv: true, D3Funnel: true, RadarChart: true, GaugeChart: true */ "use strict"; var ui = angular.module('axelor.ui'); ui.ChartCtrl = ChartCtrl; ui.ChartCtrl.$inject = ['$scope', '$element', '$http']; function ChartCtrl($scope, $element, $http) { var views = $scope._views; var view = $scope.view = views.chart; var viewChart = null; var searchScope = null; var loading = false; var unwatch = null; function refresh() { if (viewChart && searchScope && $scope.searchFields && !searchScope.isValid()) { return; } var context = $scope._context || {}; if ($scope.getContext) { context = _.extend({}, $scope.getContext(), context); if ($scope.onSave && !context.id) { // if embedded inside form view if (viewChart) { $scope.render(_.omit(viewChart, 'dataset')); } return; } } context = _.extend({}, context, (searchScope||{}).record, { _domainAction: $scope._viewAction }); loading = true; var params = { data: context }; if (viewChart) { params.fields = ['dataset']; } return $http.post('ws/meta/chart/' + view.name, params).then(function(response) { var res = response.data; var data = res.data; var isInitial = viewChart === null; if (viewChart === null) { viewChart = data; } else { data = _.extend({}, viewChart, data); } if ($scope.searchFields === undefined && data.search) { $scope.searchFields = data.search; $scope.searchInit = data.onInit; } else { $scope.render(data); if (isInitial) { refresh(); // force loading data } } loading = false; }, function () { loading = false; }); } $scope.setSearchScope = function (formScope) { searchScope = formScope; }; $scope.onRefresh = function(force) { if (unwatch || loading) { return; } // in case of onInit if ($scope.searchInit && !(searchScope||{}).record && !force) { return; } unwatch = $scope.$watch(function () { if ($element.is(":hidden")) { return; } unwatch(); unwatch = null; refresh(); }); }; $scope.render = function(data) { }; // refresh to load chart $scope.onRefresh(); } ChartFormCtrl.$inject = ['$scope', '$element', 'ViewService', 'DataSource']; function ChartFormCtrl($scope, $element, ViewService, DataSource) { $scope._dataSource = DataSource.create('com.axelor.meta.db.MetaView'); ui.FormViewCtrl.call(this, $scope, $element); $scope.setEditable(); $scope.setSearchScope($scope); function fixFields(fields) { _.each(fields, function(field){ if (field.type == 'reference') { field.type = 'MANY_TO_ONE'; field.canNew = false; field.canEdit = false; } if (field.type) field.type = field.type.toUpperCase(); else field.type = 'STRING'; }); return fields; } var unwatch = $scope.$watch('searchFields', function (fields) { if (!fields) { return; } unwatch(); var meta = { fields: fixFields(fields) }; var view = { type: 'form', items: [{ type: 'panel', noframe: true, items: _.map(meta.fields, function (item) { return _.extend({}, item, { showTitle: false, placeholder: item.title || item.autoTitle }); }) }] }; ViewService.process(meta, view); view.onLoad = $scope.searchInit; $scope.fields = meta.fields; $scope.schema = view; $scope.schema.loaded = true; var interval; function reload() { $scope.$parent.onRefresh(); $scope.applyLater(); } function delayedReload() { clearTimeout(interval); interval = setTimeout(reload, 500); } function onNewOrEdit() { if ($scope.$events.onLoad) { $scope.$events.onLoad().then(delayedReload); } } $scope.$on('on:new', onNewOrEdit); $scope.$on('on:edit', onNewOrEdit); $scope.$watch('record', function (record) { if (interval === undefined) { interval = null; return; } if ($scope.isValid()) delayedReload(); }, true); $scope.$watch('$events.onLoad', function (handler) { if (handler) { handler().then(delayedReload); } }); }); } function $conv(value) { if (!value) return 0; if (_.isNumber(value)) return value; if (/^(-)?\d+(\.\d+)?$/.test(value)) { return +value; } return value; } function applyXY(chart, data) { var type = data.xType; chart.y(function (d) { return d.y; }); if (type == "date") { return chart.x(function (d) { return moment(d.x).toDate(); }); } return chart.x(function (d) { return d.x; }); } var color_shades = [ d3.scale.category10().range(), // no shades d3.scale.category20().range(), // 2 shades d3.scale.category20b().range() // 4 shades ]; function colors(color, shades, type) { if (color) { var n = +(shades) || 4; var rest = color_shades[n-1]; return _.flatten(color.split(',').map(function (c) { return _.first(_.range(0, n + 1).map(d3.scale.linear().domain([0, n + 1]).range([c, 'white'])), n); }).concat(rest)); } return type == 'pie' ? d3.scale.category10().range() : d3.scale.category20().range(); } var CHARTS = {}; function PlusData(series, data) { var result = _.chain(data.dataset) .groupBy(data.xAxis) .map(function (group, name) { var value = 0; _.each(group, function (item) { value += $conv(item[series.key]); }); return { x: name, y: value }; }).value(); return result; } function PlotData(series, data) { var ticks = _.chain(data.dataset).pluck(data.xAxis).unique().value(); var groupBy = series.groupBy; var datum = []; _.chain(data.dataset).groupBy(groupBy) .map(function (group, groupName) { var name = groupBy ? groupName : null; var values = _.map(group, function (item) { var x = $conv(item[data.xAxis]) || 0; var y = $conv(item[series.key] || name || 0); return { x: x, y: y }; }); var my = _.pluck(values, 'x'); var missing = _.difference(ticks, my); if (ticks.length === missing.length) { return; } _.each(missing, function(x) { values.push({ x: x, y: 0 }); }); values = _.sortBy(values, 'x'); datum.push({ key: name || series.title, type: series.type, values: values }); }); return datum; } function PieChart(scope, element, data) { var series = _.first(data.series); var datum = PlusData(series, data); var config = data.config || {}; var chart = nv.models.pieChart() .showLabels(false) .height(null) .width(null) .x(function(d) { return d.x; }) .y(function(d) { return d.y; }); if (series.type === "donut") { chart.donut(true) .donutRatio(0.40); } if (_.toBoolean(config.percent)) { chart.showLabels(true) .labelType("percent") .labelThreshold(0.05); } d3.select(element[0]) .datum(datum) .transition().duration(1200).call(chart); return chart; } CHARTS.pie = PieChart; CHARTS.donut = PieChart; function DBarChart(scope, element, data) { var series = _.first(data.series); var datum = PlusData(series, data); datum = [{ key: data.title, values: datum }]; var chart = nv.models.discreteBarChart() .x(function(d) { return d.x; }) .y(function(d) { return d.y; }) .staggerLabels(true) .showValues(true); d3.select(element[0]) .datum(datum) .transition().duration(500).call(chart); return chart; } function BarChart(scope, element, data) { var series = _.first(data.series); var datum = PlotData(series, data); var chart = nv.models.multiBarChart() .reduceXTicks(false); chart.multibar.hideable(true); chart.stacked(data.stacked); d3.select(element[0]) .datum(datum) .transition().duration(500).call(chart); return chart; } function HBarChart(scope, element, data) { var series = _.first(data.series); var datum = PlotData(series, data); var chart = nv.models.multiBarHorizontalChart(); chart.stacked(data.stacked); d3.select(element[0]) .datum(datum) .transition().duration(500).call(chart); return chart; } function FunnelChart(scope, element, data) { if(!data.dataset){ return; } var chart = new D3Funnel(element[0]); var w = element.width(); var h = element.height(); var config = _.extend({}, data.config); var props = { fillType: 'gradient', hoverEffects: true, dynamicArea: true, animation: 200}; if(config.width){ props.width = w*config.width/100; } if(config.height){ props.height = h*config.height/100; } var series = _.first(data.series) || {}; var opts = []; _.each(data.dataset, function(dat){ opts.push([dat[data.xAxis],($conv(dat[series.key])||0)]); }); chart.draw(opts, props); chart.update = function(){}; return chart; } CHARTS.bar = BarChart; CHARTS.dbar = DBarChart; CHARTS.hbar = HBarChart; CHARTS.funnel = FunnelChart; function LineChart(scope, element, data) { var series = _.first(data.series); var datum = PlotData(series, data); var chart = nv.models.lineChart() .showLegend(true) .showYAxis(true) .showXAxis(true); applyXY(chart, data); d3.select(element[0]) .datum(datum) .transition().duration(500).call(chart); return chart; } function AreaChart(scope, element, data) { var series = _.first(data.series); var datum = PlotData(series, data); var chart = nv.models.stackedAreaChart(); applyXY(chart, data); d3.select(element[0]) .datum(datum) .transition().duration(500).call(chart); return chart; } CHARTS.line = LineChart; CHARTS.area = AreaChart; function RadarCharter(scope, element, data) { var result = _.map(data.dataset, function(item) { return _.map(data.series, function(s) { var title = s.title || s.key, value = item[s.key]; return { axis: title, value: $conv(value) || 0 }; }); }); var id = _.uniqueId('_radarChart'), parent = element.parent(); parent.attr('id', id) .addClass('radar-chart') .empty(); var size = Math.min(parent.innerWidth(), parent.innerHeight()); RadarChart.draw('#'+id, result, { w: size, h: size }); parent.children('svg') .css('width', 'auto') .css('margin', 'auto') .css('margin-top', 10); return null; } function GaugeCharter(scope, element, data) { var config = data.config, min = +(config.min) || 0, max = +(config.max) || 100, value = 0; var item = _.first(data.dataset), series = _.first(data.series), key = series.key || data.xAxis; if (item) { value = item[key] || value; } var w = element.width(); var h = element.height(); var parent = element.hide().parent(); parent.children('svg').remove(); parent.append(element); var chart = GaugeChart(parent[0], { size: 300, clipWidth: 300, clipHeight: h, ringWidth: 60, minValue: min, maxValue: max, transitionMs: 4000 }); chart.render(); chart.update(value); parent.children('svg:last') .css('display', 'block') .css('width', 'auto') .css('margin', 'auto') .css('margin-top', 0); } function TextChart(scope, element, data) { var config = _.extend({ strong: true, shadow: false, fontSize: 22 }, data.config); var values = _.first(data.dataset) || {}; var series = _.first(data.series) || {}; var value = values[series.key]; if (config.format) { value = _t(config.format, value); } var svg = d3.select(element.empty()[0]); var text = svg.append("svg:text") .attr("x", "50%") .attr("y", "50%") .attr("dy", ".3em") .attr("text-anchor", "middle") .text(value); if (config.color) text.attr("fill", config.color); if (config.fontSize) text.style("font-size", config.fontSize); if (_.toBoolean(config.strong)) text.style("font-weight", "bold"); if (_.toBoolean(config.shadow)) text.style("text-shadow", "0 1px 2px rgba(0, 0, 0, .5)"); } CHARTS.text = TextChart; CHARTS.radar = RadarCharter; CHARTS.gauge = GaugeCharter; function Chart(scope, element, data) { var type = null; var config = data.config || {}; for(var i = 0 ; i < data.series.length ; i++) { type = data.series[i].type; if (type === "bar" && !data.series[i].groupBy) type = "dbar"; if (type === "pie" || type === "dbar" || type === "radar" || type === "gauge") { break; } } if (type === "pie" && data.series.length > 1) { return; } if (type !== "radar" && data.series.length > 1) { type = "multi"; } element.off('adjustSize').empty(); nv.addGraph(function generate() { var noData = _t('No records found.'); if (data.dataset && data.dataset.stacktrace) { noData = data.dataset.message; data.dataset = []; } var maker = CHARTS[type] || CHARTS.bar || function () {}; var chart = maker(scope, element, data); if (!chart) { return; } if (chart.color) { chart.color(colors(config.colors, config.shades, type)); } if (chart.noData) { chart.noData(noData); } if(chart.controlLabels) { chart.controlLabels({ grouped: _t('Grouped'), stacked: _t('Stacked'), stream: _t('Stream'), expanded: _t('Expanded'), stack_percent: _t('Stack %') }); } var tickFormats = { "date" : function (d) { var f = config.xFormat; return moment(d).format(f || 'YYYY-MM-DD'); }, "month" : function(d) { var v = "" + d; var f = config.xFormat; if (v.indexOf(".") > -1) return ""; if (_.isString(d) && /^(\d+)$/.test(d)) { d = parseInt(d); } if (_.isNumber(d)) { return moment([moment().year(), d - 1, 1]).format(f || "MMM"); } if (_.isString(d) && d.indexOf('-') > 0) { return moment(d).format(f || 'MMM, YYYY'); } return d; }, "year" : function(d) { return moment([moment().year(), d - 1, 1]).format("YYYY"); }, "number": d3.format(',f'), "decimal": d3.format(',.1f'), "text": function(d) { return d; } }; var tickFormat = tickFormats[data.xType]; if (chart.xAxis && tickFormat) { chart.xAxis .rotateLabels(-45) .tickFormat(tickFormat); } if (chart.yAxis && data.yTitle) { chart.yAxis.axisLabel(data.yTitle); } var margin = null; ['top', 'left', 'bottom', 'right'].forEach(function (side) { var key = 'margin-' + side; var val = parseInt(config[key]); if (val) { (margin||(margin={}))[side] = val; } }); if (chart.margin && margin) { chart.margin(margin); } var lastWidth = 0; var lastHeight = 0; function adjust() { if (!element[0] || element.parent().is(":hidden")) { return; } var rect = element[0].getBoundingClientRect(); var w = rect.width, h = rect.height; if (w === lastWidth && h === lastHeight) { return; } lastWidth = w; lastHeight = h; chart.update(); } element.on('adjustSize', _.debounce(adjust, 100)); setTimeout(chart.update, 10); return chart; }); } var directiveFn = function(){ return { controller: ChartCtrl, link: function(scope, element, attrs) { var svg = element.children('svg'); var form = element.children('.chart-controls'); scope.render = function(data) { if (element.is(":hidden")) { return; } setTimeout(function () { svg.height(element.height() - form.height()).width('100%'); scope.title = data.title; Chart(scope, svg, data); return; }); }; function onNewOrEdit() { if (scope.searchInit && scope.searchFields) { return; } scope.onRefresh(true); } scope.$on('on:new', onNewOrEdit); scope.$on('on:edit', onNewOrEdit); }, replace: true, template: '<div class="chart-container" style="background-color: white; ">'+ '<div ui-chart-form></div>'+ '<svg></svg>'+ '</div>' }; }; ui.directive('uiChartForm', function () { return { scope: true, controller: ChartFormCtrl, link: function (scope, element, attrs, ctrls) { }, replace: true, template: "<div class='chart-controls'>" + "<div ui-view-form x-handler='this'></div>" + "</div>" }; }); ui.directive('uiViewChart', directiveFn); ui.directive('uiPortletChart', directiveFn); })();
Don't update chat dashlet title if provided Fixes RM-5538
axelor-web/src/main/webapp/js/view/view.chart.js
Don't update chat dashlet title if provided
<ide><path>xelor-web/src/main/webapp/js/view/view.chart.js <ide> } <ide> setTimeout(function () { <ide> svg.height(element.height() - form.height()).width('100%'); <del> scope.title = data.title; <add> if (!scope.dashlet || !scope.dashlet.title) { <add> scope.title = data.title; <add> } <ide> Chart(scope, svg, data); <ide> return; <ide> });
Java
apache-2.0
8a88b5b27648e2aad515beeb5a8779547b8144ce
0
bladecoder/bladecoder-adventure-engine,bladecoder/bladecoder-adventure-engine
/******************************************************************************* * Copyright 2014 Rafael Garcia Moreno. * * 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.bladecoder.engineeditor.scneditor; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Container; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.utils.Array; import com.bladecoder.engine.util.Config; import com.bladecoder.engine.util.DPIUtils; import com.bladecoder.engineeditor.Ctx; import com.bladecoder.engineeditor.common.EditorLogger; import com.bladecoder.engineeditor.common.I18NUtils; import com.bladecoder.engineeditor.common.ImageUtils; import com.bladecoder.engineeditor.common.Message; import com.bladecoder.engineeditor.common.ModelTools; import com.bladecoder.engineeditor.common.RunProccess; import com.bladecoder.engineeditor.model.Project; import com.kotcrab.vis.ui.widget.file.FileChooser; import com.kotcrab.vis.ui.widget.file.FileChooser.Mode; import com.kotcrab.vis.ui.widget.file.FileChooser.SelectionMode; import com.kotcrab.vis.ui.widget.file.FileChooser.ViewMode; import com.kotcrab.vis.ui.widget.file.FileChooserListener; public class ToolsWindow extends Container<Table> { ScnWidget scnWidget; com.bladecoder.engine.model.BaseActor actor; public ToolsWindow(Skin skin, ScnWidget sw) { scnWidget = sw; Table table = new Table(skin); TextButton tmpButton = new TextButton("Temporal tool", skin, "no-toggled"); TextButton testOnAndroidButton = new TextButton("Test on Android device", skin, "no-toggled"); TextButton testOnIphoneEmulatorButton = new TextButton("Test on Iphone emulator", skin, "no-toggled"); TextButton testOnIpadEmulatorButton = new TextButton("Test on Ipad emulator", skin, "no-toggled"); TextButton testOnIOSDeviceButton = new TextButton("Test on IOS device", skin, "no-toggled"); TextButton exportTSVButton = new TextButton("I18N - Export texts as .tsv", skin, "no-toggled"); TextButton importTSVButton = new TextButton("I18N - Import.tsv file", skin, "no-toggled"); TextButton exportUIImages = new TextButton("Export UI Images", skin, "no-toggled"); TextButton createUIAtlas = new TextButton("Create UI Atlas", skin, "no-toggled"); TextButton particleEditor = new TextButton("Particle Editor", skin, "no-toggled"); table.defaults().left().expandX(); table.top().pad(DPIUtils.getSpacing() / 2); table.add(new Label("Tools", skin, "big")).center(); Drawable drawable = skin.getDrawable("trans"); setBackground(drawable); table.row(); table.add(testOnAndroidButton).expandX().fill(); table.row(); table.add(testOnIphoneEmulatorButton).expandX().fill(); table.row(); table.add(testOnIpadEmulatorButton).expandX().fill(); table.row(); table.add(testOnIOSDeviceButton).expandX().fill(); // disable if not mac if (!System.getProperty("os.name").toLowerCase().contains("mac")) { testOnIphoneEmulatorButton.setDisabled(true); testOnIpadEmulatorButton.setDisabled(true); testOnIOSDeviceButton.setDisabled(true); } table.row(); table.add(exportTSVButton).expandX().fill(); table.row(); table.add(importTSVButton).expandX().fill(); table.row(); table.add(exportUIImages).expandX().fill(); table.row(); table.add(createUIAtlas).expandX().fill(); table.row(); table.add(particleEditor).expandX().fill(); // table.row(); // table.add(tmpButton).expandX().fill(); // ADD CUTMODE FOR VERBS THAT ONLY HAVE A LOOKAT OR SAY ACTION tmpButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { ModelTools.fixSaySubtitleActor(); Message.showMsg(getStage(), "TOOL PROCESSED", 4); } }); // TEST ON ANDROID DEVICE testOnAndroidButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { testOnAndroid(); } }); testOnIphoneEmulatorButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { testOnIphoneEmulator(); } }); testOnIpadEmulatorButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { testOnIpadEmulator(); } }); testOnIOSDeviceButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { testOnIOSDevice(); } }); exportTSVButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { exportTSV(); } }); importTSVButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { importTSV(); } }); exportUIImages.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { exportUIImages(); } }); createUIAtlas.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { createUIAtlas(); } }); particleEditor.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { particleEditor(); } }); table.pack(); setActor(table); prefSize(table.getWidth(), Math.max(200, table.getHeight())); setSize(table.getWidth(), Math.max(200, table.getHeight())); } protected void createUIAtlas() { FileChooser fileChooser = new FileChooser(Mode.OPEN); fileChooser.setSize(Gdx.graphics.getWidth() * 0.7f, Gdx.graphics.getHeight() * 0.7f); fileChooser.setViewMode(ViewMode.LIST); fileChooser.setSelectionMode(SelectionMode.DIRECTORIES); getStage().addActor(fileChooser); fileChooser.setListener(new FileChooserListener() { @Override public void selected(Array<FileHandle> files) { // fileChooser.setTitle("Select the file to export the project // texts"); // ImageUtils.createAtlas(files.get(0).file().getAbsolutePath(), // Ctx.project.getProjectPath() + "/" + Project.UI_PATH + "/1/", // "ui", 1, TextureFilter.Linear, // TextureFilter.Nearest); List<String> res = Ctx.project.getResolutions(); for (String r : res) { float scale = Float.parseFloat(r); try { ImageUtils.createAtlas(files.get(0).file().getAbsolutePath(), Ctx.project.getProjectPath() + "/" + Project.UI_PATH + "/" + r, "ui" + ".atlas", scale, TextureFilter.Linear, TextureFilter.Nearest); } catch (IOException e) { EditorLogger.error(e.getMessage()); Message.showMsgDialog(getStage(), "Error creating atlas", e.getMessage()); return; } } Message.showMsg(getStage(), "UI Atlas created sucessfully.", 4); } @Override public void canceled() { } }); } protected void exportUIImages() { FileChooser fileChooser = new FileChooser(Mode.OPEN); fileChooser.setSize(Gdx.graphics.getWidth() * 0.7f, Gdx.graphics.getHeight() * 0.7f); fileChooser.setViewMode(ViewMode.LIST); fileChooser.setSelectionMode(SelectionMode.DIRECTORIES); getStage().addActor(fileChooser); fileChooser.setListener(new FileChooserListener() { @Override public void selected(Array<FileHandle> files) { try { // fileChooser.setTitle("Select the file to export the // project texts"); ImageUtils.unpackAtlas( new File(Ctx.project.getProjectPath() + "/" + Project.UI_PATH + "/1/ui.atlas"), files.get(0).file()); Message.showMsg(getStage(), "UI Atlas images exported sucessfully.", 4); } catch (Exception e) { Message.showMsg(getStage(), "There was a problem exporting images from UI Atlas.", 4); EditorLogger.printStackTrace(e); } } @Override public void canceled() { } }); } private void exportTSV() { FileChooser fileChooser = new FileChooser(Mode.SAVE); fileChooser.setSize(Gdx.graphics.getWidth() * 0.7f, Gdx.graphics.getHeight() * 0.7f); fileChooser.setViewMode(ViewMode.LIST); fileChooser.setSelectionMode(SelectionMode.FILES); getStage().addActor(fileChooser); fileChooser.setListener(new FileChooserListener() { @Override public void selected(Array<FileHandle> files) { try { // fileChooser.setTitle("Select the file to export the // project texts"); I18NUtils.exportTSV(Ctx.project.getProjectDir().getAbsolutePath(), files.get(0).file().getAbsolutePath(), Ctx.project.getChapter().getId(), "default"); Message.showMsg(getStage(), files.get(0).file().getName() + " exported sucessfully.", 4); } catch (IOException e) { Message.showMsg(getStage(), "There was a problem generating the .tsv file.", 4); EditorLogger.printStackTrace(e); } } @Override public void canceled() { } }); } private void importTSV() { FileChooser fileChooser = new FileChooser(Mode.OPEN); fileChooser.setSize(Gdx.graphics.getWidth() * 0.7f, Gdx.graphics.getHeight() * 0.7f); fileChooser.setViewMode(ViewMode.LIST); fileChooser.setSelectionMode(SelectionMode.FILES); getStage().addActor(fileChooser); fileChooser.setListener(new FileChooserListener() { @Override public void selected(Array<FileHandle> files) { try { // chooser.setTitle("Select the .tsv file to import"); I18NUtils.importTSV(Ctx.project.getProjectDir().getAbsolutePath(), files.get(0).file().getAbsolutePath(), Ctx.project.getChapter().getId(), "default"); // Reload texts Ctx.project.getI18N().load(Ctx.project.getChapter().getId()); Message.showMsg(getStage(), files.get(0).file().getName() + " imported sucessfully.", 4); } catch (IOException e) { Message.showMsg(getStage(), "There was a problem importing the .tsv file.", 4); EditorLogger.printStackTrace(e); } } @Override public void canceled() { } }); } private void testOnAndroid() { if (Ctx.project.getSelectedScene() == null) { String msg = "There are no scenes in this chapter."; Message.showMsg(getStage(), msg, 3); return; } Ctx.project.getProjectConfig().setProperty(Config.CHAPTER_PROP, Ctx.project.getChapter().getId()); Ctx.project.getProjectConfig().setProperty(Config.TEST_SCENE_PROP, Ctx.project.getSelectedScene().getId()); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); Message.showMsgDialog(getStage(), "Error", msg); return; } new Thread(new Runnable() { Stage stage = getStage(); @Override public void run() { Message.showMsg(stage, "Running scene on Android device...", 5); if (!RunProccess.runGradle(Ctx.project.getProjectDir(), "android:uninstallDebug android:installDebug android:run")) { Message.showMsg(stage, "There was a problem running the project", 4); } Ctx.project.getProjectConfig().remove(Config.CHAPTER_PROP); Ctx.project.getProjectConfig().remove(Config.TEST_SCENE_PROP); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); EditorLogger.error(msg); return; } } }).start(); } private void testOnIphoneEmulator() { if (Ctx.project.getSelectedScene() == null) { String msg = "There are no scenes in this chapter."; Message.showMsg(getStage(), msg, 3); return; } Ctx.project.getProjectConfig().setProperty(Config.CHAPTER_PROP, Ctx.project.getChapter().getId()); Ctx.project.getProjectConfig().setProperty(Config.TEST_SCENE_PROP, Ctx.project.getSelectedScene().getId()); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); Message.showMsgDialog(getStage(), "Error", msg); return; } new Thread(new Runnable() { Stage stage = getStage(); @Override public void run() { Message.showMsg(stage, "Running scene on Iphone emulator...", 5); if (!RunProccess.runGradle(Ctx.project.getProjectDir(), "ios:launchIPhoneSimulator")) { Message.showMsg(stage, "There was a problem running the project", 4); } Ctx.project.getProjectConfig().remove(Config.CHAPTER_PROP); Ctx.project.getProjectConfig().remove(Config.TEST_SCENE_PROP); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); EditorLogger.error(msg); return; } } }).start(); } private void testOnIpadEmulator() { if (Ctx.project.getSelectedScene() == null) { String msg = "There are no scenes in this chapter."; Message.showMsg(getStage(), msg, 3); return; } Ctx.project.getProjectConfig().setProperty(Config.CHAPTER_PROP, Ctx.project.getChapter().getId()); Ctx.project.getProjectConfig().setProperty(Config.TEST_SCENE_PROP, Ctx.project.getSelectedScene().getId()); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); Message.showMsgDialog(getStage(), "Error", msg); return; } new Thread(new Runnable() { Stage stage = getStage(); @Override public void run() { Message.showMsg(stage, "Running scene on Ipad simulator...", 5); if (!RunProccess.runGradle(Ctx.project.getProjectDir(), "ios:launchIPadSimulator")) { Message.showMsg(stage, "There was a problem running the project", 4); } Ctx.project.getProjectConfig().remove(Config.CHAPTER_PROP); Ctx.project.getProjectConfig().remove(Config.TEST_SCENE_PROP); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); EditorLogger.error(msg); return; } } }).start(); } private void testOnIOSDevice() { if (Ctx.project.getSelectedScene() == null) { String msg = "There are no scenes in this chapter."; Message.showMsg(getStage(), msg, 3); return; } Ctx.project.getProjectConfig().setProperty(Config.CHAPTER_PROP, Ctx.project.getChapter().getId()); Ctx.project.getProjectConfig().setProperty(Config.TEST_SCENE_PROP, Ctx.project.getSelectedScene().getId()); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); Message.showMsgDialog(getStage(), "Error", msg); return; } new Thread(new Runnable() { Stage stage = getStage(); @Override public void run() { Message.showMsg(stage, "Running scene on IOS device...", 5); if (!RunProccess.runGradle(Ctx.project.getProjectDir(), "ios:launchIOSDevice")) { Message.showMsg(stage, "There was a problem running the project", 4); } Ctx.project.getProjectConfig().remove(Config.CHAPTER_PROP); Ctx.project.getProjectConfig().remove(Config.TEST_SCENE_PROP); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); EditorLogger.error(msg); return; } } }).start(); } private void particleEditor() { // Open the particle editor List<String> cp = new ArrayList<String>(); cp.add(System.getProperty("java.class.path")); try { RunProccess.runJavaProccess("com.badlogic.gdx.tools.particleeditor.ParticleEditor", cp, null); } catch (IOException e) { Message.showMsgDialog(getStage(), "Error", "Error launching Particle Editor."); EditorLogger.printStackTrace(e); } } }
adventure-editor/src/main/java/com/bladecoder/engineeditor/scneditor/ToolsWindow.java
/******************************************************************************* * Copyright 2014 Rafael Garcia Moreno. * * 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.bladecoder.engineeditor.scneditor; import java.io.File; import java.io.IOException; import java.util.List; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Container; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.utils.Array; import com.bladecoder.engine.util.Config; import com.bladecoder.engine.util.DPIUtils; import com.bladecoder.engineeditor.Ctx; import com.bladecoder.engineeditor.common.EditorLogger; import com.bladecoder.engineeditor.common.I18NUtils; import com.bladecoder.engineeditor.common.ImageUtils; import com.bladecoder.engineeditor.common.Message; import com.bladecoder.engineeditor.common.ModelTools; import com.bladecoder.engineeditor.common.RunProccess; import com.bladecoder.engineeditor.model.Project; import com.kotcrab.vis.ui.widget.file.FileChooser; import com.kotcrab.vis.ui.widget.file.FileChooser.Mode; import com.kotcrab.vis.ui.widget.file.FileChooser.SelectionMode; import com.kotcrab.vis.ui.widget.file.FileChooser.ViewMode; import com.kotcrab.vis.ui.widget.file.FileChooserListener; public class ToolsWindow extends Container<Table> { ScnWidget scnWidget; com.bladecoder.engine.model.BaseActor actor; public ToolsWindow(Skin skin, ScnWidget sw) { scnWidget = sw; Table table = new Table(skin); TextButton tmpButton = new TextButton("Temporal tool", skin, "no-toggled"); TextButton testOnAndroidButton = new TextButton("Test on Android device", skin, "no-toggled"); TextButton testOnIphoneEmulatorButton = new TextButton("Test on Iphone emulator", skin, "no-toggled"); TextButton testOnIpadEmulatorButton = new TextButton("Test on Ipad emulator", skin, "no-toggled"); TextButton testOnIOSDeviceButton = new TextButton("Test on IOS device", skin, "no-toggled"); TextButton exportTSVButton = new TextButton("I18N - Export texts as .tsv", skin, "no-toggled"); TextButton importTSVButton = new TextButton("I18N - Import.tsv file", skin, "no-toggled"); TextButton exportUIImages = new TextButton("Export UI Images", skin, "no-toggled"); TextButton createUIAtlas = new TextButton("Create UI Atlas", skin, "no-toggled"); table.defaults().left().expandX(); table.top().pad(DPIUtils.getSpacing() / 2); table.add(new Label("Tools", skin, "big")).center(); Drawable drawable = skin.getDrawable("trans"); setBackground(drawable); table.row(); table.add(testOnAndroidButton).expandX().fill(); table.row(); table.add(testOnIphoneEmulatorButton).expandX().fill(); table.row(); table.add(testOnIpadEmulatorButton).expandX().fill(); table.row(); table.add(testOnIOSDeviceButton).expandX().fill(); // disable if not mac if (!System.getProperty("os.name").toLowerCase().contains("mac")) { testOnIphoneEmulatorButton.setDisabled(true); testOnIpadEmulatorButton.setDisabled(true); testOnIOSDeviceButton.setDisabled(true); } table.row(); table.add(exportTSVButton).expandX().fill(); table.row(); table.add(importTSVButton).expandX().fill(); table.row(); table.add(exportUIImages).expandX().fill(); table.row(); table.add(createUIAtlas).expandX().fill(); // table.row(); // table.add(tmpButton).expandX().fill(); // ADD CUTMODE FOR VERBS THAT ONLY HAVE A LOOKAT OR SAY ACTION tmpButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { ModelTools.fixSaySubtitleActor(); Message.showMsg(getStage(), "TOOL PROCESSED", 4); } }); // TEST ON ANDROID DEVICE testOnAndroidButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { testOnAndroid(); } }); testOnIphoneEmulatorButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { testOnIphoneEmulator(); } }); testOnIpadEmulatorButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { testOnIpadEmulator(); } }); testOnIOSDeviceButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { testOnIOSDevice(); } }); exportTSVButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { exportTSV(); } }); importTSVButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { importTSV(); } }); exportUIImages.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { exportUIImages(); } }); createUIAtlas.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { createUIAtlas(); } }); table.pack(); setActor(table); prefSize(table.getWidth(), Math.max(200, table.getHeight())); setSize(table.getWidth(), Math.max(200, table.getHeight())); } protected void createUIAtlas() { FileChooser fileChooser = new FileChooser(Mode.OPEN); fileChooser.setSize(Gdx.graphics.getWidth() * 0.7f, Gdx.graphics.getHeight() * 0.7f); fileChooser.setViewMode(ViewMode.LIST); fileChooser.setSelectionMode(SelectionMode.DIRECTORIES); getStage().addActor(fileChooser); fileChooser.setListener(new FileChooserListener() { @Override public void selected(Array<FileHandle> files) { // fileChooser.setTitle("Select the file to export the project // texts"); // ImageUtils.createAtlas(files.get(0).file().getAbsolutePath(), // Ctx.project.getProjectPath() + "/" + Project.UI_PATH + "/1/", // "ui", 1, TextureFilter.Linear, // TextureFilter.Nearest); List<String> res = Ctx.project.getResolutions(); for (String r : res) { float scale = Float.parseFloat(r); try { ImageUtils.createAtlas(files.get(0).file().getAbsolutePath(), Ctx.project.getProjectPath() + "/" + Project.UI_PATH + "/" + r, "ui" + ".atlas", scale, TextureFilter.Linear, TextureFilter.Nearest); } catch (IOException e) { EditorLogger.error(e.getMessage()); Message.showMsgDialog(getStage(), "Error creating atlas", e.getMessage()); return; } } Message.showMsg(getStage(), "UI Atlas created sucessfully.", 4); } @Override public void canceled() { } }); } protected void exportUIImages() { FileChooser fileChooser = new FileChooser(Mode.OPEN); fileChooser.setSize(Gdx.graphics.getWidth() * 0.7f, Gdx.graphics.getHeight() * 0.7f); fileChooser.setViewMode(ViewMode.LIST); fileChooser.setSelectionMode(SelectionMode.DIRECTORIES); getStage().addActor(fileChooser); fileChooser.setListener(new FileChooserListener() { @Override public void selected(Array<FileHandle> files) { try { // fileChooser.setTitle("Select the file to export the // project texts"); ImageUtils.unpackAtlas( new File(Ctx.project.getProjectPath() + "/" + Project.UI_PATH + "/1/ui.atlas"), files.get(0).file()); Message.showMsg(getStage(), "UI Atlas images exported sucessfully.", 4); } catch (Exception e) { Message.showMsg(getStage(), "There was a problem exporting images from UI Atlas.", 4); EditorLogger.printStackTrace(e); } } @Override public void canceled() { } }); } private void exportTSV() { FileChooser fileChooser = new FileChooser(Mode.SAVE); fileChooser.setSize(Gdx.graphics.getWidth() * 0.7f, Gdx.graphics.getHeight() * 0.7f); fileChooser.setViewMode(ViewMode.LIST); fileChooser.setSelectionMode(SelectionMode.FILES); getStage().addActor(fileChooser); fileChooser.setListener(new FileChooserListener() { @Override public void selected(Array<FileHandle> files) { try { // fileChooser.setTitle("Select the file to export the // project texts"); I18NUtils.exportTSV(Ctx.project.getProjectDir().getAbsolutePath(), files.get(0).file().getAbsolutePath(), Ctx.project.getChapter().getId(), "default"); Message.showMsg(getStage(), files.get(0).file().getName() + " exported sucessfully.", 4); } catch (IOException e) { Message.showMsg(getStage(), "There was a problem generating the .tsv file.", 4); EditorLogger.printStackTrace(e); } } @Override public void canceled() { } }); } private void importTSV() { FileChooser fileChooser = new FileChooser(Mode.OPEN); fileChooser.setSize(Gdx.graphics.getWidth() * 0.7f, Gdx.graphics.getHeight() * 0.7f); fileChooser.setViewMode(ViewMode.LIST); fileChooser.setSelectionMode(SelectionMode.FILES); getStage().addActor(fileChooser); fileChooser.setListener(new FileChooserListener() { @Override public void selected(Array<FileHandle> files) { try { // chooser.setTitle("Select the .tsv file to import"); I18NUtils.importTSV(Ctx.project.getProjectDir().getAbsolutePath(), files.get(0).file().getAbsolutePath(), Ctx.project.getChapter().getId(), "default"); // Reload texts Ctx.project.getI18N().load(Ctx.project.getChapter().getId()); Message.showMsg(getStage(), files.get(0).file().getName() + " imported sucessfully.", 4); } catch (IOException e) { Message.showMsg(getStage(), "There was a problem importing the .tsv file.", 4); EditorLogger.printStackTrace(e); } } @Override public void canceled() { } }); } private void testOnAndroid() { if (Ctx.project.getSelectedScene() == null) { String msg = "There are no scenes in this chapter."; Message.showMsg(getStage(), msg, 3); return; } Ctx.project.getProjectConfig().setProperty(Config.CHAPTER_PROP, Ctx.project.getChapter().getId()); Ctx.project.getProjectConfig().setProperty(Config.TEST_SCENE_PROP, Ctx.project.getSelectedScene().getId()); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); Message.showMsgDialog(getStage(), "Error", msg); return; } new Thread(new Runnable() { Stage stage = getStage(); @Override public void run() { Message.showMsg(stage, "Running scene on Android device...", 5); if (!RunProccess.runGradle(Ctx.project.getProjectDir(), "android:uninstallDebug android:installDebug android:run")) { Message.showMsg(stage, "There was a problem running the project", 4); } Ctx.project.getProjectConfig().remove(Config.CHAPTER_PROP); Ctx.project.getProjectConfig().remove(Config.TEST_SCENE_PROP); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); EditorLogger.error(msg); return; } } }).start(); } private void testOnIphoneEmulator() { if (Ctx.project.getSelectedScene() == null) { String msg = "There are no scenes in this chapter."; Message.showMsg(getStage(), msg, 3); return; } Ctx.project.getProjectConfig().setProperty(Config.CHAPTER_PROP, Ctx.project.getChapter().getId()); Ctx.project.getProjectConfig().setProperty(Config.TEST_SCENE_PROP, Ctx.project.getSelectedScene().getId()); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); Message.showMsgDialog(getStage(), "Error", msg); return; } new Thread(new Runnable() { Stage stage = getStage(); @Override public void run() { Message.showMsg(stage, "Running scene on Iphone emulator...", 5); if (!RunProccess.runGradle(Ctx.project.getProjectDir(), "ios:launchIPhoneSimulator")) { Message.showMsg(stage, "There was a problem running the project", 4); } Ctx.project.getProjectConfig().remove(Config.CHAPTER_PROP); Ctx.project.getProjectConfig().remove(Config.TEST_SCENE_PROP); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); EditorLogger.error(msg); return; } } }).start(); } private void testOnIpadEmulator() { if (Ctx.project.getSelectedScene() == null) { String msg = "There are no scenes in this chapter."; Message.showMsg(getStage(), msg, 3); return; } Ctx.project.getProjectConfig().setProperty(Config.CHAPTER_PROP, Ctx.project.getChapter().getId()); Ctx.project.getProjectConfig().setProperty(Config.TEST_SCENE_PROP, Ctx.project.getSelectedScene().getId()); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); Message.showMsgDialog(getStage(), "Error", msg); return; } new Thread(new Runnable() { Stage stage = getStage(); @Override public void run() { Message.showMsg(stage, "Running scene on Ipad simulator...", 5); if (!RunProccess.runGradle(Ctx.project.getProjectDir(), "ios:launchIPadSimulator")) { Message.showMsg(stage, "There was a problem running the project", 4); } Ctx.project.getProjectConfig().remove(Config.CHAPTER_PROP); Ctx.project.getProjectConfig().remove(Config.TEST_SCENE_PROP); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); EditorLogger.error(msg); return; } } }).start(); } private void testOnIOSDevice() { if (Ctx.project.getSelectedScene() == null) { String msg = "There are no scenes in this chapter."; Message.showMsg(getStage(), msg, 3); return; } Ctx.project.getProjectConfig().setProperty(Config.CHAPTER_PROP, Ctx.project.getChapter().getId()); Ctx.project.getProjectConfig().setProperty(Config.TEST_SCENE_PROP, Ctx.project.getSelectedScene().getId()); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); Message.showMsgDialog(getStage(), "Error", msg); return; } new Thread(new Runnable() { Stage stage = getStage(); @Override public void run() { Message.showMsg(stage, "Running scene on IOS device...", 5); if (!RunProccess.runGradle(Ctx.project.getProjectDir(), "ios:launchIOSDevice")) { Message.showMsg(stage, "There was a problem running the project", 4); } Ctx.project.getProjectConfig().remove(Config.CHAPTER_PROP); Ctx.project.getProjectConfig().remove(Config.TEST_SCENE_PROP); Ctx.project.setModified(); try { Ctx.project.saveProject(); } catch (Exception ex) { String msg = "Something went wrong while saving the project.\n\n" + ex.getClass().getSimpleName() + " - " + ex.getMessage(); EditorLogger.error(msg); return; } } }).start(); } }
Added Particle Editor to the Tools button.
adventure-editor/src/main/java/com/bladecoder/engineeditor/scneditor/ToolsWindow.java
Added Particle Editor to the Tools button.
<ide><path>dventure-editor/src/main/java/com/bladecoder/engineeditor/scneditor/ToolsWindow.java <ide> <ide> import java.io.File; <ide> import java.io.IOException; <add>import java.util.ArrayList; <ide> import java.util.List; <ide> <ide> import com.badlogic.gdx.Gdx; <ide> <ide> TextButton exportUIImages = new TextButton("Export UI Images", skin, "no-toggled"); <ide> TextButton createUIAtlas = new TextButton("Create UI Atlas", skin, "no-toggled"); <add> TextButton particleEditor = new TextButton("Particle Editor", skin, "no-toggled"); <ide> <ide> table.defaults().left().expandX(); <ide> table.top().pad(DPIUtils.getSpacing() / 2); <ide> table.row(); <ide> table.add(createUIAtlas).expandX().fill(); <ide> <add> table.row(); <add> table.add(particleEditor).expandX().fill(); <add> <ide> // table.row(); <ide> // table.add(tmpButton).expandX().fill(); <ide> <ide> @Override <ide> public void changed(ChangeEvent event, Actor actor) { <ide> createUIAtlas(); <add> } <add> }); <add> <add> particleEditor.addListener(new ChangeListener() { <add> @Override <add> public void changed(ChangeEvent event, Actor actor) { <add> particleEditor(); <ide> } <ide> }); <ide> <ide> }).start(); <ide> <ide> } <add> <add> private void particleEditor() { <add> // Open the particle editor <add> List<String> cp = new ArrayList<String>(); <add> cp.add(System.getProperty("java.class.path")); <add> try { <add> RunProccess.runJavaProccess("com.badlogic.gdx.tools.particleeditor.ParticleEditor", cp, null); <add> } catch (IOException e) { <add> Message.showMsgDialog(getStage(), "Error", "Error launching Particle Editor."); <add> EditorLogger.printStackTrace(e); <add> } <add> } <ide> }
Java
apache-2.0
e5a634d5f82b9044d7bec0b4da38ce92b59c1885
0
Netflix/spectator
/* * Copyright 2014-2021 Netflix, 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 com.netflix.spectator.atlas; import com.netflix.spectator.api.Clock; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.RegistryConfig; import java.time.Duration; import java.util.Collections; import java.util.Map; /** * Configuration for Atlas registry. */ public interface AtlasConfig extends RegistryConfig { /** * Returns the step size (reporting frequency) to use. The default is 1 minute. */ default Duration step() { String v = get("atlas.step"); return (v == null) ? Duration.ofMinutes(1) : Duration.parse(v); } /** * Returns the TTL for meters that do not have any activity. After this period the meter * will be considered expired and will not get reported. Default is 15 minutes. */ default Duration meterTTL() { String v = get("atlas.meterTTL"); return (v == null) ? Duration.ofMinutes(15) : Duration.parse(v); } /** * Returns true if publishing to Atlas is enabled. Default is true. */ default boolean enabled() { String v = get("atlas.enabled"); return v == null || Boolean.parseBoolean(v); } /** * Returns true if the registry should automatically start the background reporting threads * in the constructor. When using DI systems this can be used to automatically start the * registry when it is constructed. Otherwise the {@code AtlasRegistry.start()} method will * need to be called explicitly. Default is false. */ default boolean autoStart() { String v = get("atlas.autoStart"); return v != null && Boolean.parseBoolean(v); } /** * Returns the number of threads to use with the scheduler. The default is * 4 threads. */ default int numThreads() { String v = get("atlas.numThreads"); return (v == null) ? 4 : Integer.parseInt(v); } /** * Returns the URI for the Atlas backend. The default is * {@code http://localhost:7101/api/v1/publish}. */ default String uri() { String v = get("atlas.uri"); return (v == null) ? "http://localhost:7101/api/v1/publish" : v; } /** * Returns the step size (reporting frequency) to use for streaming to Atlas LWC. * The default is 5s. This is the highest resolution that would be supported for getting * an on-demand stream of the data. It must be less than or equal to the Atlas step * ({@link #step()}) and the Atlas step should be an even multiple of this value. */ default Duration lwcStep() { String v = get("atlas.lwc.step"); return (v == null) ? Duration.ofSeconds(5) : Duration.parse(v); } /** * Returns true if streaming to Atlas LWC is enabled. Default is false. */ default boolean lwcEnabled() { String v = get("atlas.lwc.enabled"); return v != null && Boolean.parseBoolean(v); } /** * Returns true if expressions with the same step size as Atlas publishing should be * ignored for streaming. This is used for cases where data being published to Atlas * is also sent into streaming from the backend. Default is true. */ default boolean lwcIgnorePublishStep() { String v = get("atlas.lwc.ignore-publish-step"); return v == null || Boolean.parseBoolean(v); } /** Returns the frequency for refreshing config settings from the LWC service. */ default Duration configRefreshFrequency() { String v = get("atlas.configRefreshFrequency"); return (v == null) ? Duration.ofSeconds(10) : Duration.parse(v); } /** Returns the TTL for subscriptions from the LWC service. */ default Duration configTTL() { return configRefreshFrequency().multipliedBy(15); } /** * Returns the URI for the Atlas LWC endpoint to retrieve current subscriptions. * The default is {@code http://localhost:7101/lwc/api/v1/expressions/local-dev}. */ default String configUri() { String v = get("atlas.config-uri"); return (v == null) ? "http://localhost:7101/lwc/api/v1/expressions/local-dev" : v; } /** * Returns the URI for the Atlas LWC endpoint to evaluate the data for a suscription. * The default is {@code http://localhost:7101/lwc/api/v1/evaluate}. */ default String evalUri() { String v = get("atlas.eval-uri"); return (v == null) ? "http://localhost:7101/lwc/api/v1/evaluate" : v; } /** * Returns the connection timeout for requests to the backend. The default is * 1 second. */ default Duration connectTimeout() { String v = get("atlas.connectTimeout"); return (v == null) ? Duration.ofSeconds(1) : Duration.parse(v); } /** * Returns the read timeout for requests to the backend. The default is * 10 seconds. */ default Duration readTimeout() { String v = get("atlas.readTimeout"); return (v == null) ? Duration.ofSeconds(10) : Duration.parse(v); } /** * Returns the number of measurements per request to use for the backend. If more * measurements are found, then multiple requests will be made. The default is * 10,000. */ default int batchSize() { String v = get("atlas.batchSize"); return (v == null) ? 10000 : Integer.parseInt(v); } /** * Returns the common tags to apply to all metrics reported to Atlas. The returned tags * must only use valid characters as defined by {@link #validTagCharacters()}. The default * is an empty map. */ default Map<String, String> commonTags() { return Collections.emptyMap(); } /** * Returns a pattern indicating the valid characters for a tag key or value. The default is * {@code -._A-Za-z0-9~^}. */ default String validTagCharacters() { return "-._A-Za-z0-9~^"; } /** * Returns a map from tag key to a pattern indicating the valid characters for the values * of that key. The default is an empty map. * * @deprecated This method is no longer used internally. */ @Deprecated default Map<String, String> validTagValueCharacters() { return Collections.emptyMap(); } /** * Returns a registry to use for recording metrics about the behavior of the AtlasRegistry. * By default it will return null and the metrics will be reported to itself. In some cases * it is useful to customize this for debugging so that the metrics for the behavior of * AtlasRegistry will have a different failure mode than AtlasRegistry. */ default Registry debugRegistry() { return null; } /** * Returns a rollup policy that will be applied to the measurements before sending to Atlas. * The policy will not be applied to data going to the streaming path. Default is a no-op * policy. */ default RollupPolicy rollupPolicy() { return RollupPolicy.noop(commonTags()); } /** * Avoid collecting right on boundaries to minimize transitions on step longs * during a collection. By default it will randomly distribute across the middle * of the step interval. */ default long initialPollingDelay(Clock clock, long stepSize) { long now = clock.wallTime(); long stepBoundary = now / stepSize * stepSize; // Buffer by 10% of the step interval on either side long offset = stepSize / 10; // For larger intervals spread it out, otherwise bias towards the start // to ensure there is plenty of time to send without needing to cross over // to the next interval. The threshold of 1s was chosen because it is typically // big enough to avoid GC troubles where it is common to see pause times in the // low 100s of milliseconds. if (offset >= 1000L) { // Check if the current delay is within the acceptable range long delay = now - stepBoundary; if (delay < offset) { return delay + offset; } else { return Math.min(delay, stepSize - offset); } } else { long firstTime = stepBoundary + stepSize / 10; return firstTime > now ? firstTime - now : firstTime + stepSize - now; } } /** * <strong>Alpha:</strong> this method is experimental and may change or be completely * removed with no notice. * * Override to provide a custom publisher for sending data to Atlas. The intended use is * for some cases where it is desirable to send the payload somewhere else or to use an * alternate client. If the return value is null, then the data will be sent via the normal * path. */ default Publisher publisher() { return null; } }
spectator-reg-atlas/src/main/java/com/netflix/spectator/atlas/AtlasConfig.java
/* * Copyright 2014-2021 Netflix, 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 com.netflix.spectator.atlas; import com.netflix.spectator.api.Clock; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.RegistryConfig; import java.time.Duration; import java.util.Collections; import java.util.Map; /** * Configuration for Atlas registry. */ public interface AtlasConfig extends RegistryConfig { /** * Returns the step size (reporting frequency) to use. The default is 1 minute. */ default Duration step() { String v = get("atlas.step"); return (v == null) ? Duration.ofMinutes(1) : Duration.parse(v); } /** * Returns the TTL for meters that do not have any activity. After this period the meter * will be considered expired and will not get reported. Default is 15 minutes. */ default Duration meterTTL() { String v = get("atlas.meterTTL"); return (v == null) ? Duration.ofMinutes(15) : Duration.parse(v); } /** * Returns true if publishing to Atlas is enabled. Default is true. */ default boolean enabled() { String v = get("atlas.enabled"); return v == null || Boolean.parseBoolean(v); } /** * Returns true if the registry should automatically start the background reporting threads * in the constructor. When using DI systems this can be used to automatically start the * registry when it is constructed. Otherwise the {@code AtlasRegistry.start()} method will * need to be called explicitly. Default is false. */ default boolean autoStart() { String v = get("atlas.autoStart"); return v != null && Boolean.parseBoolean(v); } /** * Returns the number of threads to use with the scheduler. The default is * 4 threads. */ default int numThreads() { String v = get("atlas.numThreads"); return (v == null) ? 4 : Integer.parseInt(v); } /** * Returns the URI for the Atlas backend. The default is * {@code http://localhost:7101/api/v1/publish}. */ default String uri() { String v = get("atlas.uri"); return (v == null) ? "http://localhost:7101/api/v1/publish" : v; } /** * Returns the step size (reporting frequency) to use for streaming to Atlas LWC. * The default is 5s. This is the highest resolution that would be supported for getting * an on-demand stream of the data. It must be less than or equal to the Atlas step * ({@link #step()}) and the Atlas step should be an even multiple of this value. */ default Duration lwcStep() { String v = get("atlas.lwc.step"); return (v == null) ? Duration.ofSeconds(5) : Duration.parse(v); } /** * Returns true if streaming to Atlas LWC is enabled. Default is false. */ default boolean lwcEnabled() { String v = get("atlas.lwc.enabled"); return v != null && Boolean.parseBoolean(v); } /** * Returns true if expressions with the same step size as Atlas publishing should be * ignored for streaming. This is used for cases where data being published to Atlas * is also sent into streaming from the backend. Default is true. */ default boolean lwcIgnorePublishStep() { String v = get("atlas.lwc.ignore-publish-step"); return v == null || Boolean.parseBoolean(v); } /** Returns the frequency for refreshing config settings from the LWC service. */ default Duration configRefreshFrequency() { String v = get("atlas.configRefreshFrequency"); return (v == null) ? Duration.ofSeconds(10) : Duration.parse(v); } /** Returns the TTL for subscriptions from the LWC service. */ default Duration configTTL() { return configRefreshFrequency().multipliedBy(15); } /** * Returns the URI for the Atlas LWC endpoint to retrieve current subscriptions. * The default is {@code http://localhost:7101/lwc/api/v1/expressions/local-dev}. */ default String configUri() { String v = get("atlas.config-uri"); return (v == null) ? "http://localhost:7101/lwc/api/v1/expressions/local-dev" : v; } /** * Returns the URI for the Atlas LWC endpoint to evaluate the data for a suscription. * The default is {@code http://localhost:7101/lwc/api/v1/evaluate}. */ default String evalUri() { String v = get("atlas.eval-uri"); return (v == null) ? "http://localhost:7101/lwc/api/v1/evaluate" : v; } /** * Returns the connection timeout for requests to the backend. The default is * 1 second. */ default Duration connectTimeout() { String v = get("atlas.connectTimeout"); return (v == null) ? Duration.ofSeconds(1) : Duration.parse(v); } /** * Returns the read timeout for requests to the backend. The default is * 10 seconds. */ default Duration readTimeout() { String v = get("atlas.readTimeout"); return (v == null) ? Duration.ofSeconds(10) : Duration.parse(v); } /** * Returns the number of measurements per request to use for the backend. If more * measurements are found, then multiple requests will be made. The default is * 10,000. */ default int batchSize() { String v = get("atlas.batchSize"); return (v == null) ? 10000 : Integer.parseInt(v); } /** * Returns the common tags to apply to all metrics reported to Atlas. * The default is an empty map. */ default Map<String, String> commonTags() { return Collections.emptyMap(); } /** * Returns a pattern indicating the valid characters for a tag key or value. The default is * {@code -._A-Za-z0-9~^}. */ default String validTagCharacters() { return "-._A-Za-z0-9~^"; } /** * Returns a map from tag key to a pattern indicating the valid characters for the values * of that key. The default is an empty map. * * @deprecated This method is no longer used internally. */ @Deprecated default Map<String, String> validTagValueCharacters() { return Collections.emptyMap(); } /** * Returns a registry to use for recording metrics about the behavior of the AtlasRegistry. * By default it will return null and the metrics will be reported to itself. In some cases * it is useful to customize this for debugging so that the metrics for the behavior of * AtlasRegistry will have a different failure mode than AtlasRegistry. */ default Registry debugRegistry() { return null; } /** * Returns a rollup policy that will be applied to the measurements before sending to Atlas. * The policy will not be applied to data going to the streaming path. Default is a no-op * policy. */ default RollupPolicy rollupPolicy() { return RollupPolicy.noop(commonTags()); } /** * Avoid collecting right on boundaries to minimize transitions on step longs * during a collection. By default it will randomly distribute across the middle * of the step interval. */ default long initialPollingDelay(Clock clock, long stepSize) { long now = clock.wallTime(); long stepBoundary = now / stepSize * stepSize; // Buffer by 10% of the step interval on either side long offset = stepSize / 10; // For larger intervals spread it out, otherwise bias towards the start // to ensure there is plenty of time to send without needing to cross over // to the next interval. The threshold of 1s was chosen because it is typically // big enough to avoid GC troubles where it is common to see pause times in the // low 100s of milliseconds. if (offset >= 1000L) { // Check if the current delay is within the acceptable range long delay = now - stepBoundary; if (delay < offset) { return delay + offset; } else { return Math.min(delay, stepSize - offset); } } else { long firstTime = stepBoundary + stepSize / 10; return firstTime > now ? firstTime - now : firstTime + stepSize - now; } } /** * <strong>Alpha:</strong> this method is experimental and may change or be completely * removed with no notice. * * Override to provide a custom publisher for sending data to Atlas. The intended use is * for some cases where it is desirable to send the payload somewhere else or to use an * alternate client. If the return value is null, then the data will be sent via the normal * path. */ default Publisher publisher() { return null; } }
clarify expectations for common tags (#977) Update the comment for the commonTags with AtlasRegistry to indicate that the user is responsible for ensuring that they conform to the valid tag character restrictions.
spectator-reg-atlas/src/main/java/com/netflix/spectator/atlas/AtlasConfig.java
clarify expectations for common tags (#977)
<ide><path>pectator-reg-atlas/src/main/java/com/netflix/spectator/atlas/AtlasConfig.java <ide> } <ide> <ide> /** <del> * Returns the common tags to apply to all metrics reported to Atlas. <del> * The default is an empty map. <add> * Returns the common tags to apply to all metrics reported to Atlas. The returned tags <add> * must only use valid characters as defined by {@link #validTagCharacters()}. The default <add> * is an empty map. <ide> */ <ide> default Map<String, String> commonTags() { <ide> return Collections.emptyMap();
Java
apache-2.0
322e9cee4a61d531a893f74db10bb62ee44d6d7c
0
cloudevents/sdk-java
/** * Copyright 2019 The CloudEvents Authors * * 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 io.cloudevents.fun; import java.util.Map; /** * * @author fabiojose * * @param <P> The payload type * @param <T> The 'data' type * @param <H> The type of headers value */ @FunctionalInterface public interface DataMarshaller<P, T, H> { /** * Marshals the 'data' into payload * @param data * @param headers * @return * @throws RuntimeException When something bad happens during the marshal process */ P marshal(T data, Map<String, H> headers) throws RuntimeException; }
api/src/main/java/io/cloudevents/fun/DataMarshaller.java
/** * Copyright 2019 The CloudEvents Authors * * 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 io.cloudevents.fun; import java.util.Map; /** * * @author fabiojose * */ @FunctionalInterface public interface DataMarshaller<P, T> { /** * Marshals the 'data' into payload * @param data * @param headers * @return * @throws RuntimeException When something bad happens during the marshal process */ P marshal(T data, Map<String, Object> headers) throws RuntimeException; }
Typing the header's value Signed-off-by: Fabio José <[email protected]>
api/src/main/java/io/cloudevents/fun/DataMarshaller.java
Typing the header's value
<ide><path>pi/src/main/java/io/cloudevents/fun/DataMarshaller.java <ide> * <ide> * @author fabiojose <ide> * <add> * @param <P> The payload type <add> * @param <T> The 'data' type <add> * @param <H> The type of headers value <ide> */ <ide> @FunctionalInterface <del>public interface DataMarshaller<P, T> { <add>public interface DataMarshaller<P, T, H> { <ide> <ide> /** <ide> * Marshals the 'data' into payload <ide> * @return <ide> * @throws RuntimeException When something bad happens during the marshal process <ide> */ <del> P marshal(T data, Map<String, Object> headers) throws RuntimeException; <add> P marshal(T data, Map<String, H> headers) throws RuntimeException; <ide> <ide> }
Java
agpl-3.0
9d9fca10c3f6dd7b204eb4fea4ab8ef078d3fc6a
0
animotron/core,animotron/core
/* * Copyright (C) 2011 The Animo Project * http://animotron.org * * 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 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 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., 675 Mass Ave, Cambridge, MA 02129, USA. */ package org.animotron.graph.builder; import org.animotron.exception.AnimoException; import org.animotron.exception.ENotFound; import org.animotron.graph.GraphOperation; import org.animotron.manipulator.Manipulators; import org.animotron.manipulator.Manipulators.Catcher; import org.animotron.statement.Statement; import org.animotron.statement.ml.TEXT; import org.animotron.statement.operator.AN; import org.animotron.statement.operator.THE; import org.animotron.statement.relation.Relation; import org.animotron.utils.MessageDigester; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.Transaction; import java.security.MessageDigest; import java.util.LinkedList; import java.util.List; import java.util.Stack; import java.util.StringTokenizer; import static org.animotron.Properties.HASH; import static org.animotron.graph.AnimoGraph.*; /** * Animo graph builder, it do optimization/compression and * inform listeners on store/delete events. * * Direct graph as input from top element to bottom processing strategy. * * Methods to use: * * startGraph() * endGraph() * * start(String prefix, String ns, String reference, String value) * start(Statement statement, String prefix, String ns, String reference, String value) * end() * * getRelationship() * * @author <a href="mailto:[email protected]">Dmitriy Shabanov</a> * @author <a href="mailto:[email protected]">Evgeny Gazdovsky</a> */ public abstract class GraphBuilder { private Relationship the = null; private Stack<Object[]> statements; private Catcher catcher; private List<Object[]> flow; protected Transaction tx; private boolean ignoreNotFound; public GraphBuilder() { this.ignoreNotFound = true; } public GraphBuilder(boolean ignoreNotFound) { this.ignoreNotFound = ignoreNotFound; } public final Relationship getRelationship() { return the; } final protected void startGraph() { catcher = Manipulators.getCatcher(); statements = new Stack<Object[]>(); flow = new LinkedList<Object[]>(); the = null; tx = beginTx(); } final public boolean successful() { return the != null; } final protected void endGraph() throws AnimoException { endGraph(null); } final protected void endGraph(GraphOperation<?> o) throws AnimoException { if (!statements.empty()) { end(); } try { int i = 0; for (Object[] item : flow) { build(item, i++); if (i % 100 == 0) System.out.println(i); if (i % 10000 == 0) { tx.success(); finishTx(tx); tx = beginTx(); } } the = (Relationship) flow.get(0)[3]; if (o != null) o.execute(); tx.success(); finishTx(tx); catcher.push(); } catch (AnimoException e) { fail(e); throw e; } catch (Exception e) { fail(e); } } final protected void start(Statement statement) { start(statement, null); } final protected void start(String value) { start(TEXT._, value); } final protected void start(Statement statement, String reference) { if (flow.isEmpty() && !(statement instanceof THE)) { start(THE._, null); } Object[] parent = null; if (!statements.empty()) { if (statement instanceof THE) { start(AN._, reference); end(); } else { parent = statements.peek(); } } MessageDigest md = statement.hash(reference); Object[] item = { statement, // 0 statement reference, // 1 name or value md, // 2 message digest null, // 3 current relationship null, // 4 current node parent, // 5 parent item false, // 6 done }; statements.push(item); flow.add(item); } final protected void end() { Object[] current = statements.pop(); byte[] hash = ((MessageDigest) current[2]).digest(); Object[] parent = (Object[]) current[5]; if (parent != null) { ((MessageDigest) (parent[2])).update(hash); } current[2] = hash; } final protected String removeWS(String value) { StringBuilder buf = new StringBuilder(); if (value.length() > 0) { StringTokenizer tok = new StringTokenizer(value); while (tok.hasMoreTokens()) { buf.append(tok.nextToken()); if (tok.hasMoreTokens()) buf.append(' '); } } if (buf.length() > 0) return buf.toString(); return null; } //TODO: Store hash for every node as byte[] //TODO: Build graph via single thread in sync and async modes private void build(Object[] item, int order) throws AnimoException { Object[] p = (Object[]) item[5]; if (p != null) { if ((Boolean) p[6]) { item[6] = true; return; } } Relationship r; Statement statement = (Statement) item[0]; if (statement instanceof THE) { THE the = (THE) statement; String hash = hash(item); String name = item[1] != null ? (String) item[1] : hash; r = the.get(name); if (r != null) { if (HASH.has(r)) { String h = HASH.get(r); if (h == null) { catcher.creative(r); HASH.set(r, hash); } else if (!h.equals(hash)) { catcher.renew(r); HASH.set(r, hash); } else { item[6] = true; } } else { catcher.creative(r); HASH.set(r, hash); } } else { r = the.create(name, hash); catcher.creative(r); } } else { Node parent = (Node) p[4]; if (parent == null) //"Internal error: parent can not be null." throw new AnimoException((Relationship)item[3]); if (!(statement instanceof Relation)) { String hash = hash(item); Node node = getCache(hash); if (node == null) { r = build(statement, parent, item, order); createCache(r.getEndNode(), hash); } else { r = parent.createRelationshipTo(node, statement.relationshipType()); order(r, order); item[6] = true; } } else { r = build(statement, parent, item, order); } } item[3] = r; item[4] = r.getEndNode(); } private String hash (byte[] md) { return MessageDigester.byteArrayToHex(md); } private String hash(Object[] item) { return hash((byte[]) item[2]); } private Relationship build(Statement statement, Node parent, Object[] item, int order) throws ENotFound { return statement.build(parent, (String) item[1], order, ignoreNotFound); } protected void fail(Exception e){ e.printStackTrace(System.out); finishTx(tx); the = null; } }
src/main/java/org/animotron/graph/builder/GraphBuilder.java
/* * Copyright (C) 2011 The Animo Project * http://animotron.org * * 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 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 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., 675 Mass Ave, Cambridge, MA 02129, USA. */ package org.animotron.graph.builder; import org.animotron.exception.AnimoException; import org.animotron.exception.ENotFound; import org.animotron.graph.GraphOperation; import org.animotron.manipulator.Manipulators; import org.animotron.manipulator.Manipulators.Catcher; import org.animotron.statement.Statement; import org.animotron.statement.ml.TEXT; import org.animotron.statement.operator.AN; import org.animotron.statement.operator.THE; import org.animotron.statement.relation.Relation; import org.animotron.utils.MessageDigester; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.Transaction; import java.security.MessageDigest; import java.util.LinkedList; import java.util.List; import java.util.Stack; import java.util.StringTokenizer; import static org.animotron.Properties.HASH; import static org.animotron.graph.AnimoGraph.*; /** * Animo graph builder, it do optimization/compression and * inform listeners on store/delete events. * * Direct graph as input from top element to bottom processing strategy. * * Methods to use: * * startGraph() * endGraph() * * start(String prefix, String ns, String reference, String value) * start(Statement statement, String prefix, String ns, String reference, String value) * end() * * getRelationship() * * @author <a href="mailto:[email protected]">Dmitriy Shabanov</a> * @author <a href="mailto:[email protected]">Evgeny Gazdovsky</a> */ public abstract class GraphBuilder { private Relationship the = null; private Stack<Object[]> statements; private Catcher catcher; private List<Object[]> flow; protected Transaction tx; private boolean ignoreNotFound; public GraphBuilder() { this.ignoreNotFound = true; } public GraphBuilder(boolean ignoreNotFound) { this.ignoreNotFound = ignoreNotFound; } public final Relationship getRelationship() { return the; } final protected void startGraph() { catcher = Manipulators.getCatcher(); statements = new Stack<Object[]>(); flow = new LinkedList<Object[]>(); the = null; tx = beginTx(); } final public boolean successful() { return the != null; } final protected void endGraph() throws AnimoException { endGraph(null); } final protected void endGraph(GraphOperation<?> o) throws AnimoException { if (!statements.empty()) { end(); } try { int i = 0; for (Object[] item : flow) { build(item, i++); } the = (Relationship) flow.get(0)[3]; if (o != null) o.execute(); tx.success(); finishTx(tx); catcher.push(); } catch (AnimoException e) { fail(e); throw e; } catch (Exception e) { fail(e); } } final protected void start(Statement statement) { start(statement, null); } final protected void start(String value) { start(TEXT._, value); } final protected void start(Statement statement, String reference) { if (flow.isEmpty() && !(statement instanceof THE)) { start(THE._, null); } Object[] parent = null; if (!statements.empty()) { if (statement instanceof THE) { start(AN._, reference); end(); } else { parent = statements.peek(); } } MessageDigest md = statement.hash(reference); Object[] item = { statement, // 0 statement reference, // 1 name or value md, // 2 message digest null, // 3 current relationship null, // 4 current node parent, // 5 parent item false, // 6 done }; statements.push(item); flow.add(item); } final protected void end() { Object[] current = statements.pop(); byte[] hash = ((MessageDigest) current[2]).digest(); Object[] parent = (Object[]) current[5]; if (parent != null) { ((MessageDigest) (parent[2])).update(hash); } current[2] = hash; } final protected String removeWS(String value) { StringBuilder buf = new StringBuilder(); if (value.length() > 0) { StringTokenizer tok = new StringTokenizer(value); while (tok.hasMoreTokens()) { buf.append(tok.nextToken()); if (tok.hasMoreTokens()) buf.append(' '); } } if (buf.length() > 0) return buf.toString(); return null; } //TODO: Store hash for every node as byte[] //TODO: Build graph via single thread in sync and async modes private void build(Object[] item, int order) throws AnimoException { Object[] p = (Object[]) item[5]; if (p != null) { if ((Boolean) p[6]) { item[6] = true; return; } } Relationship r; Statement statement = (Statement) item[0]; if (statement instanceof THE) { THE the = (THE) statement; String hash = hash(item); String name = item[1] != null ? (String) item[1] : hash; r = the.get(name); if (r != null) { if (HASH.has(r)) { String h = HASH.get(r); if (h == null) { catcher.creative(r); HASH.set(r, hash); } else if (!h.equals(hash)) { catcher.renew(r); HASH.set(r, hash); } else { item[6] = true; } } else { catcher.creative(r); HASH.set(r, hash); } } else { r = the.create(name, hash); catcher.creative(r); } } else { Node parent = (Node) p[4]; if (parent == null) //"Internal error: parent can not be null." throw new AnimoException((Relationship)item[3]); if (!(statement instanceof Relation)) { String hash = hash(item); Node node = getCache(hash); if (node == null) { r = build(statement, parent, item, order); createCache(r.getEndNode(), hash); } else { r = parent.createRelationshipTo(node, statement.relationshipType()); order(r, order); item[6] = true; } } else { r = build(statement, parent, item, order); } } item[3] = r; item[4] = r.getEndNode(); } private String hash (byte[] md) { return MessageDigester.byteArrayToHex(md); } private String hash(Object[] item) { return hash((byte[]) item[2]); } private Relationship build(Statement statement, Node parent, Object[] item, int order) throws ENotFound { return statement.build(parent, (String) item[1], order, ignoreNotFound); } protected void fail(Exception e){ e.printStackTrace(System.out); finishTx(tx); the = null; } }
commit each 10k elements
src/main/java/org/animotron/graph/builder/GraphBuilder.java
commit each 10k elements
<ide><path>rc/main/java/org/animotron/graph/builder/GraphBuilder.java <ide> <ide> for (Object[] item : flow) { <ide> build(item, i++); <add> if (i % 100 == 0) <add> System.out.println(i); <add> <add> if (i % 10000 == 0) { <add> tx.success(); <add> finishTx(tx); <add> <add> tx = beginTx(); <add> } <ide> } <ide> <ide> the = (Relationship) flow.get(0)[3];
Java
lgpl-2.1
6c9a66579369de887b040e0f71c4eebe5f4200fc
0
netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration
/* File: $Id$ * Revision: $Revision$ * Author: $Author$ * Date: $Date$ * * The Netarchive Suite - Software to harvest and preserve websites * Copyright 2004-2012 The Royal Danish Library, the Danish State and * University Library, the National Library of France and the Austrian * National Library. * * This library 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 library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package dk.netarkivet.harvester.datamodel; import java.sql.Clob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import dk.netarkivet.common.exceptions.ArgumentNotValid; import dk.netarkivet.common.exceptions.IOFailure; import dk.netarkivet.common.exceptions.PermissionDenied; import dk.netarkivet.common.exceptions.UnknownID; import dk.netarkivet.common.utils.DBUtils; import dk.netarkivet.common.utils.ExceptionUtils; import dk.netarkivet.common.utils.FilterIterator; import dk.netarkivet.common.utils.StringUtils; import dk.netarkivet.harvester.datamodel.extendedfield.ExtendedField; import dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldDAO; import dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldTypes; import dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldValue; import dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldValueDAO; import dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldValueDBDAO; /** * A database-based implementation of the DomainDAO. * * The statements to create the tables are located in: * <ul> * <li><em>Derby:</em> scripts/sql/createfullhddb.sql</li> * <li><em>MySQL:</em> scripts/sql/createfullhddb.mysql</li> * <li><em>PostgreSQL:</em> scripts/postgresql/netarchivesuite_init.sql</li> * </ul> * */ public class DomainDBDAO extends DomainDAO { /** The log. */ private static final Log log = LogFactory.getLog(DomainDBDAO.class); /** * Creates a database-based implementation of the DomainDAO. Will check that * all schemas have correct versions, and update the ones that haven't. * * @throws IOFailure * on trouble updating tables to new versions, or on tables with * wrong versions that we don't know how to change to expected * version. */ protected DomainDBDAO() { Connection connection = HarvestDBConnection.get(); try { HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.CONFIGURATIONS); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.DOMAINS); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.CONFIGPASSWORDS); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.CONFIGSEEDLISTS); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.SEEDLISTS); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.PASSWORDS); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.OWNERINFO); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.HISTORYINFO); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.EXTENDEDFIELDTYPE); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.EXTENDEDFIELD); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.EXTENDEDFIELDVALUE); } finally { HarvestDBConnection.release(connection); } } @Override protected void create(Connection connection, Domain d) { ArgumentNotValid.checkNotNull(d, "d"); ArgumentNotValid.checkNotNullOrEmpty(d.getName(), "d.getName()"); if (exists(connection, d.getName())) { String msg = "Cannot create already existing domain " + d; log.debug(msg); throw new PermissionDenied(msg); } PreparedStatement s = null; log.debug("trying to create domain with name: " + d.getName()); try { connection.setAutoCommit(false); s = connection.prepareStatement("INSERT INTO domains " + "(name, comments, defaultconfig, crawlertraps, edition," + " alias, lastaliasupdate ) " + "VALUES ( ?, ?, -1, ?, ?, ?, ? )", Statement.RETURN_GENERATED_KEYS); // Id is autogenerated // defaultconfig cannot exist yet, so we put in -1 // until we have configs DBUtils.setName(s, 1, d, Constants.MAX_NAME_SIZE); DBUtils.setComments(s, 2, d, Constants.MAX_COMMENT_SIZE); s.setString(3,StringUtils.conjoin("\n", d .getCrawlerTraps())); long initialEdition = 1; s.setLong(4, initialEdition); AliasInfo aliasInfo = d.getAliasInfo(); DBUtils.setLongMaybeNull(s, 5, aliasInfo == null ? null : DBUtils.selectLongValue(connection, "SELECT domain_id FROM domains WHERE name = ?", aliasInfo.getAliasOf())); DBUtils.setDateMaybeNull(s, 6, aliasInfo == null ? null : aliasInfo .getLastChange()); s.executeUpdate(); d.setID(DBUtils.getGeneratedID(s)); s.close(); Iterator<Password> passwords = d.getAllPasswords(); while (passwords.hasNext()) { Password p = passwords.next(); insertPassword(connection, d, p); } Iterator<SeedList> seedlists = d.getAllSeedLists(); if (!seedlists.hasNext()) { String msg = "No seedlists for domain " + d; log.debug(msg); throw new ArgumentNotValid(msg); } while (seedlists.hasNext()) { SeedList sl = seedlists.next(); insertSeedlist(connection, d, sl); } Iterator<DomainConfiguration> dcs = d.getAllConfigurations(); if (!dcs.hasNext()) { String msg = "No configurations for domain " + d; log.debug(msg); throw new ArgumentNotValid(msg); } while (dcs.hasNext()) { DomainConfiguration dc = dcs.next(); insertConfiguration(connection, d, dc); // Create xref tables for seedlists referenced by this config createConfigSeedlistsEntries(connection, d, dc); // Create xref tables for passwords referenced by this config createConfigPasswordsEntries(connection, d, dc); } // Now that configs are defined, set the default config. s = connection.prepareStatement( "UPDATE domains SET defaultconfig = " + "(SELECT config_id FROM configurations " + "WHERE configurations.name = ? " + "AND configurations.domain_id = ?) " + "WHERE domain_id = ?"); DBUtils.setName(s, 1, d.getDefaultConfiguration(), Constants.MAX_NAME_SIZE); s.setLong(2, d.getID()); s.setLong(3, d.getID()); s.executeUpdate(); s.close(); for (Iterator<HarvestInfo> hi = d.getHistory().getHarvestInfo(); hi.hasNext();) { insertHarvestInfo(connection, d, hi.next()); } for (DomainOwnerInfo doi : d.getAllDomainOwnerInfo()) { insertOwnerInfo(connection, d, doi); } addExtendedFieldValues(d); saveExtendedFieldValues(connection, d); connection.commit(); d.setEdition(initialEdition); } catch (SQLException e) { String message = "SQL error creating domain " + d + " in database" + "\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(message, e); throw new IOFailure(message, e); } finally { DBUtils.rollbackIfNeeded(connection, "creating", d); } } @Override public synchronized void update(Domain d) { ArgumentNotValid.checkNotNull(d, "domain"); if (!exists(d.getName())) { throw new UnknownID("No domain named " + d.getName() + " exists"); } Connection connection = HarvestDBConnection.get(); PreparedStatement s = null; try { connection.setAutoCommit(false); // Domain object may not have ID yet, so get it from the DB long domainID = DBUtils.selectLongValue(connection, "SELECT domain_id FROM domains WHERE name = ?", d.getName()); if (d.hasID() && d.getID() != domainID) { String message = "Domain " + d + " has wrong id: Has " + d.getID() + ", but persistent store claims " + domainID; log.warn(message); throw new ArgumentNotValid(message); } d.setID(domainID); // The alias field is now updated using a separate select request // rather than embedding the select inside the update statement. // This change was needed to accommodate MySQL, and may lower // performance. s = connection.prepareStatement("UPDATE domains SET " + "comments = ?, crawlertraps = ?, edition = ?," + "alias = ?, lastAliasUpdate = ? " + "WHERE domain_id = ? AND edition = ?"); DBUtils.setComments(s, 1, d, Constants.MAX_COMMENT_SIZE); s.setString(2,StringUtils.conjoin("\n", d .getCrawlerTraps())); final long newEdition = d.getEdition() + 1; s.setLong(3, newEdition); AliasInfo aliasInfo = d.getAliasInfo(); DBUtils.setLongMaybeNull(s, 4, aliasInfo == null ? null : DBUtils.selectLongValue(connection, "SELECT domain_id FROM domains WHERE name = ?", aliasInfo.getAliasOf())); DBUtils.setDateMaybeNull(s, 5, aliasInfo == null ? null : aliasInfo.getLastChange()); s.setLong(6, d.getID()); s.setLong(7, d.getEdition()); int rows = s.executeUpdate(); if (rows == 0) { String message = "Edition " + d.getEdition() + " has expired, cannot update " + d; log.debug(message); throw new PermissionDenied(message); } s.close(); updatePasswords(connection, d); updateSeedlists(connection, d); updateConfigurations(connection, d); updateOwnerInfo(connection, d); updateHarvestInfo(connection, d); saveExtendedFieldValues(connection, d); // Now that configs are updated, we can set default_config s = connection.prepareStatement("UPDATE domains SET " + "defaultconfig = (SELECT config_id" + " FROM configurations" + " WHERE domain_id = ?" + " AND name = ?)" + " WHERE domain_id = ?"); s.setLong(1, d.getID()); s.setString(2, d.getDefaultConfiguration().getName()); s.setLong(3, d.getID()); s.executeUpdate(); connection.commit(); d.setEdition(newEdition); } catch (SQLException e) { String message = "SQL error updating domain " + d + " in database" + "\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(message, e); throw new IOFailure(message, e); } finally { DBUtils.closeStatementIfOpen(s); DBUtils.rollbackIfNeeded(connection, "updating", d); HarvestDBConnection.release(connection); } } /** * Update the list of passwords for the given domain, keeping IDs where * applicable. * @param c * A connection to the database * @param d * A domain to update. * @throws SQLException * If any database problems occur during the update process. */ private void updatePasswords(Connection c, Domain d) throws SQLException { Map<String, Long> oldNames = DBUtils.selectStringLongMap( c, "SELECT name, password_id FROM passwords " + "WHERE domain_id = ?", d.getID()); PreparedStatement s = c.prepareStatement("UPDATE passwords SET " + "comments = ?, " + "url = ?, " + "realm = ?, " + "username = ?, " + "password = ? " + "WHERE name = ? AND domain_id = ?"); for (Iterator<Password> pwds = d.getAllPasswords(); pwds.hasNext();) { Password pwd = pwds.next(); if (oldNames.containsKey(pwd.getName())) { DBUtils.setComments(s, 1, pwd, Constants.MAX_COMMENT_SIZE); DBUtils.setStringMaxLength(s, 2, pwd.getPasswordDomain(), Constants.MAX_URL_SIZE, pwd, "password url"); DBUtils.setStringMaxLength(s, 3, pwd.getRealm(), Constants.MAX_REALM_NAME_SIZE, pwd, "password realm"); DBUtils.setStringMaxLength(s, 4, pwd.getUsername(), Constants.MAX_USER_NAME_SIZE, pwd, "password username"); DBUtils.setStringMaxLength(s, 5, pwd.getPassword(), Constants.MAX_PASSWORD_SIZE, pwd, "password"); s.setString(6, pwd.getName()); s.setLong(7, d.getID()); s.executeUpdate(); s.clearParameters(); pwd.setID(oldNames.get(pwd.getName())); oldNames.remove(pwd.getName()); } else { insertPassword(c, d, pwd); } } s.close(); s = c.prepareStatement("DELETE FROM passwords WHERE password_id = ?"); for (Long gone : oldNames.values()) { // Check that we're not deleting something that's in use // Since deletion is very rare, this is allowed to take // some time. String usages = DBUtils.getUsages(c, "SELECT configurations.name" + " FROM configurations, config_passwords" + " WHERE configurations.config_id = " + "config_passwords.config_id" + " AND config_passwords.password_id = ?", gone, gone); if (usages != null) { String name = DBUtils.selectStringValue( c, "SELECT name FROM passwords WHERE password_id = ?", gone); String message = "Cannot delete password " + name + " as it is used in " + usages; log.debug(message); throw new PermissionDenied(message); } s.setLong(1, gone); s.executeUpdate(); s.clearParameters(); } } /** * Update the list of seedlists for the given domain, keeping IDs where * applicable. * @param c A connection to the database * @param d A domain to update. * @throws SQLException * If any database problems occur during the update process. */ private void updateSeedlists(Connection c, Domain d) throws SQLException { Map<String, Long> oldNames = DBUtils.selectStringLongMap(c, "SELECT name, seedlist_id FROM seedlists " + "WHERE domain_id = ?", d.getID()); PreparedStatement s = c.prepareStatement("UPDATE seedlists SET " + "comments = ?, " + "seeds = ? " + "WHERE name = ? AND domain_id = ?"); for (Iterator<SeedList> sls = d.getAllSeedLists(); sls.hasNext();) { SeedList sl = sls.next(); if (oldNames.containsKey(sl.getName())) { DBUtils.setComments(s, 1, sl, Constants.MAX_COMMENT_SIZE); DBUtils.setClobMaxLength(s, 2, sl.getSeedsAsString(), Constants.MAX_SEED_LIST_SIZE, sl, "seedlist"); s.setString(3, sl.getName()); s.setLong(4, d.getID()); s.executeUpdate(); s.clearParameters(); sl.setID(oldNames.get(sl.getName())); oldNames.remove(sl.getName()); } else { insertSeedlist(c, d, sl); } } s.close(); s = c.prepareStatement("DELETE FROM seedlists " + "WHERE seedlist_id = ?"); for (Long gone : oldNames.values()) { // Check that we're not deleting something that's in use // Since deletion is very rare, this is allowed to take // some time. String usages = DBUtils.getUsages(c, "SELECT configurations.name" + " FROM configurations, config_seedlists" + " WHERE configurations.config_id = " + "config_seedlists.config_id" + " AND config_seedlists.seedlist_id = ?", gone, gone); if (usages != null) { String name = DBUtils.selectStringValue( c, "SELECT name FROM seedlists WHERE seedlist_id = ?", gone); String message = "Cannot delete seedlist " + name + " as it is used in " + usages; log.debug(message); throw new PermissionDenied(message); } s.setLong(1, gone); s.executeUpdate(); s.clearParameters(); } } /** * Update the list of configurations for the given domain, keeping IDs where * applicable. This also builds the xref tables for passwords and seedlists * used in configurations, and so should be run after those are updated. * @param connection * A connection to the database * @param d * A domain to update. * @throws SQLException * If any database problems occur during the update process. */ private void updateConfigurations( Connection connection, Domain d) throws SQLException { Map<String, Long> oldNames = DBUtils.selectStringLongMap(connection, "SELECT name, config_id FROM configurations " + "WHERE domain_id = ?", d.getID()); PreparedStatement s = connection.prepareStatement( "UPDATE configurations SET comments = ?, " + "template_id = ( SELECT template_id FROM ordertemplates " + "WHERE name = ? ), " + "maxobjects = ?, " + "maxrate = ?, " + "maxbytes = ? " + "WHERE name = ? AND domain_id = ?"); for (Iterator<DomainConfiguration> dcs = d.getAllConfigurations(); dcs.hasNext();) { DomainConfiguration dc = dcs.next(); if (oldNames.containsKey(dc.getName())) { // Update DBUtils.setComments(s, 1, dc, Constants.MAX_COMMENT_SIZE); s.setString(2, dc.getOrderXmlName()); s.setLong(3, dc.getMaxObjects()); s.setInt(4, dc.getMaxRequestRate()); s.setLong(5, dc.getMaxBytes()); s.setString(6, dc.getName()); s.setLong(7, d.getID()); s.executeUpdate(); s.clearParameters(); dc.setID(oldNames.get(dc.getName())); oldNames.remove(dc.getName()); } else { insertConfiguration(connection, d, dc); } updateConfigPasswordsEntries(connection, d, dc); updateConfigSeedlistsEntries(connection, d, dc); } s.close(); s = connection.prepareStatement("DELETE FROM configurations " + "WHERE config_id = ?"); for (Long gone : oldNames.values()) { // Before deleting, check if this is unused. Since deletion is // rare, this is allowed to take some time to give good output String usages = DBUtils.getUsages(connection, "SELECT harvestdefinitions.name" + " FROM harvestdefinitions, harvest_configs" + " WHERE harvestdefinitions.harvest_id = " + "harvest_configs.harvest_id" + " AND harvest_configs.config_id = ?", gone, gone); if (usages != null) { String name = DBUtils.selectStringValue(connection, "SELECT name FROM configurations " + "WHERE config_id = ?", gone); String message = "Cannot delete configuration " + name + " as it is used in " + usages; log.debug(message); throw new PermissionDenied(message); } s.setLong(1, gone); s.executeUpdate(); s.clearParameters(); } } /** * Update the list of owner info for the given domain, keeping IDs where * applicable. * @param c * A connection to the database * @param d * A domain to update. * @throws SQLException * If any database problems occur during the update process. */ private void updateOwnerInfo(Connection c, Domain d) throws SQLException { List<Long> oldIDs = DBUtils.selectLongList(c, "SELECT ownerinfo_id FROM ownerinfo " + "WHERE domain_id = ?", d.getID()); PreparedStatement s = c.prepareStatement("UPDATE ownerinfo SET " + "created = ?, " + "info = ? " + "WHERE ownerinfo_id = ?"); for (DomainOwnerInfo doi : d.getAllDomainOwnerInfo()) { if (doi.hasID() && oldIDs.remove(doi.getID())) { s.setTimestamp(1, new Timestamp(doi.getDate().getTime())); DBUtils.setStringMaxLength(s, 2, doi.getInfo(), Constants.MAX_OWNERINFO_SIZE, doi, "owner info"); s.setLong(3, doi.getID()); s.executeUpdate(); s.clearParameters(); } else { insertOwnerInfo(c, d, doi); } } if (oldIDs.size() != 0) { String message = "Not allowed to delete ownerinfo " + oldIDs + " on " + d; log.debug(message); throw new IOFailure(message); } } /** * Update the list of harvest info for the given domain, keeping IDs where * applicable. * @param c * A connection to the database * @param d * A domain to update. * @throws SQLException * If any database problems occur during the update process. */ private void updateHarvestInfo(Connection c, Domain d) throws SQLException { List<Long> oldIDs = DBUtils.selectLongList( c, "SELECT historyinfo.historyinfo_id " + "FROM historyinfo, configurations " + "WHERE historyinfo.config_id " + "= configurations.config_id" + " AND configurations.domain_id = ?", d .getID()); PreparedStatement s = c.prepareStatement("UPDATE historyinfo SET " + "stopreason = ?, " + "objectcount = ?, " + "bytecount = ?, " + "config_id = " + " (SELECT config_id FROM configurations, domains" + " WHERE domains.domain_id = ?" + " AND configurations.name = ?" + " AND configurations.domain_id = domains.domain_id), " + "harvest_id = ?, " + "job_id = ? " + "WHERE historyinfo_id = ?"); Iterator<HarvestInfo> his = d.getHistory().getHarvestInfo(); while (his.hasNext()) { HarvestInfo hi = his.next(); if (hi.hasID() && oldIDs.remove(hi.getID())) { s.setInt(1, hi.getStopReason().ordinal()); s.setLong(2, hi.getCountObjectRetrieved()); s.setLong(3, hi.getSizeDataRetrieved()); s.setLong(4, d.getID()); s.setString(5, d.getConfiguration( hi.getDomainConfigurationName()).getName()); s.setLong(6, hi.getHarvestID()); if (hi.getJobID() != null) { s.setLong(7, hi.getJobID()); } else { s.setNull(7, Types.BIGINT); } s.setLong(8, hi.getID()); s.executeUpdate(); s.clearParameters(); } else { insertHarvestInfo(c, d, hi); } } if (oldIDs.size() != 0) { String message = "Not allowed to delete historyinfo " + oldIDs + " on " + d; log.debug(message); throw new IOFailure(message); } } /** * Insert new harvest info for a domain. * @param c * A connection to the database * @param d * A domain to insert on. The domains ID must be correct. * @param harvestInfo * Harvest info to insert. */ private void insertHarvestInfo( Connection c, Domain d, HarvestInfo harvestInfo) { PreparedStatement s = null; try { // Note that the config_id is grabbed from the configurations table. s = c.prepareStatement("INSERT INTO historyinfo " + "( stopreason, objectcount, bytecount, config_id, " + "job_id, harvest_id, harvest_time ) " + "VALUES ( ?, ?, ?, ?, ?, ?, ? )", Statement.RETURN_GENERATED_KEYS); s.setInt(1, harvestInfo.getStopReason().ordinal()); s.setLong(2, harvestInfo.getCountObjectRetrieved()); s.setLong(3, harvestInfo.getSizeDataRetrieved()); // TODO More stable way to get IDs, use a select s.setLong(4, d.getConfiguration( harvestInfo.getDomainConfigurationName()).getID()); if (harvestInfo.getJobID() != null) { s.setLong(5, harvestInfo.getJobID()); } else { s.setNull(5, Types.BIGINT); } s.setLong(6, harvestInfo.getHarvestID()); s.setTimestamp(7, new Timestamp(harvestInfo.getDate().getTime())); s.executeUpdate(); harvestInfo.setID(DBUtils.getGeneratedID(s)); } catch (SQLException e) { throw new IOFailure("SQL error while inserting harvest info " + harvestInfo + " for " + d + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } } /** * Insert new owner info for a domain. * @param c * A connection to the database * @param d * A domain to insert on. The domains ID must be correct. * @param doi * Owner info to insert. * @throws SQLException * If any database problems occur during the insertion process. */ private void insertOwnerInfo( Connection c, Domain d, DomainOwnerInfo doi) throws SQLException { PreparedStatement s = c.prepareStatement("INSERT INTO ownerinfo " + "( domain_id, created, info ) VALUES ( ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); s.setLong(1, d.getID()); s.setTimestamp(2, new Timestamp(doi.getDate().getTime())); s.setString(3, doi.getInfo()); s.executeUpdate(); doi.setID(DBUtils.getGeneratedID(s)); } /** * Insert new seedlist for a domain. * @param c * A connection to the database * @param d * A domain to insert on. The domains ID must be correct. * @param sl * Seedlist to insert. * @throws SQLException * If some database error occurs during the insertion process. */ private void insertSeedlist( Connection c, Domain d, SeedList sl) throws SQLException { PreparedStatement s = c.prepareStatement("INSERT INTO seedlists " + "( name, comments, domain_id, seeds ) " + "VALUES ( ?, ?, ?, ? )", Statement.RETURN_GENERATED_KEYS); // ID is autogenerated DBUtils.setName(s, 1, sl, Constants.MAX_NAME_SIZE); DBUtils.setComments(s, 2, sl, Constants.MAX_COMMENT_SIZE); s.setLong(3, d.getID()); DBUtils.setClobMaxLength(s, 4, sl.getSeedsAsString(), Constants.MAX_SEED_LIST_SIZE, sl, "seedlist"); s.executeUpdate(); sl.setID(DBUtils.getGeneratedID(s)); } /** * Inserts a new password entry into the database. * @param c * A connection to the database * @param d * A domain to insert on. The domains ID must be correct. * @param p * A password entry to insert. * @throws SQLException * If some database error occurs during the insertion process. */ private void insertPassword( Connection c, Domain d, Password p) throws SQLException { PreparedStatement s = c.prepareStatement("INSERT INTO passwords " + "( name, comments, domain_id, url, realm, username, " + "password ) " + "VALUES ( ?, ?, ?, ?, ?, ?, ? )", Statement.RETURN_GENERATED_KEYS); // ID is autogenerated DBUtils.setName(s, 1, p, Constants.MAX_NAME_SIZE); DBUtils.setComments(s, 2, p, Constants.MAX_COMMENT_SIZE); s.setLong(3, d.getID()); DBUtils.setStringMaxLength(s, 4, p.getPasswordDomain(), Constants.MAX_URL_SIZE, p, "password url"); DBUtils.setStringMaxLength(s, 5, p.getRealm(), Constants.MAX_REALM_NAME_SIZE, p, "password realm"); DBUtils.setStringMaxLength(s, 6, p.getUsername(), Constants.MAX_USER_NAME_SIZE, p, "password username"); DBUtils.setStringMaxLength(s, 7, p.getPassword(), Constants.MAX_PASSWORD_SIZE, p, "password"); s.executeUpdate(); p.setID(DBUtils.getGeneratedID(s)); } /** * Insert the basic configuration info into the DB. This does not establish * the connections with seedlists and passwords, use * {create,update}Config{Passwords,Seedlists}Entries for that. * @param connection * A connection to the database * * @param d * a domain * @param dc * a domainconfiguration * @throws SQLException * If some database error occurs during the insertion process. */ private void insertConfiguration( Connection connection, Domain d, DomainConfiguration dc) throws SQLException { long templateId = DBUtils.selectLongValue(connection, "SELECT template_id FROM ordertemplates WHERE name = ?", dc .getOrderXmlName()); PreparedStatement s = connection.prepareStatement( "INSERT INTO configurations " + "( name, comments, domain_id, template_id, maxobjects, " + "maxrate, maxbytes ) " + "VALUES ( ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); // Id is autogenerated DBUtils.setName(s, 1, dc, Constants.MAX_NAME_SIZE); DBUtils.setComments(s, 2, dc, Constants.MAX_COMMENT_SIZE); s.setLong(3, d.getID()); s.setLong(4, templateId); s.setLong(5, dc.getMaxObjects()); s.setInt(6, dc.getMaxRequestRate()); s.setLong(7, dc.getMaxBytes()); int rows = s.executeUpdate(); if (rows != 1) { String message = "Error inserting configuration " + dc; log.warn(message); throw new IOFailure(message); } dc.setID(DBUtils.getGeneratedID(s)); } /** * Delete all entries in the given crossref table that belong to the * configuration. * @param c * A connection to the database * @param configId * The domain configuration to remove entries for. * @param table * One of "config_passwords" or "config_seedlists" * @throws SQLException * If any database problems occur during the delete process. */ private void deleteConfigFromTable( Connection c, long configId, String table) throws SQLException { PreparedStatement s = c.prepareStatement("DELETE FROM " + table + " WHERE " + table + ".config_id = ?"); s.setLong(1, configId); s.executeUpdate(); } /** * Delete all entries from the config_passwords table that refer to the * given configuration and insert the current ones. * @param c * A connection to the database * @param d * A domain to operate on * @param dc * Configuration to update. * @throws SQLException * If any database problems occur during the update process. */ private void updateConfigPasswordsEntries( Connection c, Domain d, DomainConfiguration dc) throws SQLException { deleteConfigFromTable(c, dc.getID(), "config_passwords"); createConfigPasswordsEntries(c, d, dc); } /** * Create the xref table for passwords used by configurations. * @param c * A connection to the database * @param d * A domain to operate on. * @param dc * A configuration to create xref table for. * @throws SQLException * If any database problems occur during the insertion of * password entries for the given domain configuration */ private void createConfigPasswordsEntries( Connection c, Domain d, DomainConfiguration dc) throws SQLException { PreparedStatement s = c.prepareStatement("INSERT INTO config_passwords " + "( config_id, password_id ) " + "SELECT config_id, password_id " + " FROM configurations, passwords" + " WHERE configurations.domain_id = ?" + " AND configurations.name = ?" + " AND passwords.name = ?" + " AND passwords.domain_id = configurations.domain_id"); for (Iterator<Password> passwords = dc.getPasswords(); passwords .hasNext();) { Password p = passwords.next(); s.setLong(1, d.getID()); s.setString(2, dc.getName()); s.setString(3, p.getName()); s.executeUpdate(); s.clearParameters(); } } /** * Delete all entries from the config_seedlists table that refer to the * given configuration and insert the current ones. * @param c An open connection to the harvestDatabase. * * @param d * A domain to operate on * @param dc * Configuration to update. * @throws SQLException * If any database problems occur during the update process. */ private void updateConfigSeedlistsEntries( Connection c, Domain d, DomainConfiguration dc) throws SQLException { deleteConfigFromTable(c, dc.getID(), "config_seedlists"); createConfigSeedlistsEntries(c, d, dc); } /** * Create the xref table for seedlists used by configurations. * @param c * A connection to the database * @param d * A domain to operate on. * @param dc * A configuration to create xref table for. * @throws SQLException * If any database problems occur during the insertion of * seedlist entries for the given domain configuration */ private void createConfigSeedlistsEntries( Connection c, Domain d, DomainConfiguration dc) throws SQLException { PreparedStatement s = c.prepareStatement("INSERT INTO config_seedlists " + " ( config_id, seedlist_id ) " + "SELECT configurations.config_id, seedlists.seedlist_id" + " FROM configurations, seedlists" + " WHERE configurations.name = ?" + " AND seedlists.name = ?" + " AND configurations.domain_id = ?" + " AND seedlists.domain_id = ?"); for (Iterator<SeedList> seedlists = dc.getSeedLists(); seedlists .hasNext();) { SeedList sl = seedlists.next(); s.setString(1, dc.getName()); s.setString(2, sl.getName()); s.setLong(3, d.getID()); s.setLong(4, d.getID()); s.executeUpdate(); s.clearParameters(); } } @Override protected synchronized Domain read(Connection c, String domainName) { ArgumentNotValid.checkNotNullOrEmpty(domainName, "domainName"); if (!exists(domainName)) { throw new UnknownID("No domain by the name '" + domainName + "'"); } Domain result; PreparedStatement s = null; try { s = c.prepareStatement("SELECT domains.domain_id, " + "domains.comments, " + "domains.crawlertraps, " + "domains.edition, " + "configurations.name, " + " (SELECT name FROM domains as aliasdomains" + " WHERE aliasdomains.domain_id = domains.alias), " + "domains.lastaliasupdate " + "FROM domains, configurations " + "WHERE domains.name = ?" + " AND domains.defaultconfig = configurations.config_id"); s.setString(1, domainName); ResultSet res = s.executeQuery(); if (!res.next()) { final String message = "Error reading existing domain '" + domainName + "'"; log.warn(message); throw new IOFailure(message); } int domainId = res.getInt(1); String comments = res.getString(2); String crawlertraps = res.getString(3); long edition = res.getLong(4); String defaultconfig = res.getString(5); String alias = res.getString(6); Date lastAliasUpdate = DBUtils.getDateMaybeNull(res, 7); s.close(); Domain d = new Domain(domainName); d.setComments(comments); // don't throw exception if illegal regexps are found. boolean strictMode = false; d.setCrawlerTraps(Arrays.asList(crawlertraps.split("\n")), strictMode); d.setID(domainId); d.setEdition(edition); if (alias != null) { d.setAliasInfo( new AliasInfo(domainName, alias, lastAliasUpdate)); } readSeedlists(c, d); readPasswords(c, d); readConfigurations(c, d); // Now that configs are in, we can set the default d.setDefaultConfiguration(defaultconfig); readOwnerInfo(c, d); readHistoryInfo(c, d); readExtendedFieldValues(d); result = d; } catch (SQLException e) { throw new IOFailure("SQL Error while reading domain " + domainName + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } return result; } /** * Read the configurations for the domain. This should not be called until * after passwords and seedlists are read. * @param c * A connection to the database * @param d * The domain being read. Its ID must be set. * @throws SQLException * If database errors occur. */ private void readConfigurations( Connection c, Domain d) throws SQLException { // Read the configurations now that passwords and seedlists exist PreparedStatement s = c.prepareStatement("SELECT " + "config_id, " + "configurations.name, " + "comments, " + "ordertemplates.name, " + "maxobjects, " + "maxrate, " + "maxbytes" + " FROM configurations, ordertemplates " + "WHERE domain_id = ?" + " AND configurations.template_id = " + "ordertemplates.template_id"); s.setLong(1, d.getID()); ResultSet res = s.executeQuery(); while (res.next()) { long domainconfigId = res.getLong(1); String domainconfigName = res.getString(2); String domainConfigComments = res.getString(3); String order = res.getString(4); long maxobjects = res.getLong(5); int maxrate = res.getInt(6); long maxbytes = res.getLong(7); PreparedStatement s1 = c.prepareStatement("SELECT seedlists.name " + "FROM seedlists, config_seedlists " + "WHERE config_seedlists.config_id = ? " + "AND config_seedlists.seedlist_id = " + "seedlists.seedlist_id"); s1.setLong(1, domainconfigId); ResultSet seedlistResultset = s1.executeQuery(); List<SeedList> seedlists = new ArrayList<SeedList>(); while (seedlistResultset.next()) { seedlists .add(d.getSeedList(seedlistResultset.getString(1))); } s1.close(); if (seedlists.isEmpty()) { String message = "Configuration " + domainconfigName + " of " + d + " has no seedlists"; log.warn(message); throw new IOFailure(message); } s1 = c.prepareStatement("SELECT passwords.name " + "FROM passwords, config_passwords " + "WHERE config_passwords.config_id = ? " + "AND config_passwords.password_id = " + "passwords.password_id"); s1.setLong(1, domainconfigId); ResultSet passwordResultset = s1.executeQuery(); List<Password> passwords = new ArrayList<Password>(); while (passwordResultset.next()) { passwords .add(d.getPassword(passwordResultset.getString(1))); } DomainConfiguration dc = new DomainConfiguration( domainconfigName, d, seedlists, passwords); dc.setOrderXmlName(order); dc.setMaxObjects(maxobjects); dc.setMaxRequestRate(maxrate); dc.setComments(domainConfigComments); dc.setMaxBytes(maxbytes); dc.setID(domainconfigId); d.addConfiguration(dc); s1.close(); } if (!d.getAllConfigurations().hasNext()) { String message = "Loaded domain " + d + " with no configurations"; log.warn(message); throw new IOFailure(message); } } /** * Read owner info entries for the domain. * @param c * A connection to the database * @param d * The domain being read. Its ID must be set. * @throws SQLException * If database errors occur. */ private void readOwnerInfo(Connection c, Domain d) throws SQLException { // Read owner info PreparedStatement s = c.prepareStatement("SELECT ownerinfo_id, created, info" + " FROM ownerinfo WHERE domain_id = ?"); s.setLong(1, d.getID()); ResultSet res = s.executeQuery(); while (res.next()) { final DomainOwnerInfo ownerinfo = new DomainOwnerInfo(new Date( res.getTimestamp(2).getTime()), res.getString(3)); ownerinfo.setID(res.getLong(1)); d.addOwnerInfo(ownerinfo); } } /** * Read history info entries for the domain. * @param c * A connection to the database * @param d * The domain being read. Its ID must be set. * @throws SQLException * If database errors occur. */ private void readHistoryInfo( Connection c, Domain d) throws SQLException { // Read history info PreparedStatement s = c.prepareStatement( "SELECT historyinfo_id, stopreason, " + "objectcount, bytecount, " + "name, job_id, harvest_id, harvest_time " + "FROM historyinfo, configurations " + "WHERE configurations.domain_id = ?" + " AND historyinfo.config_id = configurations.config_id"); s.setLong(1, d.getID()); ResultSet res = s.executeQuery(); while (res.next()) { long hiID = res.getLong(1); int stopreasonNum = res.getInt(2); StopReason stopreason = StopReason.getStopReason(stopreasonNum); long objectCount = res.getLong(3); long byteCount = res.getLong(4); String configName = res.getString(5); Long jobId = res.getLong(6); if (res.wasNull()) { jobId = null; } long harvestId = res.getLong(7); Date harvestTime = new Date(res.getTimestamp(8).getTime()); HarvestInfo hi; // XML DAOs didn't keep the job id in harvestinfo, so some // entries will be null. hi = new HarvestInfo(harvestId, jobId, d.getName(), configName, harvestTime, byteCount, objectCount, stopreason); hi.setID(hiID); d.getHistory().addHarvestInfo(hi); } } /** * Read passwords for the domain. * @param c * A connection to the database * @param d * The domain being read. Its ID must be set. * @throws SQLException * If database errors occur. */ private void readPasswords(Connection c, Domain d) throws SQLException { PreparedStatement s = c.prepareStatement( "SELECT password_id, name, comments, url, " + "realm, username, password " + "FROM passwords WHERE domain_id = ?"); s.setLong(1, d.getID()); ResultSet res = s.executeQuery(); while (res.next()) { final Password pwd = new Password(res.getString(2), res .getString(3), res.getString(4), res.getString(5), res .getString(6), res.getString(7)); pwd.setID(res.getLong(1)); d.addPassword(pwd); } } /** * Read seedlists for the domain. * @param c * A connection to the database * @param d * The domain being read. Its ID must be set. * @throws SQLException * If database errors occur. */ private void readSeedlists(Connection c, Domain d) throws SQLException { PreparedStatement s = c.prepareStatement( "SELECT seedlist_id, name, comments, seeds" + " FROM seedlists WHERE domain_id = ?"); s.setLong(1, d.getID()); ResultSet res = s.executeQuery(); while (res.next()) { final SeedList seedlist = getSeedListFromResultset(res); d.addSeedList(seedlist); } s.close(); if (!d.getAllSeedLists().hasNext()) { final String msg = "Domain " + d + " loaded with no seedlists"; log.warn(msg); throw new IOFailure(msg); } } /** * Make SeedList based on entry from seedlists * (id, name, comments, seeds). * @param res a Resultset * @return a SeedList based on ResultSet entry. * @throws SQLException if unable to get data from database */ private SeedList getSeedListFromResultset(ResultSet res) throws SQLException { final long seedlistId = res.getLong(1); final String seedlistName = res.getString(2); String seedlistComments = res.getString(3); String seedlistContents = ""; if (DBSpecifics.getInstance().supportsClob()) { Clob clob = res.getClob(4); seedlistContents = clob.getSubString(1, (int) clob.length()); } else { seedlistContents = res.getString(4); } final SeedList seedlist = new SeedList(seedlistName, seedlistContents); seedlist.setComments(seedlistComments); seedlist.setID(seedlistId); return seedlist; } @Override public synchronized boolean exists(String domainName) { ArgumentNotValid.checkNotNullOrEmpty(domainName, "domainName"); Connection c = HarvestDBConnection.get(); try { return exists(c, domainName); } finally { HarvestDBConnection.release(c); } } /** * Return true if a domain with the given name exists. * * @param c an open connection to the harvestDatabase * @param domainName a name of a domain * @return true if a domain with the given name exists, otherwise false. */ private synchronized boolean exists(Connection c, String domainName) { return 1 == DBUtils.selectIntValue(c, "SELECT COUNT(*) FROM domains WHERE name = ?", domainName); } @Override public synchronized int getCountDomains() { Connection c = HarvestDBConnection.get(); try { return DBUtils.selectIntValue(c, "SELECT COUNT(*) FROM domains"); } finally { HarvestDBConnection.release(c); } } @Override public synchronized Iterator<Domain> getAllDomains() { Connection c = HarvestDBConnection.get(); try { List<String> domainNames = DBUtils.selectStringList( c, "SELECT name FROM domains ORDER BY name"); List<Domain> orderedDomains = new LinkedList<Domain>(); for (String name : domainNames) { orderedDomains.add(read(c, name)); } return orderedDomains.iterator(); } finally { HarvestDBConnection.release(c); } } @Override public Iterator<Domain> getAllDomainsInSnapshotHarvestOrder() { Connection c = HarvestDBConnection.get(); try { // Note: maxbytes are ordered with largest first for symmetry // with HarvestDefinition.CompareConfigDesc List<String> domainNames = DBUtils.selectStringList( c, "SELECT domains.name" + " FROM domains, configurations, ordertemplates" + " WHERE domains.defaultconfig=configurations.config_id" + " AND configurations.template_id" + "=ordertemplates.template_id" + " ORDER BY" + " ordertemplates.name," + " configurations.maxbytes DESC," + " domains.name"); return new FilterIterator<String, Domain>(domainNames.iterator()) { public Domain filter(String s) { return read(s); } }; } finally { HarvestDBConnection.release(c); } } @Override public List<String> getDomains(String glob) { ArgumentNotValid.checkNotNullOrEmpty(glob, "glob"); // SQL uses % and _ instead of * and ? String sqlGlob = DBUtils.makeSQLGlob(glob); Connection c = HarvestDBConnection.get(); try { return DBUtils.selectStringList( c, "SELECT name FROM domains WHERE name LIKE ?", sqlGlob); } finally { HarvestDBConnection.release(c); } } @Override public boolean mayDelete(DomainConfiguration config) { ArgumentNotValid.checkNotNull(config, "config"); String defaultConfigName = this.getDefaultDomainConfigurationName(config.getDomainName()); Connection c = HarvestDBConnection.get(); try { // Never delete default config and don't delete configs being used. return !config.getName().equals(defaultConfigName) && !DBUtils.selectAny(c, "SELECT config_id" + " FROM harvest_configs" + " WHERE config_id = ?", config.getID()); } finally { HarvestDBConnection.release(c); } } /** * Get the name of the default configuration for the given domain. * @param domainName a name of a domain * @return the name of the default configuration for the given domain. */ private String getDefaultDomainConfigurationName(String domainName) { Connection c = HarvestDBConnection.get(); try { return DBUtils.selectStringValue(c, "SELECT configurations.name " + "FROM domains, configurations " + "WHERE domains.defaultconfig = configurations.config_id" + " AND domains.name = ?", domainName); } finally { HarvestDBConnection.release(c); } } @Override public synchronized SparseDomain readSparse(String domainName) { ArgumentNotValid.checkNotNullOrEmpty(domainName, "domainName"); Connection c = HarvestDBConnection.get(); try { List<String> domainConfigurationNames = DBUtils.selectStringList( c, "SELECT configurations.name " + " FROM configurations, domains " + "WHERE domains.domain_id = configurations.domain_id " + " AND domains.name = ?", domainName); if (domainConfigurationNames.size() == 0) { throw new UnknownID("No domain exists with name '" + domainName + "'"); } return new SparseDomain(domainName, domainConfigurationNames); } finally { HarvestDBConnection.release(c); } } @Override public List<AliasInfo> getAliases(String domain) { ArgumentNotValid.checkNotNullOrEmpty(domain, "String domain"); List<AliasInfo> resultSet = new ArrayList<AliasInfo>(); Connection c = HarvestDBConnection.get(); PreparedStatement s = null; // return all <domain, alias, lastaliasupdate> tuples // where alias = domain if (!exists(c, domain)) { log.debug("domain named '" + domain + "' does not exist. Returning empty result set"); return resultSet; } try { s = c.prepareStatement("SELECT domains.name, " + "domains.lastaliasupdate " + " FROM domains, domains as fatherDomains " + " WHERE domains.alias = fatherDomains.domain_id AND" + " fatherDomains.name = ?" + " ORDER BY domains.name"); s.setString(1, domain); ResultSet res = s.executeQuery(); while (res.next()) { AliasInfo ai = new AliasInfo(res.getString(1), domain, DBUtils .getDateMaybeNull(res, 2)); resultSet.add(ai); } return resultSet; } catch (SQLException e) { throw new IOFailure("Failure getting alias-information" + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } } @Override public List<AliasInfo> getAllAliases() { List<AliasInfo> resultSet = new ArrayList<AliasInfo>(); Connection c = HarvestDBConnection.get(); PreparedStatement s = null; // return all <domain, alias, lastaliasupdate> tuples // where alias is not-null try { s = c.prepareStatement("SELECT domains.name, " + "(SELECT name FROM domains as aliasdomains" + " WHERE aliasdomains.domain_id " + "= domains.alias), " + " domains.lastaliasupdate " + " FROM domains " + " WHERE domains.alias IS NOT NULL" + " ORDER BY " + " lastaliasupdate ASC"); ResultSet res = s.executeQuery(); while (res.next()) { String domainName = res.getString(1); String aliasOf = res.getString(2); Date lastchanged = DBUtils.getDateMaybeNull(res, 3); AliasInfo ai = new AliasInfo(domainName, aliasOf, lastchanged); resultSet.add(ai); } return resultSet; } catch (SQLException e) { throw new IOFailure("Failure getting alias-information" + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } } /** * Return all TLDs represented by the domains in the domains table. * it was asked that a level X TLD belong appear in TLD list where * the level is <=X for example bidule.bnf.fr belong to .bnf.fr and to .fr * it appear in the level 1 list of TLD and in the level 2 list * @param level maximum level of TLD * @return a list of TLDs * @see DomainDAO#getTLDs(int) */ @Override public List<TLDInfo> getTLDs(int level) { Map<String, TLDInfo> resultMap = new HashMap<String, TLDInfo>(); Connection c = HarvestDBConnection.get(); PreparedStatement s = null; try { s = c.prepareStatement("SELECT name FROM domains"); ResultSet res = s.executeQuery(); while (res.next()) { String domain = res.getString(1); //getting the TLD level of the domain int domainTLDLevel = TLDInfo.getTLDLevel(domain); //restraining to max level if(domainTLDLevel > level) { domainTLDLevel = level; } //looping from level 1 to level max of the domain for(int currentLevel = 1; currentLevel <= domainTLDLevel; currentLevel++){ //getting the tld of the domain by level String tld = TLDInfo.getMultiLevelTLD(domain, currentLevel); TLDInfo i = resultMap.get(tld); if (i == null) { i = new TLDInfo(tld); resultMap.put(tld, i); } i.addSubdomain(domain); } } List<TLDInfo> resultSet = new ArrayList<TLDInfo>(resultMap.values()); Collections.sort(resultSet); return resultSet; } catch (SQLException e) { throw new IOFailure("Failure getting TLD-information" + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } } @Override public HarvestInfo getDomainJobInfo( Job j, String domainName, String configName) { ArgumentNotValid.checkNotNull(j, "j"); ArgumentNotValid.checkNotNullOrEmpty(domainName, "domainName"); ArgumentNotValid.checkNotNullOrEmpty(configName, "configName"); HarvestInfo resultInfo = null; Connection connection = HarvestDBConnection.get(); PreparedStatement s = null; try { // Get domain_id for domainName long domainId = DBUtils.selectLongValue(connection, "SELECT domain_id FROM domains WHERE name=?", domainName); s = connection.prepareStatement("SELECT stopreason, " + "objectcount, bytecount, " + "harvest_time FROM historyinfo WHERE " + "job_id = ? AND " + "config_id = ? AND " + "harvest_id = ?"); s.setLong(1, j.getJobID()); s.setLong(2, DBUtils.selectLongValue(connection, "SELECT config_id FROM configurations " + "WHERE name = ? AND domain_id=?", configName, domainId)); s.setLong(3, j.getOrigHarvestDefinitionID()); ResultSet res = s.executeQuery(); // If no result, the job may not have been run yet // return null HarvestInfo if (res.next()) { StopReason reason = StopReason.getStopReason(res.getInt(1)); long objectCount = res.getLong(2); long byteCount = res.getLong(3); Date harvestTime = res.getDate(4); resultInfo = new HarvestInfo(j.getOrigHarvestDefinitionID(), j.getJobID(), domainName, configName, harvestTime, byteCount, objectCount, reason); } return resultInfo; } catch (SQLException e) { throw new IOFailure("Failure getting DomainJobInfo" + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(connection); } } @Override public List<DomainHarvestInfo> getDomainHarvestInfo(String domainName, boolean latestFirst) { ArgumentNotValid.checkNotNullOrEmpty(domainName, "domainName"); Connection c = HarvestDBConnection.get(); PreparedStatement s = null; final ArrayList<DomainHarvestInfo> domainHarvestInfos = new ArrayList<DomainHarvestInfo>(); final String ascOrDesc = latestFirst ? "DESC" : "ASC"; try { // For historical reasons, not all historyinfo objects have the // information required to find the job that made them. Therefore, // we must left outer join them onto the jobs list to get the // start date and end date for those where they can be found. s = c.prepareStatement("SELECT jobs.job_id, hdname, hdid," + " harvest_num," + " configname, startdate," + " enddate, objectcount, bytecount, stopreason" + " FROM ( " + " SELECT harvestdefinitions.name AS hdname," + " harvestdefinitions.harvest_id AS hdid," + " configurations.name AS configname," + " objectcount, bytecount, job_id, stopreason" + " FROM domains, configurations, historyinfo, " + " harvestdefinitions" + " WHERE domains.name = ? " + " AND domains.domain_id = configurations.domain_id" + " AND historyinfo.config_id = " + "configurations.config_id" + " AND historyinfo.harvest_id = " + "harvestdefinitions.harvest_id" + " ) AS hist" + " LEFT OUTER JOIN jobs" + " ON hist.job_id = jobs.job_id ORDER BY startdate " + ascOrDesc); s.setString(1, domainName); ResultSet res = s.executeQuery(); while (res.next()) { final int jobID = res.getInt(1); final String harvestName = res.getString(2); final int harvestID = res.getInt(3); final int harvestNum = res.getInt(4); final String configName = res.getString(5); final Date startDate = DBUtils.getDateMaybeNull(res, 6); final Date endDate = DBUtils.getDateMaybeNull(res, 7); final long objectCount = res.getLong(8); final long byteCount = res.getLong(9); final StopReason reason = StopReason.getStopReason(res .getInt(10)); domainHarvestInfos.add(new DomainHarvestInfo(domainName, jobID, harvestName, harvestID, harvestNum, configName, startDate, endDate, byteCount, objectCount, reason)); } return domainHarvestInfos; } catch (SQLException e) { String message = "SQL error getting domain harvest info for " + domainName + "\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(message, e); throw new IOFailure(message, e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } } /** * Adds Defaultvalues for all extended fields of this entity. * @param d the domain to which to add the values */ private void addExtendedFieldValues(Domain d) { ExtendedFieldDAO extendedFieldDAO = ExtendedFieldDAO.getInstance(); List<ExtendedField> list = extendedFieldDAO .getAll(ExtendedFieldTypes.DOMAIN); Iterator<ExtendedField> it = list.iterator(); while (it.hasNext()) { ExtendedField ef = it.next(); ExtendedFieldValue efv = new ExtendedFieldValue(); efv.setContent(ef.getDefaultValue()); efv.setExtendedFieldID(ef.getExtendedFieldID()); d.getExtendedFieldValues().add(efv); } } /** * Saves all extended Field values for a Domain in the Database. * @param c Connection to Database * @param d Domain where loaded extended Field Values will be set * * @throws SQLException * If database errors occur. */ private void saveExtendedFieldValues(Connection c, Domain d) throws SQLException { List<ExtendedFieldValue> list = d.getExtendedFieldValues(); for (int i = 0; i < list.size(); i++) { ExtendedFieldValue efv = list.get(i); efv.setInstanceID(d.getID()); ExtendedFieldValueDBDAO dao = (ExtendedFieldValueDBDAO) ExtendedFieldValueDAO.getInstance(); if (efv.getExtendedFieldValueID() != null) { dao.update(c, efv, false); } else { dao.create(c, efv, false); } } } /** * Reads all extended Field values from the database for a domain. * @param d Domain where loaded extended Field Values will be set * * @throws SQLException * If database errors occur. * */ private void readExtendedFieldValues(Domain d) throws SQLException { ExtendedFieldDAO dao = ExtendedFieldDAO.getInstance(); List<ExtendedField> list = dao.getAll(ExtendedFieldTypes.DOMAIN); for (int i = 0; i < list.size(); i++) { ExtendedField ef = list.get(i); ExtendedFieldValueDAO dao2 = ExtendedFieldValueDAO.getInstance(); ExtendedFieldValue efv = dao2.read(ef.getExtendedFieldID(), d.getID()); if (efv == null) { efv = new ExtendedFieldValue(); efv.setExtendedFieldID(ef.getExtendedFieldID()); efv.setInstanceID(d.getID()); efv.setContent(ef.getDefaultValue()); } d.addExtendedFieldValue(efv); } } @Override public DomainConfiguration getDomainConfiguration(String domainName, String configName) { DomainHistory history = getDomainHistory(domainName); List<String> crawlertraps = getCrawlertraps(domainName); Connection c = HarvestDBConnection.get(); List<DomainConfiguration> foundConfigs = new ArrayList<DomainConfiguration>(); PreparedStatement s = null; try { // Read the configurations now that passwords and seedlists exist s = c.prepareStatement("SELECT config_id, " + "configurations.name, " + "comments, " + "ordertemplates.name, " + "maxobjects, " + "maxrate, " + "maxbytes" + " FROM configurations, ordertemplates " + "WHERE domain_id = (SELECT domain_id FROM domains " + " WHERE name=?)" + " AND configurations.name = ?" + " AND configurations.template_id = " + "ordertemplates.template_id"); s.setString(1, domainName); s.setString(2, configName); ResultSet res = s.executeQuery(); while (res.next()) { long domainconfigId = res.getLong(1); String domainconfigName = res.getString(2); String domainConfigComments = res.getString(3); final String order = res.getString(4); long maxobjects = res.getLong(5); int maxrate = res.getInt(6); long maxbytes = res.getLong(7); PreparedStatement s1 = c.prepareStatement( "SELECT seedlists.seedlist_id, seedlists.name, " + " seedlists.comments, seedlists.seeds " + "FROM seedlists, config_seedlists " + "WHERE config_seedlists.config_id = ? " + "AND config_seedlists.seedlist_id = " + "seedlists.seedlist_id"); s1.setLong(1, domainconfigId); ResultSet seedlistResultset = s1.executeQuery(); List<SeedList> seedlists = new ArrayList<SeedList>(); while (seedlistResultset.next()) { SeedList seedlist = getSeedListFromResultset( seedlistResultset); seedlists.add(seedlist); } s1.close(); if (seedlists.isEmpty()) { String message = "Configuration " + domainconfigName + " of domain '" + domainName + " has no seedlists"; log.warn(message); throw new IOFailure(message); } PreparedStatement s2 = c .prepareStatement("SELECT passwords.password_id, " + "passwords.name, passwords.comments, " + "passwords.url, passwords.realm, " + "passwords.username, passwords.password " + "FROM passwords, config_passwords " + "WHERE config_passwords.config_id = ? " + "AND config_passwords.password_id = " + "passwords.password_id"); s2.setLong(1, domainconfigId); ResultSet passwordResultset = s2.executeQuery(); List<Password> passwords = new ArrayList<Password>(); while (passwordResultset.next()) { final Password pwd = new Password( passwordResultset.getString(2), passwordResultset.getString(3), passwordResultset.getString(4), passwordResultset.getString(5), passwordResultset.getString(6), passwordResultset.getString(7)); pwd.setID(passwordResultset.getLong(1)); passwords.add(pwd); } DomainConfiguration dc = new DomainConfiguration( domainconfigName, domainName, history, crawlertraps, seedlists, passwords); dc.setOrderXmlName(order); dc.setMaxObjects(maxobjects); dc.setMaxRequestRate(maxrate); dc.setComments(domainConfigComments); dc.setMaxBytes(maxbytes); dc.setID(domainconfigId); foundConfigs.add(dc); s2.close(); } // While } catch (SQLException e) { throw new IOFailure("Error while fetching DomainConfigration: " + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } return foundConfigs.get(0); } /** * Retrieve the crawlertraps for a specific domain. * TODO should this method be public? * @param domainName the name of a domain. * @return the crawlertraps for given domain. */ private List<String> getCrawlertraps(String domainName) { Connection c = HarvestDBConnection.get(); String traps = null; PreparedStatement s = null; try { s = c.prepareStatement( "SELECT crawlertraps FROM domains WHERE name = ?"); s.setString(1, domainName); ResultSet crawlertrapsResultset = s.executeQuery(); if (crawlertrapsResultset.next()) { traps = crawlertrapsResultset.getString(1); } else { throw new IOFailure("Unable to find crawlertraps for domain '" + domainName + "'. The domain doesn't seem to exist."); } } catch (SQLException e) { throw new IOFailure( "Error while fetching crawlertraps for domain '" + domainName + "': " + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } return Arrays.asList(traps.split("\n")); } @Override public Iterator<HarvestInfo> getHarvestInfoBasedOnPreviousHarvestDefinition( final HarvestDefinition previousHarvestDefinition) { ArgumentNotValid.checkNotNull(previousHarvestDefinition, "previousHarvestDefinition"); // For each domainConfig, get harvest infos if there is any for the // previous harvest definition return new FilterIterator<DomainConfiguration, HarvestInfo>( previousHarvestDefinition.getDomainConfigurations()) { /** * @see FilterIterator#filter(Object) */ protected HarvestInfo filter(DomainConfiguration o){ DomainConfiguration config = o; DomainHistory domainHistory = getDomainHistory(config.getDomainName()); HarvestInfo hi = domainHistory.getSpecifiedHarvestInfo( previousHarvestDefinition.getOid(), config.getName()); return hi; } }; // Here ends the above return-statement } @Override public DomainHistory getDomainHistory(String domainName) { ArgumentNotValid.checkNotNullOrEmpty(domainName, "String domainName"); Connection c = HarvestDBConnection.get(); DomainHistory history = new DomainHistory(); // Read history info PreparedStatement s = null; try { s = c.prepareStatement("SELECT historyinfo_id, stopreason, " + "objectcount, bytecount, " + "name, job_id, harvest_id, harvest_time " + "FROM historyinfo, configurations " + "WHERE configurations.domain_id = " + "(SELECT domain_id FROM domains WHERE name=?)" + " AND historyinfo.config_id " + " = configurations.config_id"); s.setString(1, domainName); ResultSet res = s.executeQuery(); while (res.next()) { long hiID = res.getLong(1); int stopreasonNum = res.getInt(2); StopReason stopreason = StopReason.getStopReason(stopreasonNum); long objectCount = res.getLong(3); long byteCount = res.getLong(4); String configName = res.getString(5); Long jobId = res.getLong(6); if (res.wasNull()) { jobId = null; } long harvestId = res.getLong(7); Date harvestTime = new Date(res.getTimestamp(8).getTime()); HarvestInfo hi; hi = new HarvestInfo(harvestId, jobId, domainName, configName, harvestTime, byteCount, objectCount, stopreason); hi.setID(hiID); history.addHarvestInfo(hi); } } catch (SQLException e) { throw new IOFailure( "Error while fetching DomainHistory for domain '" + domainName + "': " + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } return history; } @Override public List<String> getDomains(String glob, String searchField) { ArgumentNotValid.checkNotNullOrEmpty(glob, "glob"); ArgumentNotValid.checkNotNullOrEmpty(searchField, "searchField"); // SQL uses % and _ instead of * and ? String sqlGlob = DBUtils.makeSQLGlob(glob); Connection c = HarvestDBConnection.get(); try { return DBUtils.selectStringList( c, "SELECT name FROM domains WHERE " + searchField.toLowerCase() + " LIKE ?", sqlGlob); } finally { HarvestDBConnection.release(c); } } }
src/dk/netarkivet/harvester/datamodel/DomainDBDAO.java
/* File: $Id$ * Revision: $Revision$ * Author: $Author$ * Date: $Date$ * * The Netarchive Suite - Software to harvest and preserve websites * Copyright 2004-2012 The Royal Danish Library, the Danish State and * University Library, the National Library of France and the Austrian * National Library. * * This library 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 library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package dk.netarkivet.harvester.datamodel; import java.sql.Clob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import dk.netarkivet.common.exceptions.ArgumentNotValid; import dk.netarkivet.common.exceptions.IOFailure; import dk.netarkivet.common.exceptions.PermissionDenied; import dk.netarkivet.common.exceptions.UnknownID; import dk.netarkivet.common.utils.DBUtils; import dk.netarkivet.common.utils.ExceptionUtils; import dk.netarkivet.common.utils.FilterIterator; import dk.netarkivet.common.utils.StringUtils; import dk.netarkivet.harvester.datamodel.extendedfield.ExtendedField; import dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldDAO; import dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldTypes; import dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldValue; import dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldValueDAO; import dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldValueDBDAO; /** * A database-based implementation of the DomainDAO. * * The statements to create the tables are located in: * <ul> * <li><em>Derby:</em> scripts/sql/createfullhddb.sql</li> * <li><em>MySQL:</em> scripts/sql/createfullhddb.mysql</li> * <li><em>PostgreSQL:</em> scripts/postgresql/netarchivesuite_init.sql</li> * </ul> * */ public class DomainDBDAO extends DomainDAO { /** The log. */ private static final Log log = LogFactory.getLog(DomainDBDAO.class); /** * Creates a database-based implementation of the DomainDAO. Will check that * all schemas have correct versions, and update the ones that haven't. * * @throws IOFailure * on trouble updating tables to new versions, or on tables with * wrong versions that we don't know how to change to expected * version. */ protected DomainDBDAO() { Connection connection = HarvestDBConnection.get(); try { HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.CONFIGURATIONS); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.DOMAINS); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.CONFIGPASSWORDS); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.CONFIGSEEDLISTS); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.SEEDLISTS); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.PASSWORDS); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.OWNERINFO); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.HISTORYINFO); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.EXTENDEDFIELDTYPE); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.EXTENDEDFIELD); HarvesterDatabaseTables.checkVersion(connection, HarvesterDatabaseTables.EXTENDEDFIELDVALUE); } finally { HarvestDBConnection.release(connection); } } @Override protected void create(Connection connection, Domain d) { ArgumentNotValid.checkNotNull(d, "d"); ArgumentNotValid.checkNotNullOrEmpty(d.getName(), "d.getName()"); if (exists(connection, d.getName())) { String msg = "Cannot create already existing domain " + d; log.debug(msg); throw new PermissionDenied(msg); } PreparedStatement s = null; log.debug("trying to create domain with name: " + d.getName()); try { connection.setAutoCommit(false); s = connection.prepareStatement("INSERT INTO domains " + "(name, comments, defaultconfig, crawlertraps, edition," + " alias, lastaliasupdate ) " + "VALUES ( ?, ?, -1, ?, ?, ?, ? )", Statement.RETURN_GENERATED_KEYS); // Id is autogenerated // defaultconfig cannot exist yet, so we put in -1 // until we have configs DBUtils.setName(s, 1, d, Constants.MAX_NAME_SIZE); DBUtils.setComments(s, 2, d, Constants.MAX_COMMENT_SIZE); s.setString(3,StringUtils.conjoin("\n", d .getCrawlerTraps())); long initialEdition = 1; s.setLong(4, initialEdition); AliasInfo aliasInfo = d.getAliasInfo(); DBUtils.setLongMaybeNull(s, 5, aliasInfo == null ? null : DBUtils.selectLongValue(connection, "SELECT domain_id FROM domains WHERE name = ?", aliasInfo.getAliasOf())); DBUtils.setDateMaybeNull(s, 6, aliasInfo == null ? null : aliasInfo .getLastChange()); s.executeUpdate(); d.setID(DBUtils.getGeneratedID(s)); s.close(); Iterator<Password> passwords = d.getAllPasswords(); while (passwords.hasNext()) { Password p = passwords.next(); insertPassword(connection, d, p); } Iterator<SeedList> seedlists = d.getAllSeedLists(); if (!seedlists.hasNext()) { String msg = "No seedlists for domain " + d; log.debug(msg); throw new ArgumentNotValid(msg); } while (seedlists.hasNext()) { SeedList sl = seedlists.next(); insertSeedlist(connection, d, sl); } Iterator<DomainConfiguration> dcs = d.getAllConfigurations(); if (!dcs.hasNext()) { String msg = "No configurations for domain " + d; log.debug(msg); throw new ArgumentNotValid(msg); } while (dcs.hasNext()) { DomainConfiguration dc = dcs.next(); insertConfiguration(connection, d, dc); // Create xref tables for seedlists referenced by this config createConfigSeedlistsEntries(connection, d, dc); // Create xref tables for passwords referenced by this config createConfigPasswordsEntries(connection, d, dc); } // Now that configs are defined, set the default config. s = connection.prepareStatement( "UPDATE domains SET defaultconfig = " + "(SELECT config_id FROM configurations " + "WHERE configurations.name = ? " + "AND configurations.domain_id = ?) " + "WHERE domain_id = ?"); DBUtils.setName(s, 1, d.getDefaultConfiguration(), Constants.MAX_NAME_SIZE); s.setLong(2, d.getID()); s.setLong(3, d.getID()); s.executeUpdate(); s.close(); for (Iterator<HarvestInfo> hi = d.getHistory().getHarvestInfo(); hi.hasNext();) { insertHarvestInfo(connection, d, hi.next()); } for (DomainOwnerInfo doi : d.getAllDomainOwnerInfo()) { insertOwnerInfo(connection, d, doi); } addExtendedFieldValues(d); saveExtendedFieldValues(connection, d); connection.commit(); d.setEdition(initialEdition); } catch (SQLException e) { String message = "SQL error creating domain " + d + " in database" + "\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(message, e); throw new IOFailure(message, e); } finally { DBUtils.rollbackIfNeeded(connection, "creating", d); } } @Override public synchronized void update(Domain d) { ArgumentNotValid.checkNotNull(d, "domain"); if (!exists(d.getName())) { throw new UnknownID("No domain named " + d.getName() + " exists"); } Connection connection = HarvestDBConnection.get(); PreparedStatement s = null; try { connection.setAutoCommit(false); // Domain object may not have ID yet, so get it from the DB long domainID = DBUtils.selectLongValue(connection, "SELECT domain_id FROM domains WHERE name = ?", d.getName()); if (d.hasID() && d.getID() != domainID) { String message = "Domain " + d + " has wrong id: Has " + d.getID() + ", but persistent store claims " + domainID; log.warn(message); throw new ArgumentNotValid(message); } d.setID(domainID); // The alias field is now updated using a separate select request // rather than embedding the select inside the update statement. // This change was needed to accommodate MySQL, and may lower // performance. s = connection.prepareStatement("UPDATE domains SET " + "comments = ?, crawlertraps = ?, edition = ?," + "alias = ?, lastAliasUpdate = ? " + "WHERE domain_id = ? AND edition = ?"); DBUtils.setComments(s, 1, d, Constants.MAX_COMMENT_SIZE); s.setString(3,StringUtils.conjoin("\n", d .getCrawlerTraps())); final long newEdition = d.getEdition() + 1; s.setLong(3, newEdition); AliasInfo aliasInfo = d.getAliasInfo(); DBUtils.setLongMaybeNull(s, 4, aliasInfo == null ? null : DBUtils.selectLongValue(connection, "SELECT domain_id FROM domains WHERE name = ?", aliasInfo.getAliasOf())); DBUtils.setDateMaybeNull(s, 5, aliasInfo == null ? null : aliasInfo.getLastChange()); s.setLong(6, d.getID()); s.setLong(7, d.getEdition()); int rows = s.executeUpdate(); if (rows == 0) { String message = "Edition " + d.getEdition() + " has expired, cannot update " + d; log.debug(message); throw new PermissionDenied(message); } s.close(); updatePasswords(connection, d); updateSeedlists(connection, d); updateConfigurations(connection, d); updateOwnerInfo(connection, d); updateHarvestInfo(connection, d); saveExtendedFieldValues(connection, d); // Now that configs are updated, we can set default_config s = connection.prepareStatement("UPDATE domains SET " + "defaultconfig = (SELECT config_id" + " FROM configurations" + " WHERE domain_id = ?" + " AND name = ?)" + " WHERE domain_id = ?"); s.setLong(1, d.getID()); s.setString(2, d.getDefaultConfiguration().getName()); s.setLong(3, d.getID()); s.executeUpdate(); connection.commit(); d.setEdition(newEdition); } catch (SQLException e) { String message = "SQL error updating domain " + d + " in database" + "\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(message, e); throw new IOFailure(message, e); } finally { DBUtils.closeStatementIfOpen(s); DBUtils.rollbackIfNeeded(connection, "updating", d); HarvestDBConnection.release(connection); } } /** * Update the list of passwords for the given domain, keeping IDs where * applicable. * @param c * A connection to the database * @param d * A domain to update. * @throws SQLException * If any database problems occur during the update process. */ private void updatePasswords(Connection c, Domain d) throws SQLException { Map<String, Long> oldNames = DBUtils.selectStringLongMap( c, "SELECT name, password_id FROM passwords " + "WHERE domain_id = ?", d.getID()); PreparedStatement s = c.prepareStatement("UPDATE passwords SET " + "comments = ?, " + "url = ?, " + "realm = ?, " + "username = ?, " + "password = ? " + "WHERE name = ? AND domain_id = ?"); for (Iterator<Password> pwds = d.getAllPasswords(); pwds.hasNext();) { Password pwd = pwds.next(); if (oldNames.containsKey(pwd.getName())) { DBUtils.setComments(s, 1, pwd, Constants.MAX_COMMENT_SIZE); DBUtils.setStringMaxLength(s, 2, pwd.getPasswordDomain(), Constants.MAX_URL_SIZE, pwd, "password url"); DBUtils.setStringMaxLength(s, 3, pwd.getRealm(), Constants.MAX_REALM_NAME_SIZE, pwd, "password realm"); DBUtils.setStringMaxLength(s, 4, pwd.getUsername(), Constants.MAX_USER_NAME_SIZE, pwd, "password username"); DBUtils.setStringMaxLength(s, 5, pwd.getPassword(), Constants.MAX_PASSWORD_SIZE, pwd, "password"); s.setString(6, pwd.getName()); s.setLong(7, d.getID()); s.executeUpdate(); s.clearParameters(); pwd.setID(oldNames.get(pwd.getName())); oldNames.remove(pwd.getName()); } else { insertPassword(c, d, pwd); } } s.close(); s = c.prepareStatement("DELETE FROM passwords WHERE password_id = ?"); for (Long gone : oldNames.values()) { // Check that we're not deleting something that's in use // Since deletion is very rare, this is allowed to take // some time. String usages = DBUtils.getUsages(c, "SELECT configurations.name" + " FROM configurations, config_passwords" + " WHERE configurations.config_id = " + "config_passwords.config_id" + " AND config_passwords.password_id = ?", gone, gone); if (usages != null) { String name = DBUtils.selectStringValue( c, "SELECT name FROM passwords WHERE password_id = ?", gone); String message = "Cannot delete password " + name + " as it is used in " + usages; log.debug(message); throw new PermissionDenied(message); } s.setLong(1, gone); s.executeUpdate(); s.clearParameters(); } } /** * Update the list of seedlists for the given domain, keeping IDs where * applicable. * @param c A connection to the database * @param d A domain to update. * @throws SQLException * If any database problems occur during the update process. */ private void updateSeedlists(Connection c, Domain d) throws SQLException { Map<String, Long> oldNames = DBUtils.selectStringLongMap(c, "SELECT name, seedlist_id FROM seedlists " + "WHERE domain_id = ?", d.getID()); PreparedStatement s = c.prepareStatement("UPDATE seedlists SET " + "comments = ?, " + "seeds = ? " + "WHERE name = ? AND domain_id = ?"); for (Iterator<SeedList> sls = d.getAllSeedLists(); sls.hasNext();) { SeedList sl = sls.next(); if (oldNames.containsKey(sl.getName())) { DBUtils.setComments(s, 1, sl, Constants.MAX_COMMENT_SIZE); DBUtils.setClobMaxLength(s, 2, sl.getSeedsAsString(), Constants.MAX_SEED_LIST_SIZE, sl, "seedlist"); s.setString(3, sl.getName()); s.setLong(4, d.getID()); s.executeUpdate(); s.clearParameters(); sl.setID(oldNames.get(sl.getName())); oldNames.remove(sl.getName()); } else { insertSeedlist(c, d, sl); } } s.close(); s = c.prepareStatement("DELETE FROM seedlists " + "WHERE seedlist_id = ?"); for (Long gone : oldNames.values()) { // Check that we're not deleting something that's in use // Since deletion is very rare, this is allowed to take // some time. String usages = DBUtils.getUsages(c, "SELECT configurations.name" + " FROM configurations, config_seedlists" + " WHERE configurations.config_id = " + "config_seedlists.config_id" + " AND config_seedlists.seedlist_id = ?", gone, gone); if (usages != null) { String name = DBUtils.selectStringValue( c, "SELECT name FROM seedlists WHERE seedlist_id = ?", gone); String message = "Cannot delete seedlist " + name + " as it is used in " + usages; log.debug(message); throw new PermissionDenied(message); } s.setLong(1, gone); s.executeUpdate(); s.clearParameters(); } } /** * Update the list of configurations for the given domain, keeping IDs where * applicable. This also builds the xref tables for passwords and seedlists * used in configurations, and so should be run after those are updated. * @param connection * A connection to the database * @param d * A domain to update. * @throws SQLException * If any database problems occur during the update process. */ private void updateConfigurations( Connection connection, Domain d) throws SQLException { Map<String, Long> oldNames = DBUtils.selectStringLongMap(connection, "SELECT name, config_id FROM configurations " + "WHERE domain_id = ?", d.getID()); PreparedStatement s = connection.prepareStatement( "UPDATE configurations SET comments = ?, " + "template_id = ( SELECT template_id FROM ordertemplates " + "WHERE name = ? ), " + "maxobjects = ?, " + "maxrate = ?, " + "maxbytes = ? " + "WHERE name = ? AND domain_id = ?"); for (Iterator<DomainConfiguration> dcs = d.getAllConfigurations(); dcs.hasNext();) { DomainConfiguration dc = dcs.next(); if (oldNames.containsKey(dc.getName())) { // Update DBUtils.setComments(s, 1, dc, Constants.MAX_COMMENT_SIZE); s.setString(2, dc.getOrderXmlName()); s.setLong(3, dc.getMaxObjects()); s.setInt(4, dc.getMaxRequestRate()); s.setLong(5, dc.getMaxBytes()); s.setString(6, dc.getName()); s.setLong(7, d.getID()); s.executeUpdate(); s.clearParameters(); dc.setID(oldNames.get(dc.getName())); oldNames.remove(dc.getName()); } else { insertConfiguration(connection, d, dc); } updateConfigPasswordsEntries(connection, d, dc); updateConfigSeedlistsEntries(connection, d, dc); } s.close(); s = connection.prepareStatement("DELETE FROM configurations " + "WHERE config_id = ?"); for (Long gone : oldNames.values()) { // Before deleting, check if this is unused. Since deletion is // rare, this is allowed to take some time to give good output String usages = DBUtils.getUsages(connection, "SELECT harvestdefinitions.name" + " FROM harvestdefinitions, harvest_configs" + " WHERE harvestdefinitions.harvest_id = " + "harvest_configs.harvest_id" + " AND harvest_configs.config_id = ?", gone, gone); if (usages != null) { String name = DBUtils.selectStringValue(connection, "SELECT name FROM configurations " + "WHERE config_id = ?", gone); String message = "Cannot delete configuration " + name + " as it is used in " + usages; log.debug(message); throw new PermissionDenied(message); } s.setLong(1, gone); s.executeUpdate(); s.clearParameters(); } } /** * Update the list of owner info for the given domain, keeping IDs where * applicable. * @param c * A connection to the database * @param d * A domain to update. * @throws SQLException * If any database problems occur during the update process. */ private void updateOwnerInfo(Connection c, Domain d) throws SQLException { List<Long> oldIDs = DBUtils.selectLongList(c, "SELECT ownerinfo_id FROM ownerinfo " + "WHERE domain_id = ?", d.getID()); PreparedStatement s = c.prepareStatement("UPDATE ownerinfo SET " + "created = ?, " + "info = ? " + "WHERE ownerinfo_id = ?"); for (DomainOwnerInfo doi : d.getAllDomainOwnerInfo()) { if (doi.hasID() && oldIDs.remove(doi.getID())) { s.setTimestamp(1, new Timestamp(doi.getDate().getTime())); DBUtils.setStringMaxLength(s, 2, doi.getInfo(), Constants.MAX_OWNERINFO_SIZE, doi, "owner info"); s.setLong(3, doi.getID()); s.executeUpdate(); s.clearParameters(); } else { insertOwnerInfo(c, d, doi); } } if (oldIDs.size() != 0) { String message = "Not allowed to delete ownerinfo " + oldIDs + " on " + d; log.debug(message); throw new IOFailure(message); } } /** * Update the list of harvest info for the given domain, keeping IDs where * applicable. * @param c * A connection to the database * @param d * A domain to update. * @throws SQLException * If any database problems occur during the update process. */ private void updateHarvestInfo(Connection c, Domain d) throws SQLException { List<Long> oldIDs = DBUtils.selectLongList( c, "SELECT historyinfo.historyinfo_id " + "FROM historyinfo, configurations " + "WHERE historyinfo.config_id " + "= configurations.config_id" + " AND configurations.domain_id = ?", d .getID()); PreparedStatement s = c.prepareStatement("UPDATE historyinfo SET " + "stopreason = ?, " + "objectcount = ?, " + "bytecount = ?, " + "config_id = " + " (SELECT config_id FROM configurations, domains" + " WHERE domains.domain_id = ?" + " AND configurations.name = ?" + " AND configurations.domain_id = domains.domain_id), " + "harvest_id = ?, " + "job_id = ? " + "WHERE historyinfo_id = ?"); Iterator<HarvestInfo> his = d.getHistory().getHarvestInfo(); while (his.hasNext()) { HarvestInfo hi = his.next(); if (hi.hasID() && oldIDs.remove(hi.getID())) { s.setInt(1, hi.getStopReason().ordinal()); s.setLong(2, hi.getCountObjectRetrieved()); s.setLong(3, hi.getSizeDataRetrieved()); s.setLong(4, d.getID()); s.setString(5, d.getConfiguration( hi.getDomainConfigurationName()).getName()); s.setLong(6, hi.getHarvestID()); if (hi.getJobID() != null) { s.setLong(7, hi.getJobID()); } else { s.setNull(7, Types.BIGINT); } s.setLong(8, hi.getID()); s.executeUpdate(); s.clearParameters(); } else { insertHarvestInfo(c, d, hi); } } if (oldIDs.size() != 0) { String message = "Not allowed to delete historyinfo " + oldIDs + " on " + d; log.debug(message); throw new IOFailure(message); } } /** * Insert new harvest info for a domain. * @param c * A connection to the database * @param d * A domain to insert on. The domains ID must be correct. * @param harvestInfo * Harvest info to insert. */ private void insertHarvestInfo( Connection c, Domain d, HarvestInfo harvestInfo) { PreparedStatement s = null; try { // Note that the config_id is grabbed from the configurations table. s = c.prepareStatement("INSERT INTO historyinfo " + "( stopreason, objectcount, bytecount, config_id, " + "job_id, harvest_id, harvest_time ) " + "VALUES ( ?, ?, ?, ?, ?, ?, ? )", Statement.RETURN_GENERATED_KEYS); s.setInt(1, harvestInfo.getStopReason().ordinal()); s.setLong(2, harvestInfo.getCountObjectRetrieved()); s.setLong(3, harvestInfo.getSizeDataRetrieved()); // TODO More stable way to get IDs, use a select s.setLong(4, d.getConfiguration( harvestInfo.getDomainConfigurationName()).getID()); if (harvestInfo.getJobID() != null) { s.setLong(5, harvestInfo.getJobID()); } else { s.setNull(5, Types.BIGINT); } s.setLong(6, harvestInfo.getHarvestID()); s.setTimestamp(7, new Timestamp(harvestInfo.getDate().getTime())); s.executeUpdate(); harvestInfo.setID(DBUtils.getGeneratedID(s)); } catch (SQLException e) { throw new IOFailure("SQL error while inserting harvest info " + harvestInfo + " for " + d + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } } /** * Insert new owner info for a domain. * @param c * A connection to the database * @param d * A domain to insert on. The domains ID must be correct. * @param doi * Owner info to insert. * @throws SQLException * If any database problems occur during the insertion process. */ private void insertOwnerInfo( Connection c, Domain d, DomainOwnerInfo doi) throws SQLException { PreparedStatement s = c.prepareStatement("INSERT INTO ownerinfo " + "( domain_id, created, info ) VALUES ( ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); s.setLong(1, d.getID()); s.setTimestamp(2, new Timestamp(doi.getDate().getTime())); s.setString(3, doi.getInfo()); s.executeUpdate(); doi.setID(DBUtils.getGeneratedID(s)); } /** * Insert new seedlist for a domain. * @param c * A connection to the database * @param d * A domain to insert on. The domains ID must be correct. * @param sl * Seedlist to insert. * @throws SQLException * If some database error occurs during the insertion process. */ private void insertSeedlist( Connection c, Domain d, SeedList sl) throws SQLException { PreparedStatement s = c.prepareStatement("INSERT INTO seedlists " + "( name, comments, domain_id, seeds ) " + "VALUES ( ?, ?, ?, ? )", Statement.RETURN_GENERATED_KEYS); // ID is autogenerated DBUtils.setName(s, 1, sl, Constants.MAX_NAME_SIZE); DBUtils.setComments(s, 2, sl, Constants.MAX_COMMENT_SIZE); s.setLong(3, d.getID()); DBUtils.setClobMaxLength(s, 4, sl.getSeedsAsString(), Constants.MAX_SEED_LIST_SIZE, sl, "seedlist"); s.executeUpdate(); sl.setID(DBUtils.getGeneratedID(s)); } /** * Inserts a new password entry into the database. * @param c * A connection to the database * @param d * A domain to insert on. The domains ID must be correct. * @param p * A password entry to insert. * @throws SQLException * If some database error occurs during the insertion process. */ private void insertPassword( Connection c, Domain d, Password p) throws SQLException { PreparedStatement s = c.prepareStatement("INSERT INTO passwords " + "( name, comments, domain_id, url, realm, username, " + "password ) " + "VALUES ( ?, ?, ?, ?, ?, ?, ? )", Statement.RETURN_GENERATED_KEYS); // ID is autogenerated DBUtils.setName(s, 1, p, Constants.MAX_NAME_SIZE); DBUtils.setComments(s, 2, p, Constants.MAX_COMMENT_SIZE); s.setLong(3, d.getID()); DBUtils.setStringMaxLength(s, 4, p.getPasswordDomain(), Constants.MAX_URL_SIZE, p, "password url"); DBUtils.setStringMaxLength(s, 5, p.getRealm(), Constants.MAX_REALM_NAME_SIZE, p, "password realm"); DBUtils.setStringMaxLength(s, 6, p.getUsername(), Constants.MAX_USER_NAME_SIZE, p, "password username"); DBUtils.setStringMaxLength(s, 7, p.getPassword(), Constants.MAX_PASSWORD_SIZE, p, "password"); s.executeUpdate(); p.setID(DBUtils.getGeneratedID(s)); } /** * Insert the basic configuration info into the DB. This does not establish * the connections with seedlists and passwords, use * {create,update}Config{Passwords,Seedlists}Entries for that. * @param connection * A connection to the database * * @param d * a domain * @param dc * a domainconfiguration * @throws SQLException * If some database error occurs during the insertion process. */ private void insertConfiguration( Connection connection, Domain d, DomainConfiguration dc) throws SQLException { long templateId = DBUtils.selectLongValue(connection, "SELECT template_id FROM ordertemplates WHERE name = ?", dc .getOrderXmlName()); PreparedStatement s = connection.prepareStatement( "INSERT INTO configurations " + "( name, comments, domain_id, template_id, maxobjects, " + "maxrate, maxbytes ) " + "VALUES ( ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); // Id is autogenerated DBUtils.setName(s, 1, dc, Constants.MAX_NAME_SIZE); DBUtils.setComments(s, 2, dc, Constants.MAX_COMMENT_SIZE); s.setLong(3, d.getID()); s.setLong(4, templateId); s.setLong(5, dc.getMaxObjects()); s.setInt(6, dc.getMaxRequestRate()); s.setLong(7, dc.getMaxBytes()); int rows = s.executeUpdate(); if (rows != 1) { String message = "Error inserting configuration " + dc; log.warn(message); throw new IOFailure(message); } dc.setID(DBUtils.getGeneratedID(s)); } /** * Delete all entries in the given crossref table that belong to the * configuration. * @param c * A connection to the database * @param configId * The domain configuration to remove entries for. * @param table * One of "config_passwords" or "config_seedlists" * @throws SQLException * If any database problems occur during the delete process. */ private void deleteConfigFromTable( Connection c, long configId, String table) throws SQLException { PreparedStatement s = c.prepareStatement("DELETE FROM " + table + " WHERE " + table + ".config_id = ?"); s.setLong(1, configId); s.executeUpdate(); } /** * Delete all entries from the config_passwords table that refer to the * given configuration and insert the current ones. * @param c * A connection to the database * @param d * A domain to operate on * @param dc * Configuration to update. * @throws SQLException * If any database problems occur during the update process. */ private void updateConfigPasswordsEntries( Connection c, Domain d, DomainConfiguration dc) throws SQLException { deleteConfigFromTable(c, dc.getID(), "config_passwords"); createConfigPasswordsEntries(c, d, dc); } /** * Create the xref table for passwords used by configurations. * @param c * A connection to the database * @param d * A domain to operate on. * @param dc * A configuration to create xref table for. * @throws SQLException * If any database problems occur during the insertion of * password entries for the given domain configuration */ private void createConfigPasswordsEntries( Connection c, Domain d, DomainConfiguration dc) throws SQLException { PreparedStatement s = c.prepareStatement("INSERT INTO config_passwords " + "( config_id, password_id ) " + "SELECT config_id, password_id " + " FROM configurations, passwords" + " WHERE configurations.domain_id = ?" + " AND configurations.name = ?" + " AND passwords.name = ?" + " AND passwords.domain_id = configurations.domain_id"); for (Iterator<Password> passwords = dc.getPasswords(); passwords .hasNext();) { Password p = passwords.next(); s.setLong(1, d.getID()); s.setString(2, dc.getName()); s.setString(3, p.getName()); s.executeUpdate(); s.clearParameters(); } } /** * Delete all entries from the config_seedlists table that refer to the * given configuration and insert the current ones. * @param c An open connection to the harvestDatabase. * * @param d * A domain to operate on * @param dc * Configuration to update. * @throws SQLException * If any database problems occur during the update process. */ private void updateConfigSeedlistsEntries( Connection c, Domain d, DomainConfiguration dc) throws SQLException { deleteConfigFromTable(c, dc.getID(), "config_seedlists"); createConfigSeedlistsEntries(c, d, dc); } /** * Create the xref table for seedlists used by configurations. * @param c * A connection to the database * @param d * A domain to operate on. * @param dc * A configuration to create xref table for. * @throws SQLException * If any database problems occur during the insertion of * seedlist entries for the given domain configuration */ private void createConfigSeedlistsEntries( Connection c, Domain d, DomainConfiguration dc) throws SQLException { PreparedStatement s = c.prepareStatement("INSERT INTO config_seedlists " + " ( config_id, seedlist_id ) " + "SELECT configurations.config_id, seedlists.seedlist_id" + " FROM configurations, seedlists" + " WHERE configurations.name = ?" + " AND seedlists.name = ?" + " AND configurations.domain_id = ?" + " AND seedlists.domain_id = ?"); for (Iterator<SeedList> seedlists = dc.getSeedLists(); seedlists .hasNext();) { SeedList sl = seedlists.next(); s.setString(1, dc.getName()); s.setString(2, sl.getName()); s.setLong(3, d.getID()); s.setLong(4, d.getID()); s.executeUpdate(); s.clearParameters(); } } @Override protected synchronized Domain read(Connection c, String domainName) { ArgumentNotValid.checkNotNullOrEmpty(domainName, "domainName"); if (!exists(domainName)) { throw new UnknownID("No domain by the name '" + domainName + "'"); } Domain result; PreparedStatement s = null; try { s = c.prepareStatement("SELECT domains.domain_id, " + "domains.comments, " + "domains.crawlertraps, " + "domains.edition, " + "configurations.name, " + " (SELECT name FROM domains as aliasdomains" + " WHERE aliasdomains.domain_id = domains.alias), " + "domains.lastaliasupdate " + "FROM domains, configurations " + "WHERE domains.name = ?" + " AND domains.defaultconfig = configurations.config_id"); s.setString(1, domainName); ResultSet res = s.executeQuery(); if (!res.next()) { final String message = "Error reading existing domain '" + domainName + "'"; log.warn(message); throw new IOFailure(message); } int domainId = res.getInt(1); String comments = res.getString(2); String crawlertraps = res.getString(3); long edition = res.getLong(4); String defaultconfig = res.getString(5); String alias = res.getString(6); Date lastAliasUpdate = DBUtils.getDateMaybeNull(res, 7); s.close(); Domain d = new Domain(domainName); d.setComments(comments); // don't throw exception if illegal regexps are found. boolean strictMode = false; d.setCrawlerTraps(Arrays.asList(crawlertraps.split("\n")), strictMode); d.setID(domainId); d.setEdition(edition); if (alias != null) { d.setAliasInfo( new AliasInfo(domainName, alias, lastAliasUpdate)); } readSeedlists(c, d); readPasswords(c, d); readConfigurations(c, d); // Now that configs are in, we can set the default d.setDefaultConfiguration(defaultconfig); readOwnerInfo(c, d); readHistoryInfo(c, d); readExtendedFieldValues(d); result = d; } catch (SQLException e) { throw new IOFailure("SQL Error while reading domain " + domainName + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } return result; } /** * Read the configurations for the domain. This should not be called until * after passwords and seedlists are read. * @param c * A connection to the database * @param d * The domain being read. Its ID must be set. * @throws SQLException * If database errors occur. */ private void readConfigurations( Connection c, Domain d) throws SQLException { // Read the configurations now that passwords and seedlists exist PreparedStatement s = c.prepareStatement("SELECT " + "config_id, " + "configurations.name, " + "comments, " + "ordertemplates.name, " + "maxobjects, " + "maxrate, " + "maxbytes" + " FROM configurations, ordertemplates " + "WHERE domain_id = ?" + " AND configurations.template_id = " + "ordertemplates.template_id"); s.setLong(1, d.getID()); ResultSet res = s.executeQuery(); while (res.next()) { long domainconfigId = res.getLong(1); String domainconfigName = res.getString(2); String domainConfigComments = res.getString(3); String order = res.getString(4); long maxobjects = res.getLong(5); int maxrate = res.getInt(6); long maxbytes = res.getLong(7); PreparedStatement s1 = c.prepareStatement("SELECT seedlists.name " + "FROM seedlists, config_seedlists " + "WHERE config_seedlists.config_id = ? " + "AND config_seedlists.seedlist_id = " + "seedlists.seedlist_id"); s1.setLong(1, domainconfigId); ResultSet seedlistResultset = s1.executeQuery(); List<SeedList> seedlists = new ArrayList<SeedList>(); while (seedlistResultset.next()) { seedlists .add(d.getSeedList(seedlistResultset.getString(1))); } s1.close(); if (seedlists.isEmpty()) { String message = "Configuration " + domainconfigName + " of " + d + " has no seedlists"; log.warn(message); throw new IOFailure(message); } s1 = c.prepareStatement("SELECT passwords.name " + "FROM passwords, config_passwords " + "WHERE config_passwords.config_id = ? " + "AND config_passwords.password_id = " + "passwords.password_id"); s1.setLong(1, domainconfigId); ResultSet passwordResultset = s1.executeQuery(); List<Password> passwords = new ArrayList<Password>(); while (passwordResultset.next()) { passwords .add(d.getPassword(passwordResultset.getString(1))); } DomainConfiguration dc = new DomainConfiguration( domainconfigName, d, seedlists, passwords); dc.setOrderXmlName(order); dc.setMaxObjects(maxobjects); dc.setMaxRequestRate(maxrate); dc.setComments(domainConfigComments); dc.setMaxBytes(maxbytes); dc.setID(domainconfigId); d.addConfiguration(dc); s1.close(); } if (!d.getAllConfigurations().hasNext()) { String message = "Loaded domain " + d + " with no configurations"; log.warn(message); throw new IOFailure(message); } } /** * Read owner info entries for the domain. * @param c * A connection to the database * @param d * The domain being read. Its ID must be set. * @throws SQLException * If database errors occur. */ private void readOwnerInfo(Connection c, Domain d) throws SQLException { // Read owner info PreparedStatement s = c.prepareStatement("SELECT ownerinfo_id, created, info" + " FROM ownerinfo WHERE domain_id = ?"); s.setLong(1, d.getID()); ResultSet res = s.executeQuery(); while (res.next()) { final DomainOwnerInfo ownerinfo = new DomainOwnerInfo(new Date( res.getTimestamp(2).getTime()), res.getString(3)); ownerinfo.setID(res.getLong(1)); d.addOwnerInfo(ownerinfo); } } /** * Read history info entries for the domain. * @param c * A connection to the database * @param d * The domain being read. Its ID must be set. * @throws SQLException * If database errors occur. */ private void readHistoryInfo( Connection c, Domain d) throws SQLException { // Read history info PreparedStatement s = c.prepareStatement( "SELECT historyinfo_id, stopreason, " + "objectcount, bytecount, " + "name, job_id, harvest_id, harvest_time " + "FROM historyinfo, configurations " + "WHERE configurations.domain_id = ?" + " AND historyinfo.config_id = configurations.config_id"); s.setLong(1, d.getID()); ResultSet res = s.executeQuery(); while (res.next()) { long hiID = res.getLong(1); int stopreasonNum = res.getInt(2); StopReason stopreason = StopReason.getStopReason(stopreasonNum); long objectCount = res.getLong(3); long byteCount = res.getLong(4); String configName = res.getString(5); Long jobId = res.getLong(6); if (res.wasNull()) { jobId = null; } long harvestId = res.getLong(7); Date harvestTime = new Date(res.getTimestamp(8).getTime()); HarvestInfo hi; // XML DAOs didn't keep the job id in harvestinfo, so some // entries will be null. hi = new HarvestInfo(harvestId, jobId, d.getName(), configName, harvestTime, byteCount, objectCount, stopreason); hi.setID(hiID); d.getHistory().addHarvestInfo(hi); } } /** * Read passwords for the domain. * @param c * A connection to the database * @param d * The domain being read. Its ID must be set. * @throws SQLException * If database errors occur. */ private void readPasswords(Connection c, Domain d) throws SQLException { PreparedStatement s = c.prepareStatement( "SELECT password_id, name, comments, url, " + "realm, username, password " + "FROM passwords WHERE domain_id = ?"); s.setLong(1, d.getID()); ResultSet res = s.executeQuery(); while (res.next()) { final Password pwd = new Password(res.getString(2), res .getString(3), res.getString(4), res.getString(5), res .getString(6), res.getString(7)); pwd.setID(res.getLong(1)); d.addPassword(pwd); } } /** * Read seedlists for the domain. * @param c * A connection to the database * @param d * The domain being read. Its ID must be set. * @throws SQLException * If database errors occur. */ private void readSeedlists(Connection c, Domain d) throws SQLException { PreparedStatement s = c.prepareStatement( "SELECT seedlist_id, name, comments, seeds" + " FROM seedlists WHERE domain_id = ?"); s.setLong(1, d.getID()); ResultSet res = s.executeQuery(); while (res.next()) { final SeedList seedlist = getSeedListFromResultset(res); d.addSeedList(seedlist); } s.close(); if (!d.getAllSeedLists().hasNext()) { final String msg = "Domain " + d + " loaded with no seedlists"; log.warn(msg); throw new IOFailure(msg); } } /** * Make SeedList based on entry from seedlists * (id, name, comments, seeds). * @param res a Resultset * @return a SeedList based on ResultSet entry. * @throws SQLException if unable to get data from database */ private SeedList getSeedListFromResultset(ResultSet res) throws SQLException { final long seedlistId = res.getLong(1); final String seedlistName = res.getString(2); String seedlistComments = res.getString(3); String seedlistContents = ""; if (DBSpecifics.getInstance().supportsClob()) { Clob clob = res.getClob(4); seedlistContents = clob.getSubString(1, (int) clob.length()); } else { seedlistContents = res.getString(4); } final SeedList seedlist = new SeedList(seedlistName, seedlistContents); seedlist.setComments(seedlistComments); seedlist.setID(seedlistId); return seedlist; } @Override public synchronized boolean exists(String domainName) { ArgumentNotValid.checkNotNullOrEmpty(domainName, "domainName"); Connection c = HarvestDBConnection.get(); try { return exists(c, domainName); } finally { HarvestDBConnection.release(c); } } /** * Return true if a domain with the given name exists. * * @param c an open connection to the harvestDatabase * @param domainName a name of a domain * @return true if a domain with the given name exists, otherwise false. */ private synchronized boolean exists(Connection c, String domainName) { return 1 == DBUtils.selectIntValue(c, "SELECT COUNT(*) FROM domains WHERE name = ?", domainName); } @Override public synchronized int getCountDomains() { Connection c = HarvestDBConnection.get(); try { return DBUtils.selectIntValue(c, "SELECT COUNT(*) FROM domains"); } finally { HarvestDBConnection.release(c); } } @Override public synchronized Iterator<Domain> getAllDomains() { Connection c = HarvestDBConnection.get(); try { List<String> domainNames = DBUtils.selectStringList( c, "SELECT name FROM domains ORDER BY name"); List<Domain> orderedDomains = new LinkedList<Domain>(); for (String name : domainNames) { orderedDomains.add(read(c, name)); } return orderedDomains.iterator(); } finally { HarvestDBConnection.release(c); } } @Override public Iterator<Domain> getAllDomainsInSnapshotHarvestOrder() { Connection c = HarvestDBConnection.get(); try { // Note: maxbytes are ordered with largest first for symmetry // with HarvestDefinition.CompareConfigDesc List<String> domainNames = DBUtils.selectStringList( c, "SELECT domains.name" + " FROM domains, configurations, ordertemplates" + " WHERE domains.defaultconfig=configurations.config_id" + " AND configurations.template_id" + "=ordertemplates.template_id" + " ORDER BY" + " ordertemplates.name," + " configurations.maxbytes DESC," + " domains.name"); return new FilterIterator<String, Domain>(domainNames.iterator()) { public Domain filter(String s) { return read(s); } }; } finally { HarvestDBConnection.release(c); } } @Override public List<String> getDomains(String glob) { ArgumentNotValid.checkNotNullOrEmpty(glob, "glob"); // SQL uses % and _ instead of * and ? String sqlGlob = DBUtils.makeSQLGlob(glob); Connection c = HarvestDBConnection.get(); try { return DBUtils.selectStringList( c, "SELECT name FROM domains WHERE name LIKE ?", sqlGlob); } finally { HarvestDBConnection.release(c); } } @Override public boolean mayDelete(DomainConfiguration config) { ArgumentNotValid.checkNotNull(config, "config"); String defaultConfigName = this.getDefaultDomainConfigurationName(config.getDomainName()); Connection c = HarvestDBConnection.get(); try { // Never delete default config and don't delete configs being used. return !config.getName().equals(defaultConfigName) && !DBUtils.selectAny(c, "SELECT config_id" + " FROM harvest_configs" + " WHERE config_id = ?", config.getID()); } finally { HarvestDBConnection.release(c); } } /** * Get the name of the default configuration for the given domain. * @param domainName a name of a domain * @return the name of the default configuration for the given domain. */ private String getDefaultDomainConfigurationName(String domainName) { Connection c = HarvestDBConnection.get(); try { return DBUtils.selectStringValue(c, "SELECT configurations.name " + "FROM domains, configurations " + "WHERE domains.defaultconfig = configurations.config_id" + " AND domains.name = ?", domainName); } finally { HarvestDBConnection.release(c); } } @Override public synchronized SparseDomain readSparse(String domainName) { ArgumentNotValid.checkNotNullOrEmpty(domainName, "domainName"); Connection c = HarvestDBConnection.get(); try { List<String> domainConfigurationNames = DBUtils.selectStringList( c, "SELECT configurations.name " + " FROM configurations, domains " + "WHERE domains.domain_id = configurations.domain_id " + " AND domains.name = ?", domainName); if (domainConfigurationNames.size() == 0) { throw new UnknownID("No domain exists with name '" + domainName + "'"); } return new SparseDomain(domainName, domainConfigurationNames); } finally { HarvestDBConnection.release(c); } } @Override public List<AliasInfo> getAliases(String domain) { ArgumentNotValid.checkNotNullOrEmpty(domain, "String domain"); List<AliasInfo> resultSet = new ArrayList<AliasInfo>(); Connection c = HarvestDBConnection.get(); PreparedStatement s = null; // return all <domain, alias, lastaliasupdate> tuples // where alias = domain if (!exists(c, domain)) { log.debug("domain named '" + domain + "' does not exist. Returning empty result set"); return resultSet; } try { s = c.prepareStatement("SELECT domains.name, " + "domains.lastaliasupdate " + " FROM domains, domains as fatherDomains " + " WHERE domains.alias = fatherDomains.domain_id AND" + " fatherDomains.name = ?" + " ORDER BY domains.name"); s.setString(1, domain); ResultSet res = s.executeQuery(); while (res.next()) { AliasInfo ai = new AliasInfo(res.getString(1), domain, DBUtils .getDateMaybeNull(res, 2)); resultSet.add(ai); } return resultSet; } catch (SQLException e) { throw new IOFailure("Failure getting alias-information" + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } } @Override public List<AliasInfo> getAllAliases() { List<AliasInfo> resultSet = new ArrayList<AliasInfo>(); Connection c = HarvestDBConnection.get(); PreparedStatement s = null; // return all <domain, alias, lastaliasupdate> tuples // where alias is not-null try { s = c.prepareStatement("SELECT domains.name, " + "(SELECT name FROM domains as aliasdomains" + " WHERE aliasdomains.domain_id " + "= domains.alias), " + " domains.lastaliasupdate " + " FROM domains " + " WHERE domains.alias IS NOT NULL" + " ORDER BY " + " lastaliasupdate ASC"); ResultSet res = s.executeQuery(); while (res.next()) { String domainName = res.getString(1); String aliasOf = res.getString(2); Date lastchanged = DBUtils.getDateMaybeNull(res, 3); AliasInfo ai = new AliasInfo(domainName, aliasOf, lastchanged); resultSet.add(ai); } return resultSet; } catch (SQLException e) { throw new IOFailure("Failure getting alias-information" + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } } /** * Return all TLDs represented by the domains in the domains table. * it was asked that a level X TLD belong appear in TLD list where * the level is <=X for example bidule.bnf.fr belong to .bnf.fr and to .fr * it appear in the level 1 list of TLD and in the level 2 list * @param level maximum level of TLD * @return a list of TLDs * @see DomainDAO#getTLDs(int) */ @Override public List<TLDInfo> getTLDs(int level) { Map<String, TLDInfo> resultMap = new HashMap<String, TLDInfo>(); Connection c = HarvestDBConnection.get(); PreparedStatement s = null; try { s = c.prepareStatement("SELECT name FROM domains"); ResultSet res = s.executeQuery(); while (res.next()) { String domain = res.getString(1); //getting the TLD level of the domain int domainTLDLevel = TLDInfo.getTLDLevel(domain); //restraining to max level if(domainTLDLevel > level) { domainTLDLevel = level; } //looping from level 1 to level max of the domain for(int currentLevel = 1; currentLevel <= domainTLDLevel; currentLevel++){ //getting the tld of the domain by level String tld = TLDInfo.getMultiLevelTLD(domain, currentLevel); TLDInfo i = resultMap.get(tld); if (i == null) { i = new TLDInfo(tld); resultMap.put(tld, i); } i.addSubdomain(domain); } } List<TLDInfo> resultSet = new ArrayList<TLDInfo>(resultMap.values()); Collections.sort(resultSet); return resultSet; } catch (SQLException e) { throw new IOFailure("Failure getting TLD-information" + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } } @Override public HarvestInfo getDomainJobInfo( Job j, String domainName, String configName) { ArgumentNotValid.checkNotNull(j, "j"); ArgumentNotValid.checkNotNullOrEmpty(domainName, "domainName"); ArgumentNotValid.checkNotNullOrEmpty(configName, "configName"); HarvestInfo resultInfo = null; Connection connection = HarvestDBConnection.get(); PreparedStatement s = null; try { // Get domain_id for domainName long domainId = DBUtils.selectLongValue(connection, "SELECT domain_id FROM domains WHERE name=?", domainName); s = connection.prepareStatement("SELECT stopreason, " + "objectcount, bytecount, " + "harvest_time FROM historyinfo WHERE " + "job_id = ? AND " + "config_id = ? AND " + "harvest_id = ?"); s.setLong(1, j.getJobID()); s.setLong(2, DBUtils.selectLongValue(connection, "SELECT config_id FROM configurations " + "WHERE name = ? AND domain_id=?", configName, domainId)); s.setLong(3, j.getOrigHarvestDefinitionID()); ResultSet res = s.executeQuery(); // If no result, the job may not have been run yet // return null HarvestInfo if (res.next()) { StopReason reason = StopReason.getStopReason(res.getInt(1)); long objectCount = res.getLong(2); long byteCount = res.getLong(3); Date harvestTime = res.getDate(4); resultInfo = new HarvestInfo(j.getOrigHarvestDefinitionID(), j.getJobID(), domainName, configName, harvestTime, byteCount, objectCount, reason); } return resultInfo; } catch (SQLException e) { throw new IOFailure("Failure getting DomainJobInfo" + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(connection); } } @Override public List<DomainHarvestInfo> getDomainHarvestInfo(String domainName, boolean latestFirst) { ArgumentNotValid.checkNotNullOrEmpty(domainName, "domainName"); Connection c = HarvestDBConnection.get(); PreparedStatement s = null; final ArrayList<DomainHarvestInfo> domainHarvestInfos = new ArrayList<DomainHarvestInfo>(); final String ascOrDesc = latestFirst ? "DESC" : "ASC"; try { // For historical reasons, not all historyinfo objects have the // information required to find the job that made them. Therefore, // we must left outer join them onto the jobs list to get the // start date and end date for those where they can be found. s = c.prepareStatement("SELECT jobs.job_id, hdname, hdid," + " harvest_num," + " configname, startdate," + " enddate, objectcount, bytecount, stopreason" + " FROM ( " + " SELECT harvestdefinitions.name AS hdname," + " harvestdefinitions.harvest_id AS hdid," + " configurations.name AS configname," + " objectcount, bytecount, job_id, stopreason" + " FROM domains, configurations, historyinfo, " + " harvestdefinitions" + " WHERE domains.name = ? " + " AND domains.domain_id = configurations.domain_id" + " AND historyinfo.config_id = " + "configurations.config_id" + " AND historyinfo.harvest_id = " + "harvestdefinitions.harvest_id" + " ) AS hist" + " LEFT OUTER JOIN jobs" + " ON hist.job_id = jobs.job_id ORDER BY startdate " + ascOrDesc); s.setString(1, domainName); ResultSet res = s.executeQuery(); while (res.next()) { final int jobID = res.getInt(1); final String harvestName = res.getString(2); final int harvestID = res.getInt(3); final int harvestNum = res.getInt(4); final String configName = res.getString(5); final Date startDate = DBUtils.getDateMaybeNull(res, 6); final Date endDate = DBUtils.getDateMaybeNull(res, 7); final long objectCount = res.getLong(8); final long byteCount = res.getLong(9); final StopReason reason = StopReason.getStopReason(res .getInt(10)); domainHarvestInfos.add(new DomainHarvestInfo(domainName, jobID, harvestName, harvestID, harvestNum, configName, startDate, endDate, byteCount, objectCount, reason)); } return domainHarvestInfos; } catch (SQLException e) { String message = "SQL error getting domain harvest info for " + domainName + "\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(message, e); throw new IOFailure(message, e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } } /** * Adds Defaultvalues for all extended fields of this entity. * @param d the domain to which to add the values */ private void addExtendedFieldValues(Domain d) { ExtendedFieldDAO extendedFieldDAO = ExtendedFieldDAO.getInstance(); List<ExtendedField> list = extendedFieldDAO .getAll(ExtendedFieldTypes.DOMAIN); Iterator<ExtendedField> it = list.iterator(); while (it.hasNext()) { ExtendedField ef = it.next(); ExtendedFieldValue efv = new ExtendedFieldValue(); efv.setContent(ef.getDefaultValue()); efv.setExtendedFieldID(ef.getExtendedFieldID()); d.getExtendedFieldValues().add(efv); } } /** * Saves all extended Field values for a Domain in the Database. * @param c Connection to Database * @param d Domain where loaded extended Field Values will be set * * @throws SQLException * If database errors occur. */ private void saveExtendedFieldValues(Connection c, Domain d) throws SQLException { List<ExtendedFieldValue> list = d.getExtendedFieldValues(); for (int i = 0; i < list.size(); i++) { ExtendedFieldValue efv = list.get(i); efv.setInstanceID(d.getID()); ExtendedFieldValueDBDAO dao = (ExtendedFieldValueDBDAO) ExtendedFieldValueDAO.getInstance(); if (efv.getExtendedFieldValueID() != null) { dao.update(c, efv, false); } else { dao.create(c, efv, false); } } } /** * Reads all extended Field values from the database for a domain. * @param d Domain where loaded extended Field Values will be set * * @throws SQLException * If database errors occur. * */ private void readExtendedFieldValues(Domain d) throws SQLException { ExtendedFieldDAO dao = ExtendedFieldDAO.getInstance(); List<ExtendedField> list = dao.getAll(ExtendedFieldTypes.DOMAIN); for (int i = 0; i < list.size(); i++) { ExtendedField ef = list.get(i); ExtendedFieldValueDAO dao2 = ExtendedFieldValueDAO.getInstance(); ExtendedFieldValue efv = dao2.read(ef.getExtendedFieldID(), d.getID()); if (efv == null) { efv = new ExtendedFieldValue(); efv.setExtendedFieldID(ef.getExtendedFieldID()); efv.setInstanceID(d.getID()); efv.setContent(ef.getDefaultValue()); } d.addExtendedFieldValue(efv); } } @Override public DomainConfiguration getDomainConfiguration(String domainName, String configName) { DomainHistory history = getDomainHistory(domainName); List<String> crawlertraps = getCrawlertraps(domainName); Connection c = HarvestDBConnection.get(); List<DomainConfiguration> foundConfigs = new ArrayList<DomainConfiguration>(); PreparedStatement s = null; try { // Read the configurations now that passwords and seedlists exist s = c.prepareStatement("SELECT config_id, " + "configurations.name, " + "comments, " + "ordertemplates.name, " + "maxobjects, " + "maxrate, " + "maxbytes" + " FROM configurations, ordertemplates " + "WHERE domain_id = (SELECT domain_id FROM domains " + " WHERE name=?)" + " AND configurations.name = ?" + " AND configurations.template_id = " + "ordertemplates.template_id"); s.setString(1, domainName); s.setString(2, configName); ResultSet res = s.executeQuery(); while (res.next()) { long domainconfigId = res.getLong(1); String domainconfigName = res.getString(2); String domainConfigComments = res.getString(3); final String order = res.getString(4); long maxobjects = res.getLong(5); int maxrate = res.getInt(6); long maxbytes = res.getLong(7); PreparedStatement s1 = c.prepareStatement( "SELECT seedlists.seedlist_id, seedlists.name, " + " seedlists.comments, seedlists.seeds " + "FROM seedlists, config_seedlists " + "WHERE config_seedlists.config_id = ? " + "AND config_seedlists.seedlist_id = " + "seedlists.seedlist_id"); s1.setLong(1, domainconfigId); ResultSet seedlistResultset = s1.executeQuery(); List<SeedList> seedlists = new ArrayList<SeedList>(); while (seedlistResultset.next()) { SeedList seedlist = getSeedListFromResultset( seedlistResultset); seedlists.add(seedlist); } s1.close(); if (seedlists.isEmpty()) { String message = "Configuration " + domainconfigName + " of domain '" + domainName + " has no seedlists"; log.warn(message); throw new IOFailure(message); } PreparedStatement s2 = c .prepareStatement("SELECT passwords.password_id, " + "passwords.name, passwords.comments, " + "passwords.url, passwords.realm, " + "passwords.username, passwords.password " + "FROM passwords, config_passwords " + "WHERE config_passwords.config_id = ? " + "AND config_passwords.password_id = " + "passwords.password_id"); s2.setLong(1, domainconfigId); ResultSet passwordResultset = s2.executeQuery(); List<Password> passwords = new ArrayList<Password>(); while (passwordResultset.next()) { final Password pwd = new Password( passwordResultset.getString(2), passwordResultset.getString(3), passwordResultset.getString(4), passwordResultset.getString(5), passwordResultset.getString(6), passwordResultset.getString(7)); pwd.setID(passwordResultset.getLong(1)); passwords.add(pwd); } DomainConfiguration dc = new DomainConfiguration( domainconfigName, domainName, history, crawlertraps, seedlists, passwords); dc.setOrderXmlName(order); dc.setMaxObjects(maxobjects); dc.setMaxRequestRate(maxrate); dc.setComments(domainConfigComments); dc.setMaxBytes(maxbytes); dc.setID(domainconfigId); foundConfigs.add(dc); s2.close(); } // While } catch (SQLException e) { throw new IOFailure("Error while fetching DomainConfigration: " + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } return foundConfigs.get(0); } /** * Retrieve the crawlertraps for a specific domain. * TODO should this method be public? * @param domainName the name of a domain. * @return the crawlertraps for given domain. */ private List<String> getCrawlertraps(String domainName) { Connection c = HarvestDBConnection.get(); String traps = null; PreparedStatement s = null; try { s = c.prepareStatement( "SELECT crawlertraps FROM domains WHERE name = ?"); s.setString(1, domainName); ResultSet crawlertrapsResultset = s.executeQuery(); if (crawlertrapsResultset.next()) { traps = crawlertrapsResultset.getString(1); } else { throw new IOFailure("Unable to find crawlertraps for domain '" + domainName + "'. The domain doesn't seem to exist."); } } catch (SQLException e) { throw new IOFailure( "Error while fetching crawlertraps for domain '" + domainName + "': " + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } return Arrays.asList(traps.split("\n")); } @Override public Iterator<HarvestInfo> getHarvestInfoBasedOnPreviousHarvestDefinition( final HarvestDefinition previousHarvestDefinition) { ArgumentNotValid.checkNotNull(previousHarvestDefinition, "previousHarvestDefinition"); // For each domainConfig, get harvest infos if there is any for the // previous harvest definition return new FilterIterator<DomainConfiguration, HarvestInfo>( previousHarvestDefinition.getDomainConfigurations()) { /** * @see FilterIterator#filter(Object) */ protected HarvestInfo filter(DomainConfiguration o){ DomainConfiguration config = o; DomainHistory domainHistory = getDomainHistory(config.getDomainName()); HarvestInfo hi = domainHistory.getSpecifiedHarvestInfo( previousHarvestDefinition.getOid(), config.getName()); return hi; } }; // Here ends the above return-statement } @Override public DomainHistory getDomainHistory(String domainName) { ArgumentNotValid.checkNotNullOrEmpty(domainName, "String domainName"); Connection c = HarvestDBConnection.get(); DomainHistory history = new DomainHistory(); // Read history info PreparedStatement s = null; try { s = c.prepareStatement("SELECT historyinfo_id, stopreason, " + "objectcount, bytecount, " + "name, job_id, harvest_id, harvest_time " + "FROM historyinfo, configurations " + "WHERE configurations.domain_id = " + "(SELECT domain_id FROM domains WHERE name=?)" + " AND historyinfo.config_id " + " = configurations.config_id"); s.setString(1, domainName); ResultSet res = s.executeQuery(); while (res.next()) { long hiID = res.getLong(1); int stopreasonNum = res.getInt(2); StopReason stopreason = StopReason.getStopReason(stopreasonNum); long objectCount = res.getLong(3); long byteCount = res.getLong(4); String configName = res.getString(5); Long jobId = res.getLong(6); if (res.wasNull()) { jobId = null; } long harvestId = res.getLong(7); Date harvestTime = new Date(res.getTimestamp(8).getTime()); HarvestInfo hi; hi = new HarvestInfo(harvestId, jobId, domainName, configName, harvestTime, byteCount, objectCount, stopreason); hi.setID(hiID); history.addHarvestInfo(hi); } } catch (SQLException e) { throw new IOFailure( "Error while fetching DomainHistory for domain '" + domainName + "': " + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } return history; } @Override public List<String> getDomains(String glob, String searchField) { ArgumentNotValid.checkNotNullOrEmpty(glob, "glob"); ArgumentNotValid.checkNotNullOrEmpty(searchField, "searchField"); // SQL uses % and _ instead of * and ? String sqlGlob = DBUtils.makeSQLGlob(glob); Connection c = HarvestDBConnection.get(); try { return DBUtils.selectStringList( c, "SELECT name FROM domains WHERE " + searchField.toLowerCase() + " LIKE ?", sqlGlob); } finally { HarvestDBConnection.release(c); } } }
Tentative fix for NAS2074
src/dk/netarkivet/harvester/datamodel/DomainDBDAO.java
Tentative fix for NAS2074
<ide><path>rc/dk/netarkivet/harvester/datamodel/DomainDBDAO.java <ide> + "alias = ?, lastAliasUpdate = ? " <ide> + "WHERE domain_id = ? AND edition = ?"); <ide> DBUtils.setComments(s, 1, d, Constants.MAX_COMMENT_SIZE); <del> s.setString(3,StringUtils.conjoin("\n", d <add> s.setString(2,StringUtils.conjoin("\n", d <ide> .getCrawlerTraps())); <ide> final long newEdition = d.getEdition() + 1; <ide> s.setLong(3, newEdition);
Java
apache-2.0
e34b16c65685a38ca6b42d49896468980f7d8697
0
aoprisan/net.oauth,aoprisan/net.oauth
/* * Copyright 2008 Netflix, 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 net.oauth.client; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.URL; import java.util.Collection; import java.util.List; import java.util.Map; import junit.framework.TestCase; import net.oauth.OAuth; import net.oauth.OAuthAccessor; import net.oauth.OAuthConsumer; import net.oauth.OAuthMessage; import net.oauth.OAuthProblemException; import net.oauth.client.OAuthClient.ParameterStyle; import net.oauth.client.httpclient4.HttpClient4; import net.oauth.http.HttpMessage; import net.oauth.http.HttpMessageDecoder; import net.oauth.http.HttpResponseMessage; import net.oauth.signature.Echo; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.servlet.GzipFilter; import org.mortbay.thread.BoundedThreadPool; public class OAuthClientTest extends TestCase { public void testRedirect() throws Exception { final OAuthMessage request = new OAuthMessage("GET", "http://google.com/search", OAuth.newList("q", "Java")); final Integer expectedStatus = Integer.valueOf(301); final String expectedLocation = "http://www.google.com/search?q=Java"; for (OAuthClient client : clients) { try { OAuthMessage response = client.invoke(request, OAuthClient.ParameterStyle.BODY); fail("response: " + response); } catch (OAuthProblemException e) { Map<String, Object> parameters = e.getParameters(); assertEquals("status", expectedStatus, parameters.get(HttpResponseMessage.STATUS_CODE)); assertEquals("Location", expectedLocation, parameters.get(HttpResponseMessage.LOCATION)); } } } public void testInvokeMessage() throws Exception { final String echo = "http://localhost:" + port + "/Echo"; final String data = new String(new char[] { 0, 1, ' ', 'a', 127, 128, 0xFF, 0x3000, 0x4E00 }); final byte[] utf8 = data.getBytes("UTF-8"); List<OAuth.Parameter> parameters = OAuth.newList("x", "y", "oauth_token", "t"); String parametersForm = "oauth_token=t&x=y"; final Object[][] messages = new Object[][] { { new OAuthMessage("GET", echo, parameters), "GET\n" + parametersForm + "\n" + "null\n", null }, { new OAuthMessage("POST", echo, parameters), "POST\n" + parametersForm + "\n" + parametersForm.length() + "\n", OAuth.FORM_ENCODED }, { new MessageWithBody("PUT", echo, parameters, "text/OAuthClientTest; charset=\"UTF-8\"", utf8), "PUT\n" + parametersForm + "\n" + utf8.length + "\n" + data, "text/OAuthClientTest; charset=UTF-8" }, { new MessageWithBody("PUT", echo, parameters, "application/octet-stream", utf8), "PUT\n" + parametersForm + "\n" + utf8.length + "\n" + new String(utf8, "ISO-8859-1"), "application/octet-stream" }, { new OAuthMessage("DELETE", echo, parameters), "DELETE\n" + parametersForm + "\n" + "null\n", null } }; final ParameterStyle[] styles = new ParameterStyle[] { ParameterStyle.BODY, ParameterStyle.AUTHORIZATION_HEADER }; final long startTime = System.nanoTime(); for (OAuthClient client : clients) { for (Object[] testCase : messages) { for (ParameterStyle style : styles) { OAuthMessage request = (OAuthMessage) testCase[0]; final String id = client + " " + request.method + " " + style; OAuthMessage response = null; // System.out.println(id + " ..."); try { response = client.invoke(request, style); } catch (Exception e) { AssertionError failure = new AssertionError(id); failure.initCause(e); throw failure; } // System.out.println(response.getDump() // .get(OAuthMessage.HTTP_REQUEST)); String expectedBody = (String) testCase[1]; if ("POST".equalsIgnoreCase(request.method) && style == ParameterStyle.AUTHORIZATION_HEADER) { // Only the non-oauth parameters went in the body. expectedBody = expectedBody.replace("\n" + parametersForm.length() + "\n", "\n3\n"); } String body = response.readBodyAsString(); assertEquals(id, expectedBody, body); assertEquals(id, testCase[2], response.getHeader(HttpMessage.CONTENT_TYPE)); } } } final long endTime = System.nanoTime(); final float elapsedSec = ((float) (endTime - startTime)) / 1000000000L; if (elapsedSec > 10) { fail("elapsed time = " + elapsedSec + " sec"); // This often means the client isn't re-using TCP connections, // and consequently all the Jetty server threads are occupied // waiting for data on the wasted connections. } } public void testGzip() throws Exception { final OAuthConsumer consumer = new OAuthConsumer(null, null, null, null); consumer.setProperty(OAuthConsumer.ACCEPT_ENCODING, HttpMessageDecoder.ACCEPTED); consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, "PLAINTEXT"); final OAuthAccessor accessor = new OAuthAccessor(consumer); final String url = "http://localhost:" + port + "/Echo"; final List<OAuth.Parameter> parameters = OAuth.newList("echoData", "21", OAuth.OAUTH_NONCE, "n", OAuth.OAUTH_TIMESTAMP, "1"); final String expected = "POST\n" + "echoData=21&oauth_consumer_key=&oauth_nonce=n&oauth_signature_method=PLAINTEXT&oauth_timestamp=1&oauth_version=1.0\n" + "abcdefghi1abcdefghi2\n\n" // 21 bytes of data + "134\n" // content-length ; for (OAuthClient client : clients) { try { OAuthMessage response = client.invoke(accessor, "POST", url, parameters); System.out.println(response.getDump().get(HttpMessage.REQUEST)); System.out.println(response.getDump().get(HttpMessage.RESPONSE)); String id = client.getClass().getName(); assertNull(id, response.getHeader(HttpMessage.CONTENT_ENCODING)); assertNull(id, response.getHeader(HttpMessage.CONTENT_LENGTH)); assertEquals(id, expected, response.readBodyAsString()); // assertEqual(id, OAuth.decodeForm(expected), response.getParameters()); } catch (OAuthProblemException e) { Map<String, Object> p = e.getParameters(); System.out.println(p.get(HttpMessage.REQUEST)); System.err.println(p.get(HttpMessage.RESPONSE)); throw e; } catch(Exception e) { AssertionError a = new AssertionError(client.getClass().getName()); a.initCause(e); throw a; } System.out.println(); } } public void testUpload() throws IOException, OAuthProblemException { final String echo = "http://localhost:" + port + "/Echo"; final Class myClass = getClass(); final String sourceName = "/" + myClass.getPackage().getName().replace('.', '/') + "/flower.jpg"; final URL source = myClass.getResource(sourceName); assertNotNull(sourceName, source); for (OAuthClient client : clients) { for (ParameterStyle style : new ParameterStyle[] { ParameterStyle.AUTHORIZATION_HEADER, ParameterStyle.QUERY_STRING }) { final String id = client + " POST " + style; OAuthMessage response = null; InputStream input = source.openStream(); try { OAuthMessage request = new InputStreamMessage(OAuthMessage.PUT, echo, input); request.addParameter(new OAuth.Parameter("oauth_token", "t")); request.getHeaders().add(new OAuth.Parameter("Content-Type", "image/jpeg")); response = client.invoke(request, style); } catch (OAuthProblemException e) { System.err.println(e.getParameters().get(HttpMessage.REQUEST)); System.err.println(e.getParameters().get(HttpMessage.RESPONSE)); throw e; } catch (Exception e) { AssertionError failure = new AssertionError(); failure.initCause(e); throw failure; } finally { input.close(); } assertEquals(id, "image/jpeg", response.getHeader("Content-Type")); byte[] data = readAll(source.openStream()); Integer contentLength = (client.getHttpClient() instanceof HttpClient4) ? null : new Integer( data.length); byte[] expected = concatenate((OAuthMessage.PUT + "\noauth_token=t\n" + contentLength + "\n") .getBytes(), data); byte[] actual = readAll(response.getBodyAsStream()); StreamTest.assertEqual(id, expected, actual); } } } static byte[] readAll(InputStream from) throws IOException { ByteArrayOutputStream into = new ByteArrayOutputStream(); try { byte[] buf = new byte[1024]; for (int n; 0 < (n = from.read(buf));) { into.write(buf, 0, n); } } finally { from.close(); } into.close(); return into.toByteArray(); } static byte[] concatenate(byte[] x, byte[] y) { byte[] z = new byte[x.length + y.length]; System.arraycopy(x, 0, z, 0, x.length); System.arraycopy(y, 0, z, x.length, y.length); return z; } private OAuthClient[] clients; private int port = 1025; private Server server; @Override public void setUp() throws Exception { clients = new OAuthClient[] { new OAuthClient(new URLConnectionClient()), new OAuthClient(new net.oauth.client.httpclient3.HttpClient3()), new OAuthClient(new net.oauth.client.httpclient4.HttpClient4()) }; { // Get an ephemeral local port number: Socket s = new Socket(); s.bind(null); port = s.getLocalPort(); s.close(); } server = new Server(port); Context context = new Context(server, "/", Context.SESSIONS); context.addFilter(GzipFilter.class, "/*", 1); context.addServlet(new ServletHolder(new Echo()), "/Echo/*"); BoundedThreadPool pool = new BoundedThreadPool(); pool.setMaxThreads(4); server.setThreadPool(pool); server.start(); } @Override public void tearDown() throws Exception { server.stop(); } private static class MessageWithBody extends OAuthMessage { public MessageWithBody(String method, String URL, Collection<OAuth.Parameter> parameters, String contentType, byte[] body) { super(method, URL, parameters); this.body = body; Collection<Map.Entry<String, String>> headers = getHeaders(); headers.add(new OAuth.Parameter(HttpMessage.ACCEPT_ENCODING, HttpMessageDecoder.ACCEPTED)); if (body != null) { headers.add(new OAuth.Parameter(HttpMessage.CONTENT_LENGTH, String.valueOf(body.length))); } if (contentType != null) { headers.add(new OAuth.Parameter(HttpMessage.CONTENT_TYPE, contentType)); } } private final byte[] body; @Override public InputStream getBodyAsStream() { return (body == null) ? null : new ByteArrayInputStream(body); } } static class InputStreamMessage extends OAuthMessage { InputStreamMessage(String method, String url, InputStream body) { super(method, url, null); this.body = body; } private final InputStream body; @Override public InputStream getBodyAsStream() throws IOException { return body; } } }
core/src/test/java/net/oauth/client/OAuthClientTest.java
/* * Copyright 2008 Netflix, 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 net.oauth.client; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.URL; import java.util.Collection; import java.util.List; import java.util.Map; import junit.framework.TestCase; import net.oauth.OAuth; import net.oauth.OAuthAccessor; import net.oauth.OAuthConsumer; import net.oauth.OAuthException; import net.oauth.OAuthMessage; import net.oauth.OAuthProblemException; import net.oauth.client.OAuthClient.ParameterStyle; import net.oauth.client.httpclient4.HttpClient4; import net.oauth.http.HttpMessage; import net.oauth.http.HttpMessageDecoder; import net.oauth.http.HttpResponseMessage; import net.oauth.signature.Echo; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.servlet.GzipFilter; import org.mortbay.thread.BoundedThreadPool; public class OAuthClientTest extends TestCase { public void testRedirect() throws Exception { final OAuthMessage request = new OAuthMessage("GET", "http://google.com/search", OAuth.newList("q", "Java")); final Integer expectedStatus = Integer.valueOf(301); final String expectedLocation = "http://www.google.com/search?q=Java"; for (OAuthClient client : clients) { try { OAuthMessage response = client.invoke(request, OAuthClient.ParameterStyle.BODY); fail("response: " + response); } catch (OAuthProblemException e) { Map<String, Object> parameters = e.getParameters(); assertEquals("status", expectedStatus, parameters.get(HttpResponseMessage.STATUS_CODE)); assertEquals("Location", expectedLocation, parameters.get(HttpResponseMessage.LOCATION)); } } } public void testInvokeMessage() throws Exception { final String echo = "http://localhost:" + port + "/Echo"; final String data = new String(new char[] { 0, 1, ' ', 'a', 127, 128, 0xFF, 0x3000, 0x4E00 }); final byte[] utf8 = data.getBytes("UTF-8"); List<OAuth.Parameter> parameters = OAuth.newList("x", "y", "oauth_token", "t"); String parametersForm = "oauth_token=t&x=y"; final Object[][] messages = new Object[][] { { new OAuthMessage("GET", echo, parameters), "GET\n" + parametersForm + "\n" + "null\n", null }, { new OAuthMessage("POST", echo, parameters), "POST\n" + parametersForm + "\n" + parametersForm.length() + "\n", OAuth.FORM_ENCODED }, { new MessageWithBody("PUT", echo, parameters, "text/OAuthClientTest; charset=\"UTF-8\"", utf8), "PUT\n" + parametersForm + "\n" + utf8.length + "\n" + data, "text/OAuthClientTest; charset=UTF-8" }, { new MessageWithBody("PUT", echo, parameters, "application/octet-stream", utf8), "PUT\n" + parametersForm + "\n" + utf8.length + "\n" + new String(utf8, "ISO-8859-1"), "application/octet-stream" }, { new OAuthMessage("DELETE", echo, parameters), "DELETE\n" + parametersForm + "\n" + "null\n", null } }; final ParameterStyle[] styles = new ParameterStyle[] { ParameterStyle.BODY, ParameterStyle.AUTHORIZATION_HEADER }; final long startTime = System.nanoTime(); for (OAuthClient client : clients) { for (Object[] testCase : messages) { for (ParameterStyle style : styles) { OAuthMessage request = (OAuthMessage) testCase[0]; final String id = client + " " + request.method + " " + style; OAuthMessage response = null; // System.out.println(id + " ..."); try { response = client.invoke(request, style); } catch (Exception e) { AssertionError failure = new AssertionError(id); failure.initCause(e); throw failure; } // System.out.println(response.getDump() // .get(OAuthMessage.HTTP_REQUEST)); String expectedBody = (String) testCase[1]; if ("POST".equalsIgnoreCase(request.method) && style == ParameterStyle.AUTHORIZATION_HEADER) { // Only the non-oauth parameters went in the body. expectedBody = expectedBody.replace("\n" + parametersForm.length() + "\n", "\n3\n"); } String body = response.readBodyAsString(); assertEquals(id, expectedBody, body); assertEquals(id, testCase[2], response.getHeader(HttpMessage.CONTENT_TYPE)); } } } final long endTime = System.nanoTime(); final float elapsedSec = ((float) (endTime - startTime)) / 1000000000L; if (elapsedSec > 10) { fail("elapsed time = " + elapsedSec + " sec"); // This often means the client isn't re-using TCP connections, // and consequently all the Jetty server threads are occupied // waiting for data on the wasted connections. } } public void testGzip() throws Exception { final OAuthConsumer consumer = new OAuthConsumer(null, null, null, null); consumer.setProperty(OAuthConsumer.ACCEPT_ENCODING, HttpMessageDecoder.ACCEPTED); consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, "PLAINTEXT"); final OAuthAccessor accessor = new OAuthAccessor(consumer); final String url = "http://localhost:" + port + "/Echo"; final List<OAuth.Parameter> parameters = OAuth.newList("echoData", "21", OAuth.OAUTH_NONCE, "n", OAuth.OAUTH_TIMESTAMP, "1"); final String expected = "POST\n" + "echoData=21&oauth_consumer_key=&oauth_nonce=n&oauth_signature_method=PLAINTEXT&oauth_timestamp=1&oauth_version=1.0\n" + "abcdefghi1abcdefghi2\n\n" // 21 bytes of data + "134\n" // content-length ; for (OAuthClient client : clients) { try { OAuthMessage response = client.invoke(accessor, "POST", url, parameters); System.out.println(response.getDump().get(HttpMessage.REQUEST)); System.out.println(response.getDump().get(HttpMessage.RESPONSE)); String id = client.getClass().getName(); assertNull(id, response.getHeader(HttpMessage.CONTENT_ENCODING)); assertNull(id, response.getHeader(HttpMessage.CONTENT_LENGTH)); assertEquals(id, expected, response.readBodyAsString()); // assertEqual(id, OAuth.decodeForm(expected), response.getParameters()); } catch (OAuthProblemException e) { Map<String, Object> p = e.getParameters(); System.out.println(p.get(HttpMessage.REQUEST)); System.err.println(p.get(HttpMessage.RESPONSE)); throw e; } catch(Exception e) { AssertionError a = new AssertionError(client.getClass().getName()); a.initCause(e); throw a; } System.out.println(); } } public void testUpload() throws IOException { final String echo = "http://localhost:" + port + "/Echo"; final Class myClass = getClass(); final String sourceName = "/" + myClass.getPackage().getName().replace('.', '/') + "/flower.jpg"; final URL source = myClass.getResource(sourceName); assertNotNull(sourceName, source); for (OAuthClient client : clients) { final String id = client.toString(); OAuthMessage response = null; InputStream input = source.openStream(); try { OAuthMessage request = new InputStreamMessage(OAuthMessage.POST, echo, input); request.addParameter(new OAuth.Parameter("oauth_token", "t")); request.getHeaders().add(new OAuth.Parameter("Content-Type", "image/jpeg")); response = client.invoke(request, ParameterStyle.AUTHORIZATION_HEADER); } catch (Exception e) { AssertionError failure = new AssertionError(); failure.initCause(e); throw failure; } finally { input.close(); } assertEquals(id, "image/jpeg", response.getHeader("Content-Type")); byte[] data = readAll(source.openStream()); Integer contentLength = (client.getHttpClient() instanceof HttpClient4) ? null : new Integer(data.length); byte[] expected = concatenate((OAuthMessage.POST + "\noauth_token=t\n" + contentLength + "\n").getBytes(), data); byte[] actual = readAll(response.getBodyAsStream()); StreamTest.assertEqual(id, expected, actual); } } private static byte[] readAll(InputStream from) throws IOException { ByteArrayOutputStream into = new ByteArrayOutputStream(); try { byte[] buf = new byte[1024]; for (int n; 0 < (n = from.read(buf));) { into.write(buf, 0, n); } } finally { from.close(); } into.close(); return into.toByteArray(); } private static byte[] concatenate(byte[] x, byte[] y) { byte[] z = new byte[x.length + y.length]; System.arraycopy(x, 0, z, 0, x.length); System.arraycopy(y, 0, z, x.length, y.length); return z; } private OAuthClient[] clients; private int port = 1025; private Server server; @Override public void setUp() throws Exception { clients = new OAuthClient[] { new OAuthClient(new URLConnectionClient()), new OAuthClient(new net.oauth.client.httpclient3.HttpClient3()), new OAuthClient(new net.oauth.client.httpclient4.HttpClient4()) }; { // Get an ephemeral local port number: Socket s = new Socket(); s.bind(null); port = s.getLocalPort(); s.close(); } server = new Server(port); Context context = new Context(server, "/", Context.SESSIONS); context.addFilter(GzipFilter.class, "/*", 1); context.addServlet(new ServletHolder(new Echo()), "/Echo/*"); BoundedThreadPool pool = new BoundedThreadPool(); pool.setMaxThreads(4); server.setThreadPool(pool); server.start(); } @Override public void tearDown() throws Exception { server.stop(); } private static class MessageWithBody extends OAuthMessage { public MessageWithBody(String method, String URL, Collection<OAuth.Parameter> parameters, String contentType, byte[] body) { super(method, URL, parameters); this.body = body; Collection<Map.Entry<String, String>> headers = getHeaders(); headers.add(new OAuth.Parameter(HttpMessage.ACCEPT_ENCODING, HttpMessageDecoder.ACCEPTED)); if (body != null) { headers.add(new OAuth.Parameter(HttpMessage.CONTENT_LENGTH, String.valueOf(body.length))); } if (contentType != null) { headers.add(new OAuth.Parameter(HttpMessage.CONTENT_TYPE, contentType)); } } private final byte[] body; @Override public InputStream getBodyAsStream() { return (body == null) ? null : new ByteArrayInputStream(body); } } private static class InputStreamMessage extends OAuthMessage { InputStreamMessage(String method, String url, InputStream body) { super(method, url, null); this.body = body; } private final InputStream body; @Override public InputStream getBodyAsStream() throws IOException { return body; } } }
HttpClient4 doesn't send Content-Length git-svn-id: ee4ab06e2b80aa0503c7056b29ac4b88b48aacce@870 f7ae4463-c52f-0410-a7dc-93bad6e629e8
core/src/test/java/net/oauth/client/OAuthClientTest.java
HttpClient4 doesn't send Content-Length
<ide><path>ore/src/test/java/net/oauth/client/OAuthClientTest.java <ide> <ide> import java.io.ByteArrayInputStream; <ide> import java.io.ByteArrayOutputStream; <del>import java.io.FileInputStream; <ide> import java.io.IOException; <ide> import java.io.InputStream; <ide> import java.net.Socket; <ide> import net.oauth.OAuth; <ide> import net.oauth.OAuthAccessor; <ide> import net.oauth.OAuthConsumer; <del>import net.oauth.OAuthException; <ide> import net.oauth.OAuthMessage; <ide> import net.oauth.OAuthProblemException; <ide> import net.oauth.client.OAuthClient.ParameterStyle; <ide> } <ide> } <ide> <del> public void testUpload() throws IOException { <add> public void testUpload() throws IOException, OAuthProblemException { <ide> final String echo = "http://localhost:" + port + "/Echo"; <ide> final Class myClass = getClass(); <ide> final String sourceName = "/" + myClass.getPackage().getName().replace('.', '/') + "/flower.jpg"; <ide> final URL source = myClass.getResource(sourceName); <ide> assertNotNull(sourceName, source); <ide> for (OAuthClient client : clients) { <del> final String id = client.toString(); <del> OAuthMessage response = null; <del> InputStream input = source.openStream(); <del> try { <del> OAuthMessage request = new InputStreamMessage(OAuthMessage.POST, echo, input); <del> request.addParameter(new OAuth.Parameter("oauth_token", "t")); <del> request.getHeaders().add(new OAuth.Parameter("Content-Type", "image/jpeg")); <del> response = client.invoke(request, ParameterStyle.AUTHORIZATION_HEADER); <del> } catch (Exception e) { <del> AssertionError failure = new AssertionError(); <del> failure.initCause(e); <del> throw failure; <del> } finally { <del> input.close(); <del> } <del> assertEquals(id, "image/jpeg", response.getHeader("Content-Type")); <del> byte[] data = readAll(source.openStream()); <del> Integer contentLength = (client.getHttpClient() instanceof HttpClient4) ? null : new Integer(data.length); <del> byte[] expected = concatenate((OAuthMessage.POST + "\noauth_token=t\n" + contentLength + "\n").getBytes(), data); <del> byte[] actual = readAll(response.getBodyAsStream()); <del> StreamTest.assertEqual(id, expected, actual); <del> } <del> } <del> <del> private static byte[] readAll(InputStream from) throws IOException { <add> for (ParameterStyle style : new ParameterStyle[] { ParameterStyle.AUTHORIZATION_HEADER, ParameterStyle.QUERY_STRING }) { <add> final String id = client + " POST " + style; <add> OAuthMessage response = null; <add> InputStream input = source.openStream(); <add> try { <add> OAuthMessage request = new InputStreamMessage(OAuthMessage.PUT, echo, input); <add> request.addParameter(new OAuth.Parameter("oauth_token", "t")); <add> request.getHeaders().add(new OAuth.Parameter("Content-Type", "image/jpeg")); <add> response = client.invoke(request, style); <add> } catch (OAuthProblemException e) { <add> System.err.println(e.getParameters().get(HttpMessage.REQUEST)); <add> System.err.println(e.getParameters().get(HttpMessage.RESPONSE)); <add> throw e; <add> } catch (Exception e) { <add> AssertionError failure = new AssertionError(); <add> failure.initCause(e); <add> throw failure; <add> } finally { <add> input.close(); <add> } <add> assertEquals(id, "image/jpeg", response.getHeader("Content-Type")); <add> byte[] data = readAll(source.openStream()); <add> Integer contentLength = (client.getHttpClient() instanceof HttpClient4) ? null : new Integer( <add> data.length); <add> byte[] expected = concatenate((OAuthMessage.PUT + "\noauth_token=t\n" + contentLength + "\n") <add> .getBytes(), data); <add> byte[] actual = readAll(response.getBodyAsStream()); <add> StreamTest.assertEqual(id, expected, actual); <add> } <add> } <add> } <add> <add> static byte[] readAll(InputStream from) throws IOException { <ide> ByteArrayOutputStream into = new ByteArrayOutputStream(); <ide> try { <ide> byte[] buf = new byte[1024]; <ide> return into.toByteArray(); <ide> } <ide> <del> private static byte[] concatenate(byte[] x, byte[] y) { <add> static byte[] concatenate(byte[] x, byte[] y) { <ide> byte[] z = new byte[x.length + y.length]; <ide> System.arraycopy(x, 0, z, 0, x.length); <ide> System.arraycopy(y, 0, z, x.length, y.length); <ide> } <ide> } <ide> <del> private static class InputStreamMessage extends OAuthMessage <add> static class InputStreamMessage extends OAuthMessage <ide> { <ide> InputStreamMessage(String method, String url, InputStream body) { <ide> super(method, url, null);
Java
bsd-3-clause
error: pathspec 'ccp-nlp-ext-uima-annotators/src/main/java/edu/ucdenver/ccp/nlp/ext/uima/annotators/filter/SlotRemovalFilter_AE.java' did not match any file(s) known to git
1009fb0e094a00f3a1ef1a395bc49eb7fc115c5a
1
UCDenver-ccp/ccp-nlp,UCDenver-ccp/ccp-nlp
/* * SlotRemovalFilter_AE.java * Copyright (C) 2007 Center for Computational Pharmacology, University of Colorado School of Medicine * * 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 edu.ucdenver.ccp.nlp.ext.uima.annotators.filter; import java.util.ArrayList; import java.util.Iterator; import org.apache.uima.UimaContext; import org.apache.uima.analysis_engine.AnalysisEngineDescription; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.resource.metadata.TypeSystemDescription; import org.apache.uima.util.Level; import org.apache.uima.util.Logger; import org.uimafit.component.JCasAnnotator_ImplBase; import org.uimafit.descriptor.ConfigurationParameter; import org.uimafit.factory.AnalysisEngineFactory; import org.uimafit.factory.ConfigurationParameterFactory; import org.uimafit.util.JCasUtil; import edu.ucdenver.ccp.nlp.core.annotation.TextAnnotation; import edu.ucdenver.ccp.nlp.core.mention.ComplexSlotMention; import edu.ucdenver.ccp.nlp.core.mention.PrimitiveSlotMention; import edu.ucdenver.ccp.nlp.core.uima.annotation.CCPTextAnnotation; import edu.ucdenver.ccp.nlp.core.uima.annotation.impl.WrappedCCPTextAnnotation; /** * This filter allows slots to be removed globally by type: REMOVE_ALL, REMOVE_COMPLEX, REMOVE_PRIMITIVE * @author Colorado Computational Pharmacology, UC Denver; [email protected] * */ public class SlotRemovalFilter_AE extends JCasAnnotator_ImplBase { public enum SlotRemovalOption { REMOVE_ALL, REMOVE_COMPLEX, REMOVE_PRIMITIVE } // /* ==== Class/Slot pairs to remove configuration ==== */ // /** // * Parameter name used in the UIMA descriptor file for the array of String specifying which // * slots should be removed // */ // public static final String PARAM_CLASS_SLOT_PAIRS_TO_REMOVE = ConfigurationParameterFactory // .createConfigurationParameterName(SlotRemovalFilter_AE.class, "classSlotPairsToRemove"); // // /** // * the directory where the inlined-annotation files will be written // */ // @ConfigurationParameter(description = "", mandatory = true) // private String[] classSlotPairsToRemove; // // private Map<String, Set<String>> classToSlotNamesToRemoveMap; public static final String PARAM_SLOT_REMOVE_OPTION = ConfigurationParameterFactory .createConfigurationParameterName(SlotRemovalFilter_AE.class, "removeOption"); @ConfigurationParameter(description = "", mandatory = true) private SlotRemovalOption removeOption = null; private Logger logger; @Override public void initialize(UimaContext context) throws ResourceInitializationException { super.initialize(context); // classToSlotNamesToRemoveMap = new HashMap<String, Set<String>>(); // /* read in input parameters, and initialize a list of slots to remove */ // for (String classSlotPair : classSlotPairsToRemove) { // // if (classSlotPair.equals(REMOVE_ALL)) { // removeAllSlots = true; // break; // } // String[] classSlotName = classSlotPair.split("\\|"); // if (classSlotName.length != 2) { // throw new ResourceInitializationException(new // IllegalArgumentException("Invalid class/slot pairing: " // + classSlotPair)); // } // String classNameRegex = classSlotName[0]; // String slotName = classSlotName[1]; // CollectionsUtil.addToOne2ManyUniqueMap(classNameRegex, slotName, // classToSlotNamesToRemoveMap); // } logger = context.getLogger(); logger.log(Level.INFO, "SlotRemovalFilter_AE initialized. Will remove slots defined by: " + removeOption); } /** * cycle through all annotations and remove any slots that have been inputted by the user */ @Override public void process(JCas jCas) throws AnalysisEngineProcessException { // List<CCPTextAnnotation> annotationsToRemove = new ArrayList<CCPTextAnnotation>(); for (Iterator<CCPTextAnnotation> annotIter = JCasUtil.iterator(jCas, CCPTextAnnotation.class); annotIter .hasNext();) { CCPTextAnnotation ccpTa = annotIter.next(); TextAnnotation ta = new WrappedCCPTextAnnotation(ccpTa); try { switch (removeOption) { case REMOVE_ALL: if (ta.getClassMention().getPrimitiveSlotMentions().size() > 0 || ta.getClassMention().getComplexSlotMentions().size() > 0) { logger.log(Level.INFO, "Removing ALL slots from: " + ta.toString()); ta.getClassMention().setComplexSlotMentions(new ArrayList<ComplexSlotMention>()); ta.getClassMention().setPrimitiveSlotMentions(new ArrayList<PrimitiveSlotMention>()); } break; case REMOVE_COMPLEX: if (ta.getClassMention().getComplexSlotMentions().size() > 0) { logger.log(Level.INFO, "Removing complex slots from: " + ta.toString()); ta.getClassMention().setComplexSlotMentions(new ArrayList<ComplexSlotMention>()); logger.log(Level.INFO, "# complex slots remaining: " + ta.getClassMention().getComplexSlotMentions().size()); } break; case REMOVE_PRIMITIVE: if (ta.getClassMention().getPrimitiveSlotMentions().size() > 0) { logger.log(Level.INFO, "Removing primitive slots from: " + ta.toString()); ta.getClassMention().setPrimitiveSlotMentions(new ArrayList<PrimitiveSlotMention>()); } break; default: throw new IllegalArgumentException("Unhandled SlotRemoveOption: " + removeOption.name()); } } catch (Exception e) { throw new AnalysisEngineProcessException(e); } } // else { // throw new UnsupportedOperationException("This needs to be implemented still"); // String mentionName = ccpCM.getMentionName().toLowerCase(); // logger.debug("MentionName: " + mentionName + " MENTION NAMES OF INTEREST: " // + classesOfInterest.toString()); // if (classesOfInterest.contains(mentionName)) { // logger.debug("Found class of interest: " + mentionName); // // FSArray ccpSlots = ccpCM.getSlotMentions(); // // /* // * since the FSArray class has no remove() method, we will create a set of // * CCPSlotMentions that we will keep. If any slots are removed, they will // * not be added to this list, and then this new list will be put into a new // * FSArray, and replace the original FSArray. This is a bit of a // * work-around... perhaps there's a better way. // */ // List<CCPSlotMention> slotsToKeep = new ArrayList<CCPSlotMention>(); // boolean removedAtLeastOneSlot = false; // // if (ccpSlots != null) { // for (int i = 0; i < ccpSlots.size(); i++) { // CCPSlotMention ccpSM = (CCPSlotMention) ccpSlots.get(i); // String slotName = ccpSM.getMentionName().toLowerCase(); // if (slotsToRemoveList.contains(mentionName + "|" + slotName)) { // logger.debug("Found slot of interest: " + slotName); // /* then remove this slot */ // removedAtLeastOneSlot = true; // } else { // /* // * we are not going to remove this slot, so we store it in the // * list // */ // slotsToKeep.add(ccpSM); // } // } // } // // /* // * if we removed a slot, then we need to replace the FSArray for this // * CCPClassMention // */ // if (removedAtLeastOneSlot) { // FSArray keptSlots = new FSArray(jcas, slotsToKeep.size()); // for (int i = 0; i < keptSlots.size(); i++) { // keptSlots.set(i, slotsToKeep.get(i)); // } // ccpCM.setSlotMentions(keptSlots); // } // } // } // } // } // /* // * now remove annotations that had class mention types not in the classMentionTypesToKeep // * list // */ // for (CCPTextAnnotation ccpTA : annotationsToRemove) { // ccpTA.removeFromIndexes(); // ccpTA = null; // } } public static AnalysisEngineDescription getDescription(TypeSystemDescription tsd, SlotRemovalOption removalOption) throws ResourceInitializationException { return AnalysisEngineFactory.createPrimitiveDescription(SlotRemovalFilter_AE.class, tsd, PARAM_SLOT_REMOVE_OPTION, removalOption.name()); } }
ccp-nlp-ext-uima-annotators/src/main/java/edu/ucdenver/ccp/nlp/ext/uima/annotators/filter/SlotRemovalFilter_AE.java
Initial commit of an AE filter that allows slots to be removed globally by type: REMOVE_ALL, REMOVE_COMPLEX, REMOVE_PRIMITIVE
ccp-nlp-ext-uima-annotators/src/main/java/edu/ucdenver/ccp/nlp/ext/uima/annotators/filter/SlotRemovalFilter_AE.java
Initial commit of an AE filter that allows slots to be removed globally by type: REMOVE_ALL, REMOVE_COMPLEX, REMOVE_PRIMITIVE
<ide><path>cp-nlp-ext-uima-annotators/src/main/java/edu/ucdenver/ccp/nlp/ext/uima/annotators/filter/SlotRemovalFilter_AE.java <add>/* <add> * SlotRemovalFilter_AE.java <add> * Copyright (C) 2007 Center for Computational Pharmacology, University of Colorado School of Medicine <add> * <add> * This program is free software; you can redistribute it and/or <add> * modify it under the terms of the GNU General Public License <add> * as published by the Free Software Foundation; either version 2 <add> * of the License, or (at your option) any later version. <add> * <add> * This program is distributed in the hope that it will be useful, <add> * but WITHOUT ANY WARRANTY; without even the implied warranty of <add> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the <add> * GNU General Public License for more details. <add> * <add> * You should have received a copy of the GNU General Public License <add> * along with this program; if not, write to the Free Software <add> * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. <add> * <add> */ <add> <add>package edu.ucdenver.ccp.nlp.ext.uima.annotators.filter; <add> <add>import java.util.ArrayList; <add>import java.util.Iterator; <add> <add>import org.apache.uima.UimaContext; <add>import org.apache.uima.analysis_engine.AnalysisEngineDescription; <add>import org.apache.uima.analysis_engine.AnalysisEngineProcessException; <add>import org.apache.uima.jcas.JCas; <add>import org.apache.uima.resource.ResourceInitializationException; <add>import org.apache.uima.resource.metadata.TypeSystemDescription; <add>import org.apache.uima.util.Level; <add>import org.apache.uima.util.Logger; <add>import org.uimafit.component.JCasAnnotator_ImplBase; <add>import org.uimafit.descriptor.ConfigurationParameter; <add>import org.uimafit.factory.AnalysisEngineFactory; <add>import org.uimafit.factory.ConfigurationParameterFactory; <add>import org.uimafit.util.JCasUtil; <add> <add>import edu.ucdenver.ccp.nlp.core.annotation.TextAnnotation; <add>import edu.ucdenver.ccp.nlp.core.mention.ComplexSlotMention; <add>import edu.ucdenver.ccp.nlp.core.mention.PrimitiveSlotMention; <add>import edu.ucdenver.ccp.nlp.core.uima.annotation.CCPTextAnnotation; <add>import edu.ucdenver.ccp.nlp.core.uima.annotation.impl.WrappedCCPTextAnnotation; <add> <add> <add>/** <add> * This filter allows slots to be removed globally by type: REMOVE_ALL, REMOVE_COMPLEX, REMOVE_PRIMITIVE <add> * @author Colorado Computational Pharmacology, UC Denver; [email protected] <add> * <add> */ <add>public class SlotRemovalFilter_AE extends JCasAnnotator_ImplBase { <add> <add> public enum SlotRemovalOption { <add> REMOVE_ALL, <add> REMOVE_COMPLEX, <add> REMOVE_PRIMITIVE <add> } <add> <add> // /* ==== Class/Slot pairs to remove configuration ==== */ <add> // /** <add> // * Parameter name used in the UIMA descriptor file for the array of String specifying which <add> // * slots should be removed <add> // */ <add> // public static final String PARAM_CLASS_SLOT_PAIRS_TO_REMOVE = ConfigurationParameterFactory <add> // .createConfigurationParameterName(SlotRemovalFilter_AE.class, "classSlotPairsToRemove"); <add> // <add> // /** <add> // * the directory where the inlined-annotation files will be written <add> // */ <add> // @ConfigurationParameter(description = "", mandatory = true) <add> // private String[] classSlotPairsToRemove; <add> // <add> // private Map<String, Set<String>> classToSlotNamesToRemoveMap; <add> <add> public static final String PARAM_SLOT_REMOVE_OPTION = ConfigurationParameterFactory <add> .createConfigurationParameterName(SlotRemovalFilter_AE.class, "removeOption"); <add> <add> @ConfigurationParameter(description = "", mandatory = true) <add> private SlotRemovalOption removeOption = null; <add> <add> private Logger logger; <add> <add> @Override <add> public void initialize(UimaContext context) throws ResourceInitializationException { <add> super.initialize(context); <add> // classToSlotNamesToRemoveMap = new HashMap<String, Set<String>>(); <add> // /* read in input parameters, and initialize a list of slots to remove */ <add> // for (String classSlotPair : classSlotPairsToRemove) { <add> // <add> // if (classSlotPair.equals(REMOVE_ALL)) { <add> // removeAllSlots = true; <add> // break; <add> // } <add> // String[] classSlotName = classSlotPair.split("\\|"); <add> // if (classSlotName.length != 2) { <add> // throw new ResourceInitializationException(new <add> // IllegalArgumentException("Invalid class/slot pairing: " <add> // + classSlotPair)); <add> // } <add> // String classNameRegex = classSlotName[0]; <add> // String slotName = classSlotName[1]; <add> // CollectionsUtil.addToOne2ManyUniqueMap(classNameRegex, slotName, <add> // classToSlotNamesToRemoveMap); <add> // } <add> logger = context.getLogger(); <add> logger.log(Level.INFO, "SlotRemovalFilter_AE initialized. Will remove slots defined by: " + removeOption); <add> } <add> <add> /** <add> * cycle through all annotations and remove any slots that have been inputted by the user <add> */ <add> @Override <add> public void process(JCas jCas) throws AnalysisEngineProcessException { <add> // List<CCPTextAnnotation> annotationsToRemove = new ArrayList<CCPTextAnnotation>(); <add> <add> for (Iterator<CCPTextAnnotation> annotIter = JCasUtil.iterator(jCas, CCPTextAnnotation.class); annotIter <add> .hasNext();) { <add> CCPTextAnnotation ccpTa = annotIter.next(); <add> TextAnnotation ta = new WrappedCCPTextAnnotation(ccpTa); <add> try { <add> switch (removeOption) { <add> case REMOVE_ALL: <add> if (ta.getClassMention().getPrimitiveSlotMentions().size() > 0 <add> || ta.getClassMention().getComplexSlotMentions().size() > 0) { <add> logger.log(Level.INFO, "Removing ALL slots from: " + ta.toString()); <add> ta.getClassMention().setComplexSlotMentions(new ArrayList<ComplexSlotMention>()); <add> ta.getClassMention().setPrimitiveSlotMentions(new ArrayList<PrimitiveSlotMention>()); <add> } <add> break; <add> case REMOVE_COMPLEX: <add> if (ta.getClassMention().getComplexSlotMentions().size() > 0) { <add> logger.log(Level.INFO, "Removing complex slots from: " + ta.toString()); <add> ta.getClassMention().setComplexSlotMentions(new ArrayList<ComplexSlotMention>()); <add> logger.log(Level.INFO, "# complex slots remaining: " <add> + ta.getClassMention().getComplexSlotMentions().size()); <add> } <add> break; <add> case REMOVE_PRIMITIVE: <add> if (ta.getClassMention().getPrimitiveSlotMentions().size() > 0) { <add> logger.log(Level.INFO, "Removing primitive slots from: " + ta.toString()); <add> ta.getClassMention().setPrimitiveSlotMentions(new ArrayList<PrimitiveSlotMention>()); <add> } <add> break; <add> default: <add> throw new IllegalArgumentException("Unhandled SlotRemoveOption: " + removeOption.name()); <add> } <add> } catch (Exception e) { <add> throw new AnalysisEngineProcessException(e); <add> } <add> } <add> // else { <add> // throw new UnsupportedOperationException("This needs to be implemented still"); <add> // String mentionName = ccpCM.getMentionName().toLowerCase(); <add> // logger.debug("MentionName: " + mentionName + " MENTION NAMES OF INTEREST: " <add> // + classesOfInterest.toString()); <add> // if (classesOfInterest.contains(mentionName)) { <add> // logger.debug("Found class of interest: " + mentionName); <add> // <add> // FSArray ccpSlots = ccpCM.getSlotMentions(); <add> // <add> // /* <add> // * since the FSArray class has no remove() method, we will create a set of <add> // * CCPSlotMentions that we will keep. If any slots are removed, they will <add> // * not be added to this list, and then this new list will be put into a new <add> // * FSArray, and replace the original FSArray. This is a bit of a <add> // * work-around... perhaps there's a better way. <add> // */ <add> // List<CCPSlotMention> slotsToKeep = new ArrayList<CCPSlotMention>(); <add> // boolean removedAtLeastOneSlot = false; <add> // <add> // if (ccpSlots != null) { <add> // for (int i = 0; i < ccpSlots.size(); i++) { <add> // CCPSlotMention ccpSM = (CCPSlotMention) ccpSlots.get(i); <add> // String slotName = ccpSM.getMentionName().toLowerCase(); <add> // if (slotsToRemoveList.contains(mentionName + "|" + slotName)) { <add> // logger.debug("Found slot of interest: " + slotName); <add> // /* then remove this slot */ <add> // removedAtLeastOneSlot = true; <add> // } else { <add> // /* <add> // * we are not going to remove this slot, so we store it in the <add> // * list <add> // */ <add> // slotsToKeep.add(ccpSM); <add> // } <add> // } <add> // } <add> // <add> // /* <add> // * if we removed a slot, then we need to replace the FSArray for this <add> // * CCPClassMention <add> // */ <add> // if (removedAtLeastOneSlot) { <add> // FSArray keptSlots = new FSArray(jcas, slotsToKeep.size()); <add> // for (int i = 0; i < keptSlots.size(); i++) { <add> // keptSlots.set(i, slotsToKeep.get(i)); <add> // } <add> // ccpCM.setSlotMentions(keptSlots); <add> // } <add> // } <add> // } <add> <add> // } <add> // } <add> <add> // /* <add> // * now remove annotations that had class mention types not in the classMentionTypesToKeep <add> // * list <add> // */ <add> // for (CCPTextAnnotation ccpTA : annotationsToRemove) { <add> // ccpTA.removeFromIndexes(); <add> // ccpTA = null; <add> // } <add> <add> } <add> <add> public static AnalysisEngineDescription getDescription(TypeSystemDescription tsd, SlotRemovalOption removalOption) <add> throws ResourceInitializationException { <add> return AnalysisEngineFactory.createPrimitiveDescription(SlotRemovalFilter_AE.class, tsd, <add> PARAM_SLOT_REMOVE_OPTION, removalOption.name()); <add> } <add>}
Java
apache-2.0
26d948c166b85e4d08628dabc9c94b96fcce1965
0
gsheldon/optaplanner,baldimir/optaplanner,droolsjbpm/optaplanner,baldimir/optaplanner,droolsjbpm/optaplanner,gsheldon/optaplanner,tkobayas/optaplanner,baldimir/optaplanner,tkobayas/optaplanner,droolsjbpm/optaplanner,gsheldon/optaplanner,baldimir/optaplanner,tkobayas/optaplanner,gsheldon/optaplanner,droolsjbpm/optaplanner,tkobayas/optaplanner
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * 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.optaplanner.core.impl.domain.solution.descriptor; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Collectors; import com.google.common.collect.Collections2; import com.google.common.collect.Iterators; import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.Pair; import org.optaplanner.core.api.domain.autodiscover.AutoDiscoverMemberType; import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty; import org.optaplanner.core.api.domain.solution.PlanningEntityProperty; import org.optaplanner.core.api.domain.solution.PlanningScore; import org.optaplanner.core.api.domain.solution.PlanningSolution; import org.optaplanner.core.api.domain.solution.Solution; import org.optaplanner.core.api.domain.solution.cloner.SolutionCloner; import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty; import org.optaplanner.core.api.domain.solution.drools.ProblemFactProperty; import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider; import org.optaplanner.core.api.score.AbstractBendableScore; import org.optaplanner.core.api.score.Score; import org.optaplanner.core.api.score.buildin.bendable.BendableScore; import org.optaplanner.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore; import org.optaplanner.core.api.score.buildin.bendablelong.BendableLongScore; import org.optaplanner.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore; import org.optaplanner.core.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScore; import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; import org.optaplanner.core.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScore; import org.optaplanner.core.api.score.buildin.hardsoftdouble.HardSoftDoubleScore; import org.optaplanner.core.api.score.buildin.hardsoftlong.HardSoftLongScore; import org.optaplanner.core.api.score.buildin.simple.SimpleScore; import org.optaplanner.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore; import org.optaplanner.core.api.score.buildin.simpledouble.SimpleDoubleScore; import org.optaplanner.core.api.score.buildin.simplelong.SimpleLongScore; import org.optaplanner.core.config.util.ConfigUtils; import org.optaplanner.core.impl.domain.common.ReflectionHelper; import org.optaplanner.core.impl.domain.common.accessor.BeanPropertyMemberAccessor; import org.optaplanner.core.impl.domain.common.accessor.FieldMemberAccessor; import org.optaplanner.core.impl.domain.common.accessor.MemberAccessor; import org.optaplanner.core.impl.domain.entity.descriptor.EntityDescriptor; import org.optaplanner.core.impl.domain.lookup.LookUpStrategyResolver; import org.optaplanner.core.impl.domain.policy.DescriptorPolicy; import org.optaplanner.core.impl.domain.solution.AbstractSolution; import org.optaplanner.core.impl.domain.solution.cloner.FieldAccessingSolutionCloner; import org.optaplanner.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import org.optaplanner.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; import org.optaplanner.core.impl.domain.variable.descriptor.VariableDescriptor; import org.optaplanner.core.impl.score.buildin.bendable.BendableScoreDefinition; import org.optaplanner.core.impl.score.buildin.bendablebigdecimal.BendableBigDecimalScoreDefinition; import org.optaplanner.core.impl.score.buildin.bendablelong.BendableLongScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardmediumsoft.HardMediumSoftScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardmediumsoftlong.HardMediumSoftLongScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardsoft.HardSoftScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardsoftdouble.HardSoftDoubleScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardsoftlong.HardSoftLongScoreDefinition; import org.optaplanner.core.impl.score.buildin.simple.SimpleScoreDefinition; import org.optaplanner.core.impl.score.buildin.simplebigdecimal.SimpleBigDecimalScoreDefinition; import org.optaplanner.core.impl.score.buildin.simpledouble.SimpleDoubleScoreDefinition; import org.optaplanner.core.impl.score.buildin.simplelong.SimpleLongScoreDefinition; import org.optaplanner.core.impl.score.definition.ScoreDefinition; import org.optaplanner.core.impl.score.director.ScoreDirector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.optaplanner.core.config.util.ConfigUtils.MemberAccessorType.*; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class SolutionDescriptor<Solution_> { public static <Solution_> SolutionDescriptor<Solution_> buildSolutionDescriptor(Class<Solution_> solutionClass, Class<?>... entityClasses) { return buildSolutionDescriptor(solutionClass, Arrays.asList(entityClasses), null); } public static <Solution_> SolutionDescriptor<Solution_> buildSolutionDescriptor(Class<Solution_> solutionClass, List<Class<?>> entityClassList, ScoreDefinition deprecatedScoreDefinition) { DescriptorPolicy descriptorPolicy = new DescriptorPolicy(); SolutionDescriptor<Solution_> solutionDescriptor = new SolutionDescriptor<>(solutionClass); solutionDescriptor.processAnnotations(descriptorPolicy, deprecatedScoreDefinition, entityClassList); for (Class<?> entityClass : sortEntityClassList(entityClassList)) { EntityDescriptor<Solution_> entityDescriptor = new EntityDescriptor<>(solutionDescriptor, entityClass); solutionDescriptor.addEntityDescriptor(entityDescriptor); entityDescriptor.processAnnotations(descriptorPolicy); } solutionDescriptor.afterAnnotationsProcessed(descriptorPolicy); return solutionDescriptor; } private static List<Class<?>> sortEntityClassList(List<Class<?>> entityClassList) { List<Class<?>> sortedEntityClassList = new ArrayList<>(entityClassList.size()); for (Class<?> entityClass : entityClassList) { boolean added = false; for (int i = 0; i < sortedEntityClassList.size(); i++) { Class<?> sortedEntityClass = sortedEntityClassList.get(i); if (entityClass.isAssignableFrom(sortedEntityClass)) { sortedEntityClassList.add(i, entityClass); added = true; break; } } if (!added) { sortedEntityClassList.add(entityClass); } } return sortedEntityClassList; } // ************************************************************************ // Non-static members // ************************************************************************ protected final transient Logger logger = LoggerFactory.getLogger(getClass()); private final Class<Solution_> solutionClass; private SolutionCloner<Solution_> solutionCloner; private AutoDiscoverMemberType autoDiscoverMemberType; private final Map<String, MemberAccessor> problemFactMemberAccessorMap; private final Map<String, MemberAccessor> problemFactCollectionMemberAccessorMap; private final Map<String, MemberAccessor> entityMemberAccessorMap; private final Map<String, MemberAccessor> entityCollectionMemberAccessorMap; private MemberAccessor scoreMemberAccessor; private ScoreDefinition scoreDefinition; private final Map<Class<?>, EntityDescriptor<Solution_>> entityDescriptorMap; private final List<Class<?>> reversedEntityClassList; private final ConcurrentMap<Class<?>, EntityDescriptor<Solution_>> lowestEntityDescriptorCache = new ConcurrentHashMap<>(); private LookUpStrategyResolver lookUpStrategyResolver = null; public SolutionDescriptor(Class<Solution_> solutionClass) { this.solutionClass = solutionClass; problemFactMemberAccessorMap = new LinkedHashMap<>(); problemFactCollectionMemberAccessorMap = new LinkedHashMap<>(); entityMemberAccessorMap = new LinkedHashMap<>(); entityCollectionMemberAccessorMap = new LinkedHashMap<>(); entityDescriptorMap = new LinkedHashMap<>(); reversedEntityClassList = new ArrayList<>(); } public void addEntityDescriptor(EntityDescriptor<Solution_> entityDescriptor) { Class<?> entityClass = entityDescriptor.getEntityClass(); for (Class<?> otherEntityClass : entityDescriptorMap.keySet()) { if (entityClass.isAssignableFrom(otherEntityClass)) { throw new IllegalArgumentException("An earlier entityClass (" + otherEntityClass + ") should not be a subclass of a later entityClass (" + entityClass + "). Switch their declaration so superclasses are defined earlier."); } } entityDescriptorMap.put(entityClass, entityDescriptor); reversedEntityClassList.add(0, entityClass); lowestEntityDescriptorCache.put(entityClass, entityDescriptor); } public void processAnnotations(DescriptorPolicy descriptorPolicy, ScoreDefinition deprecatedScoreDefinition, List<Class<?>> entityClassList) { processSolutionAnnotations(descriptorPolicy); ArrayList<Method> potentiallyOverwritingMethodList = new ArrayList<>(); // Iterate inherited members too (unlike for EntityDescriptor where each one is declared) // to make sure each one is registered for (Class<?> lineageClass : ConfigUtils.getAllAnnotatedLineageClasses(solutionClass, PlanningSolution.class)) { List<Member> memberList = ConfigUtils.getDeclaredMembers(lineageClass); for (Member member : memberList) { if (member instanceof Method && potentiallyOverwritingMethodList.stream().anyMatch( m -> member.getName().equals(m.getName()) // Short cut to discard negatives faster && ReflectionHelper.isMethodOverwritten((Method) member, m.getDeclaringClass()))) { // Ignore member because it is an overwritten method continue; } processValueRangeProviderAnnotation(descriptorPolicy, member); processFactEntityOrScoreAnnotation(descriptorPolicy, member, deprecatedScoreDefinition, entityClassList); } potentiallyOverwritingMethodList.ensureCapacity(potentiallyOverwritingMethodList.size() + memberList.size()); memberList.stream().filter(member -> member instanceof Method) .forEach(member -> potentiallyOverwritingMethodList.add((Method) member)); } if (entityCollectionMemberAccessorMap.isEmpty() && entityMemberAccessorMap.isEmpty()) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") must have at least 1 member with a " + PlanningEntityCollectionProperty.class.getSimpleName() + " annotation or a " + PlanningEntityProperty.class.getSimpleName() + " annotation."); } if (Solution.class.isAssignableFrom(solutionClass)) { processLegacySolution(descriptorPolicy, deprecatedScoreDefinition); return; } // Do not check if problemFactCollectionMemberAccessorMap and problemFactMemberAccessorMap are empty // because they are only required for Drools score calculation. if (scoreMemberAccessor == null) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") must have 1 member with a " + PlanningScore.class.getSimpleName() + " annotation.\n" + "Maybe add a getScore() method with a " + PlanningScore.class.getSimpleName() + " annotation."); } } private void processLegacySolution(DescriptorPolicy descriptorPolicy, ScoreDefinition deprecatedScoreDefinition) { if (!problemFactMemberAccessorMap.isEmpty()) { MemberAccessor memberAccessor = problemFactMemberAccessorMap.values().iterator().next(); throw new IllegalStateException("The solutionClass (" + solutionClass + ") which implements the legacy interface " + Solution.class.getSimpleName() + ") must not have a member (" + memberAccessor.getName() + ") with a " + ProblemFactProperty.class.getSimpleName() + " annotation.\n" + "Maybe remove the use of the legacy interface."); } if (!problemFactCollectionMemberAccessorMap.isEmpty()) { MemberAccessor memberAccessor = problemFactCollectionMemberAccessorMap.values().iterator().next(); throw new IllegalStateException("The solutionClass (" + solutionClass + ") which implements the legacy interface " + Solution.class.getSimpleName() + ") must not have a member (" + memberAccessor.getName() + ") with a " + ProblemFactCollectionProperty.class.getSimpleName() + " annotation.\n" + "Maybe remove the use of the legacy interface."); } try { Method getProblemFactsMethod = solutionClass.getMethod("getProblemFacts"); MemberAccessor problemFactsMemberAccessor = new BeanPropertyMemberAccessor(getProblemFactsMethod); problemFactCollectionMemberAccessorMap.put( problemFactsMemberAccessor.getName(), problemFactsMemberAccessor); } catch (NoSuchMethodException e) { throw new IllegalStateException("Impossible situation: the solutionClass (" + solutionClass + ") which implements the legacy interface " + Solution.class.getSimpleName() + ", lacks its getProblemFacts() method.", e); } if (scoreMemberAccessor != null) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") which implements the legacy interface " + Solution.class.getSimpleName() + ") must not have a member (" + scoreMemberAccessor.getName() + ") with a " + PlanningScore.class.getSimpleName() + " annotation.\n" + "Maybe remove the use of the legacy interface."); } try { Method getScoreMethod = solutionClass.getMethod("getScore"); scoreMemberAccessor = new BeanPropertyMemberAccessor(getScoreMethod); } catch (NoSuchMethodException e) { throw new IllegalStateException("Impossible situation: the solutionClass (" + solutionClass + ") which implements the legacy interface " + Solution.class.getSimpleName() + ", lacks its getScore() method.", e); } if (deprecatedScoreDefinition == null) { deprecatedScoreDefinition = new SimpleScoreDefinition(); } scoreDefinition = deprecatedScoreDefinition; Class<? extends Score> scoreClass = extractScoreClass(); if (!scoreClass.isAssignableFrom(scoreDefinition.getScoreClass())) { throw new IllegalArgumentException("The scoreClass (" + scoreClass + ") of solutionClass (" + solutionClass + ") is not the same or a superclass as the scoreDefinition's scoreClass (" + scoreDefinition.getScoreClass() + ")."); } } /** * Only called if Drools score calculation is used. */ public void checkIfProblemFactsExist() { if (problemFactCollectionMemberAccessorMap.isEmpty() && problemFactMemberAccessorMap.isEmpty()) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") must have at least 1 member with a " + ProblemFactCollectionProperty.class.getSimpleName() + " annotation or a " + ProblemFactProperty.class.getSimpleName() + " annotation" + " when used with Drools score calculation."); } } private void processSolutionAnnotations(DescriptorPolicy descriptorPolicy) { PlanningSolution solutionAnnotation = solutionClass.getAnnotation(PlanningSolution.class); if (solutionAnnotation == null) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") has been specified as a solution in the configuration," + " but does not have a " + PlanningSolution.class.getSimpleName() + " annotation."); } autoDiscoverMemberType = solutionAnnotation.autoDiscoverMemberType(); processSolutionCloner(descriptorPolicy, solutionAnnotation); lookUpStrategyResolver = new LookUpStrategyResolver(solutionAnnotation.lookUpStrategyType()); } private void processSolutionCloner(DescriptorPolicy descriptorPolicy, PlanningSolution solutionAnnotation) { Class<? extends SolutionCloner> solutionClonerClass = solutionAnnotation.solutionCloner(); if (solutionClonerClass == PlanningSolution.NullSolutionCloner.class) { solutionClonerClass = null; } if (solutionClonerClass != null) { solutionCloner = ConfigUtils.newInstance(this, "solutionClonerClass", solutionClonerClass); } else { solutionCloner = new FieldAccessingSolutionCloner<>(this); } } private void processValueRangeProviderAnnotation(DescriptorPolicy descriptorPolicy, Member member) { if (((AnnotatedElement) member).isAnnotationPresent(ValueRangeProvider.class)) { MemberAccessor memberAccessor = ConfigUtils.buildMemberAccessor( member, FIELD_OR_READ_METHOD, ValueRangeProvider.class); descriptorPolicy.addFromSolutionValueRangeProvider(memberAccessor); } } private void processFactEntityOrScoreAnnotation(DescriptorPolicy descriptorPolicy, Member member, ScoreDefinition deprecatedScoreDefinition, List<Class<?>> entityClassList) { Class<? extends Annotation> annotationClass = extractFactEntityOrScoreAnnotationClassOrAutoDiscover( member, entityClassList); if (annotationClass == null) { return; } else if (annotationClass.equals(ProblemFactProperty.class) || annotationClass.equals(ProblemFactCollectionProperty.class)) { processProblemFactPropertyAnnotation(descriptorPolicy, member, annotationClass); } else if (annotationClass.equals(PlanningEntityProperty.class) || annotationClass.equals(PlanningEntityCollectionProperty.class)) { processPlanningEntityPropertyAnnotation(descriptorPolicy, member, annotationClass); } else if (annotationClass.equals(PlanningScore.class)) { processScoreAnnotation(descriptorPolicy, member, annotationClass, deprecatedScoreDefinition); } } private Class<? extends Annotation> extractFactEntityOrScoreAnnotationClassOrAutoDiscover( Member member, List<Class<?>> entityClassList) { Class<? extends Annotation> annotationClass = ConfigUtils.extractAnnotationClass(member, ProblemFactProperty.class, ProblemFactCollectionProperty.class, PlanningEntityProperty.class, PlanningEntityCollectionProperty.class, PlanningScore.class); if (annotationClass == null) { Class<?> type; if (autoDiscoverMemberType == AutoDiscoverMemberType.FIELD && member instanceof Field) { Field field = (Field) member; type = field.getType(); } else if (autoDiscoverMemberType == AutoDiscoverMemberType.GETTER && (member instanceof Method) && ReflectionHelper.isGetterMethod((Method) member)) { Method method = (Method) member; type = method.getReturnType(); } else { type = null; } if (type != null) { if (Score.class.isAssignableFrom(type)) { annotationClass = PlanningScore.class; } else if (Collection.class.isAssignableFrom(type)) { Type genericType = (member instanceof Field) ? ((Field) member).getGenericType() : ((Method) member).getGenericReturnType(); Class<?> elementType = ConfigUtils.extractCollectionGenericTypeParameter( "solutionClass", solutionClass, type, genericType, null, member.getName()); if (entityClassList.stream().anyMatch(entityClass -> entityClass.isAssignableFrom(elementType))) { annotationClass = PlanningEntityCollectionProperty.class; } else { annotationClass = ProblemFactCollectionProperty.class; } } else if (Map.class.isAssignableFrom(type)) { throw new IllegalStateException("The autoDiscoverMemberType (" + autoDiscoverMemberType + ") does not yet support the member (" + member + ") of type (" + type + ") which is an implementation of " + Map.class.getSimpleName() + "."); } else if (entityClassList.stream().anyMatch(entityClass -> entityClass.isAssignableFrom(type))) { annotationClass = PlanningEntityProperty.class; } else { annotationClass = ProblemFactProperty.class; } } } return annotationClass; } private void processProblemFactPropertyAnnotation(DescriptorPolicy descriptorPolicy, Member member, Class<? extends Annotation> annotationClass) { MemberAccessor memberAccessor = ConfigUtils.buildMemberAccessor( member, FIELD_OR_READ_METHOD, annotationClass); assertUnexistingProblemFactOrPlanningEntityProperty(memberAccessor, annotationClass); if (annotationClass == ProblemFactProperty.class) { problemFactMemberAccessorMap.put(memberAccessor.getName(), memberAccessor); } else if (annotationClass == ProblemFactCollectionProperty.class) { if (!Collection.class.isAssignableFrom(memberAccessor.getType())) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") has a " + ProblemFactCollectionProperty.class.getSimpleName() + " annotated member (" + member + ") that does not return a " + Collection.class.getSimpleName() + "."); } problemFactCollectionMemberAccessorMap.put(memberAccessor.getName(), memberAccessor); } else { throw new IllegalStateException("Impossible situation with annotationClass (" + annotationClass + ")."); } } private void processPlanningEntityPropertyAnnotation(DescriptorPolicy descriptorPolicy, Member member, Class<? extends Annotation> annotationClass) { MemberAccessor memberAccessor = ConfigUtils.buildMemberAccessor( member, FIELD_OR_GETTER_METHOD, annotationClass); assertUnexistingProblemFactOrPlanningEntityProperty(memberAccessor, annotationClass); if (annotationClass == PlanningEntityProperty.class) { entityMemberAccessorMap.put(memberAccessor.getName(), memberAccessor); } else if (annotationClass == PlanningEntityCollectionProperty.class) { if (!Collection.class.isAssignableFrom(memberAccessor.getType())) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") has a " + PlanningEntityCollectionProperty.class.getSimpleName() + " annotated member (" + member + ") that does not return a " + Collection.class.getSimpleName() + "."); } entityCollectionMemberAccessorMap.put(memberAccessor.getName(), memberAccessor); } else { throw new IllegalStateException("Impossible situation with annotationClass (" + annotationClass + ")."); } } private void assertUnexistingProblemFactOrPlanningEntityProperty( MemberAccessor memberAccessor, Class<? extends Annotation> annotationClass) { MemberAccessor duplicate; Class<? extends Annotation> otherAnnotationClass; String memberName = memberAccessor.getName(); if (problemFactMemberAccessorMap.containsKey(memberName)) { duplicate = problemFactMemberAccessorMap.get(memberName); otherAnnotationClass = ProblemFactProperty.class; } else if (problemFactCollectionMemberAccessorMap.containsKey(memberName)) { duplicate = problemFactCollectionMemberAccessorMap.get(memberName); otherAnnotationClass = ProblemFactCollectionProperty.class; } else if (entityMemberAccessorMap.containsKey(memberName)) { duplicate = entityMemberAccessorMap.get(memberName); otherAnnotationClass = PlanningEntityProperty.class; } else if (entityCollectionMemberAccessorMap.containsKey(memberName)) { duplicate = entityCollectionMemberAccessorMap.get(memberName); otherAnnotationClass = PlanningEntityCollectionProperty.class; } else { return; } throw new IllegalStateException("The solutionClass (" + solutionClass + ") has a " + annotationClass.getSimpleName() + " annotated member (" + memberAccessor + ") that is duplicated by a " + otherAnnotationClass.getSimpleName() + " annotated member (" + duplicate + ").\n" + (annotationClass.equals(otherAnnotationClass) ? "Maybe the annotation is defined on both the field and its getter." : "Maybe 2 mutually exclusive annotations are configured.")); } private void processScoreAnnotation(DescriptorPolicy descriptorPolicy, Member member, Class<? extends Annotation> annotationClass, ScoreDefinition deprecatedScoreDefinition) { MemberAccessor memberAccessor = ConfigUtils.buildMemberAccessor( member, FIELD_OR_GETTER_METHOD_WITH_SETTER, PlanningScore.class); if (deprecatedScoreDefinition != null) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + memberAccessor + ") but the solver configuration still has a deprecated scoreDefinitionType" + " or scoreDefinitionClass element.\n" + "Maybe remove the <scoreDefinitionType>, <bendableHardLevelsSize>, <bendableSoftLevelsSize> and <scoreDefinitionClass> elements from the solver configuration."); } if (!Score.class.isAssignableFrom(memberAccessor.getType())) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + memberAccessor + ") that does not return a subtype of Score."); } if (scoreMemberAccessor != null) { if (!scoreMemberAccessor.getName().equals(memberAccessor.getName()) || !scoreMemberAccessor.getClass().equals(memberAccessor.getClass())) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + memberAccessor + ") that is duplicated by another member (" + scoreMemberAccessor + ").\n" + " Verify that the annotation is not defined on both the field and its getter."); } // Bottom class wins. Bottom classes are parsed first due to ConfigUtil.getAllAnnotatedLineageClasses() return; } scoreMemberAccessor = memberAccessor; Class<? extends Score> scoreType = (Class<? extends Score>) scoreMemberAccessor.getType(); PlanningScore annotation = scoreMemberAccessor.getAnnotation(PlanningScore.class); if (annotation == null) { // The member was autodiscovered try { annotation = AutoDiscoverAnnotationDefaults.class.getDeclaredField("PLANNING_SCORE").getAnnotation(PlanningScore.class); } catch (NoSuchFieldException e) { throw new IllegalStateException("Impossible situation: the field (PLANNING_SCORE) must exist.", e); } } scoreDefinition = buildScoreDefinition(scoreType, annotation); } private static class AutoDiscoverAnnotationDefaults { @PlanningScore private static final Object PLANNING_SCORE = new Object(); } public ScoreDefinition buildScoreDefinition(Class<? extends Score> scoreType, PlanningScore annotation) { Class<? extends ScoreDefinition> scoreDefinitionClass = annotation.scoreDefinitionClass(); if (scoreDefinitionClass != PlanningScore.NullScoreDefinition.class) { if (annotation.bendableHardLevelsSize() != PlanningScore.NO_LEVEL_SIZE || annotation.bendableSoftLevelsSize() != PlanningScore.NO_LEVEL_SIZE) { throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor + ") that has a scoreDefinition (" + scoreDefinitionClass + ") that must not have a bendableHardLevelsSize (" + annotation.bendableHardLevelsSize() + ") or a bendableSoftLevelsSize (" + annotation.bendableSoftLevelsSize() + ")."); } return ConfigUtils.newInstance(this, "scoreDefinitionClass", scoreDefinitionClass); } if (scoreType == Score.class) { if (!AbstractSolution.class.isAssignableFrom(solutionClass)) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor + ") that doesn't return a non-abstract " + Score.class.getSimpleName() + " class.\n" + "Maybe make it return " + HardSoftScore.class.getSimpleName() + " or another specific " + Score.class.getSimpleName() + " implementation."); } else { // Magic to support AbstractSolution if (solutionClass == AbstractSolution.class) { throw new IllegalArgumentException( "The solutionClass (" + solutionClass + ") cannot be directly a " + AbstractSolution.class.getSimpleName() + ", but a subclass would be ok."); } Class<?> baseClass = solutionClass; while (baseClass.getSuperclass() != AbstractSolution.class) { baseClass = baseClass.getSuperclass(); if (baseClass == null) { throw new IllegalStateException( "Impossible situation because the solutionClass (" + solutionClass + ") is assignable from " + AbstractSolution.class.getSimpleName() + "."); } } Type genericAbstractSolution = solutionClass.getGenericSuperclass(); if (!(genericAbstractSolution instanceof ParameterizedType)) { throw new IllegalStateException( "Impossible situation because the genericAbstractSolution (" + genericAbstractSolution + ") is a " + AbstractSolution.class.getSimpleName() + "."); } ParameterizedType parameterizedAbstractSolution = (ParameterizedType) genericAbstractSolution; Type[] typeArguments = parameterizedAbstractSolution.getActualTypeArguments(); if (typeArguments.length != 1) { throw new IllegalStateException( "Impossible situation because the parameterizedAbstractSolution (" + parameterizedAbstractSolution + ") is a " + AbstractSolution.class.getSimpleName() + "."); } Type typeArgument = typeArguments[0]; if (!(typeArgument instanceof Class)) { throw new IllegalStateException( "Impossible situation because a (" + AbstractSolution.class.getSimpleName() + "'s typeArgument (" + typeArgument + ") must be a " + Score.class.getSimpleName() + "."); } scoreType = (Class<? extends Score>) typeArgument; } } if (!AbstractBendableScore.class.isAssignableFrom(scoreType)) { if (annotation.bendableHardLevelsSize() != PlanningScore.NO_LEVEL_SIZE || annotation.bendableSoftLevelsSize() != PlanningScore.NO_LEVEL_SIZE) { throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor + ") that returns a scoreType (" + scoreType + ") that must not have a bendableHardLevelsSize (" + annotation.bendableHardLevelsSize() + ") or a bendableSoftLevelsSize (" + annotation.bendableSoftLevelsSize() + ")."); } if (scoreType.equals(SimpleScore.class)) { return new SimpleScoreDefinition(); } else if (scoreType.equals(SimpleLongScore.class)) { return new SimpleLongScoreDefinition(); } else if (scoreType.equals(SimpleDoubleScore.class)) { return new SimpleDoubleScoreDefinition(); } else if (scoreType.equals(SimpleBigDecimalScore.class)) { return new SimpleBigDecimalScoreDefinition(); } else if (scoreType.equals(HardSoftScore.class)) { return new HardSoftScoreDefinition(); } else if (scoreType.equals(HardSoftLongScore.class)) { return new HardSoftLongScoreDefinition(); } else if (scoreType.equals(HardSoftDoubleScore.class)) { return new HardSoftDoubleScoreDefinition(); } else if (scoreType.equals(HardSoftBigDecimalScore.class)) { return new HardSoftBigDecimalScoreDefinition(); } else if (scoreType.equals(HardMediumSoftScore.class)) { return new HardMediumSoftScoreDefinition(); } else if (scoreType.equals(HardMediumSoftLongScore.class)) { return new HardMediumSoftLongScoreDefinition(); } else { throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor + ") that returns a scoreType (" + scoreType + ") that is not recognized as a default " + Score.class.getSimpleName() + " implementation.\n" + " If you intend to use a custom implementation," + " maybe set a scoreDefinition in the " + PlanningScore.class.getSimpleName() + " annotation."); } } else { int bendableHardLevelsSize = annotation.bendableHardLevelsSize(); int bendableSoftLevelsSize = annotation.bendableSoftLevelsSize(); if (bendableHardLevelsSize == PlanningScore.NO_LEVEL_SIZE || bendableSoftLevelsSize == PlanningScore.NO_LEVEL_SIZE) { throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor + ") that returns a scoreType (" + scoreType + ") that must have a bendableHardLevelsSize (" + annotation.bendableHardLevelsSize() + ") and a bendableSoftLevelsSize (" + annotation.bendableSoftLevelsSize() + ")."); } if (scoreType.equals(BendableScore.class)) { return new BendableScoreDefinition(bendableHardLevelsSize, bendableSoftLevelsSize); } else if (scoreType.equals(BendableLongScore.class)) { return new BendableLongScoreDefinition(bendableHardLevelsSize, bendableSoftLevelsSize); } else if (scoreType.equals(BendableBigDecimalScore.class)) { return new BendableBigDecimalScoreDefinition(bendableHardLevelsSize, bendableSoftLevelsSize); } else { throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor + ") that returns a bendable scoreType (" + scoreType + ") that is not recognized as a default " + Score.class.getSimpleName() + " implementation.\n" + " If you intend to use a custom implementation," + " maybe set a scoreDefinition in the annotation."); } } } public void afterAnnotationsProcessed(DescriptorPolicy descriptorPolicy) { for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) { entityDescriptor.linkInheritedEntityDescriptors(descriptorPolicy); } for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) { entityDescriptor.linkShadowSources(descriptorPolicy); } determineGlobalShadowOrder(); if (logger.isTraceEnabled()) { logger.trace(" Model annotations parsed for Solution {}:", solutionClass.getSimpleName()); for (Map.Entry<Class<?>, EntityDescriptor<Solution_>> entry : entityDescriptorMap.entrySet()) { EntityDescriptor<Solution_> entityDescriptor = entry.getValue(); logger.trace(" Entity {}:", entityDescriptor.getEntityClass().getSimpleName()); for (VariableDescriptor<Solution_> variableDescriptor : entityDescriptor.getDeclaredVariableDescriptors()) { logger.trace(" Variable {} ({})", variableDescriptor.getVariableName(), variableDescriptor instanceof GenuineVariableDescriptor ? "genuine" : "shadow"); } } } } private void determineGlobalShadowOrder() { // Topological sorting with Kahn's algorithm List<Pair<ShadowVariableDescriptor<Solution_>, Integer>> pairList = new ArrayList<>(); Map<ShadowVariableDescriptor<Solution_>, Pair<ShadowVariableDescriptor<Solution_>, Integer>> shadowToPairMap = new HashMap<>(); for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) { for (ShadowVariableDescriptor<Solution_> shadow : entityDescriptor.getDeclaredShadowVariableDescriptors()) { int sourceSize = shadow.getSourceVariableDescriptorList().size(); Pair<ShadowVariableDescriptor<Solution_>, Integer> pair = MutablePair.of(shadow, sourceSize); pairList.add(pair); shadowToPairMap.put(shadow, pair); } } for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) { for (GenuineVariableDescriptor<Solution_> genuine : entityDescriptor.getDeclaredGenuineVariableDescriptors()) { for (ShadowVariableDescriptor<Solution_> sink : genuine.getSinkVariableDescriptorList()) { Pair<ShadowVariableDescriptor<Solution_>, Integer> sinkPair = shadowToPairMap.get(sink); sinkPair.setValue(sinkPair.getValue() - 1); } } } int globalShadowOrder = 0; while (!pairList.isEmpty()) { pairList.sort(Comparator.comparingInt(Pair::getValue)); Pair<ShadowVariableDescriptor<Solution_>, Integer> pair = pairList.remove(0); ShadowVariableDescriptor<Solution_> shadow = pair.getKey(); if (pair.getValue() != 0) { if (pair.getValue() < 0) { throw new IllegalStateException("Impossible state because the shadowVariable (" + shadow.getSimpleEntityAndVariableName() + ") can not be used more as a sink than it has sources."); } throw new IllegalStateException("There is a cyclic shadow variable path" + " that involves the shadowVariable (" + shadow.getSimpleEntityAndVariableName() + ") because it must be later than its sources (" + shadow.getSourceVariableDescriptorList() + ") and also earlier than its sinks (" + shadow.getSinkVariableDescriptorList() + ")."); } for (ShadowVariableDescriptor<Solution_> sink : shadow.getSinkVariableDescriptorList()) { Pair<ShadowVariableDescriptor<Solution_>, Integer> sinkPair = shadowToPairMap.get(sink); sinkPair.setValue(sinkPair.getValue() - 1); } shadow.setGlobalShadowOrder(globalShadowOrder); globalShadowOrder++; } } public Class<Solution_> getSolutionClass() { return solutionClass; } /** * @return the {@link Class} of {@link PlanningScore} */ public Class<? extends Score> extractScoreClass() { return (Class<? extends Score>) scoreMemberAccessor.getType(); } public ScoreDefinition getScoreDefinition() { return scoreDefinition; } public SolutionCloner<Solution_> getSolutionCloner() { return solutionCloner; } public Map<String, MemberAccessor> getProblemFactMemberAccessorMap() { return problemFactMemberAccessorMap; } public Map<String, MemberAccessor> getProblemFactCollectionMemberAccessorMap() { return problemFactCollectionMemberAccessorMap; } public List<String> getProblemFactMemberAndProblemFactCollectionMemberNames() { List<String> memberNames = new ArrayList<>(problemFactMemberAccessorMap.size() + problemFactCollectionMemberAccessorMap.size()); memberNames.addAll(problemFactMemberAccessorMap.keySet()); memberNames.addAll(problemFactCollectionMemberAccessorMap.keySet()); return memberNames; } public Map<String, MemberAccessor> getEntityMemberAccessorMap() { return entityMemberAccessorMap; } public Map<String, MemberAccessor> getEntityCollectionMemberAccessorMap() { return entityCollectionMemberAccessorMap; } public List<String> getEntityMemberAndEntityCollectionMemberNames() { List<String> memberNames = new ArrayList<>(entityMemberAccessorMap.size() + entityCollectionMemberAccessorMap.size()); memberNames.addAll(entityMemberAccessorMap.keySet()); memberNames.addAll(entityCollectionMemberAccessorMap.keySet()); return memberNames; } // ************************************************************************ // Model methods // ************************************************************************ public Set<Class<?>> getEntityClassSet() { return entityDescriptorMap.keySet(); } public Collection<EntityDescriptor<Solution_>> getEntityDescriptors() { return entityDescriptorMap.values(); } public Collection<EntityDescriptor<Solution_>> getGenuineEntityDescriptors() { List<EntityDescriptor<Solution_>> genuineEntityDescriptorList = new ArrayList<>(entityDescriptorMap.size()); for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) { if (entityDescriptor.hasAnyDeclaredGenuineVariableDescriptor()) { genuineEntityDescriptorList.add(entityDescriptor); } } return genuineEntityDescriptorList; } public boolean hasEntityDescriptorStrict(Class<?> entityClass) { return entityDescriptorMap.containsKey(entityClass); } public EntityDescriptor<Solution_> getEntityDescriptorStrict(Class<?> entityClass) { return entityDescriptorMap.get(entityClass); } public boolean hasEntityDescriptor(Class<?> entitySubclass) { EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptor(entitySubclass); return entityDescriptor != null; } public EntityDescriptor<Solution_> findEntityDescriptorOrFail(Class<?> entitySubclass) { EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptor(entitySubclass); if (entityDescriptor == null) { throw new IllegalArgumentException("A planning entity is an instance of an entitySubclass (" + entitySubclass + ") that is not configured as a planning entity.\n" + "If that class (" + entitySubclass.getSimpleName() + ") (or superclass thereof) is not a entityClass (" + getEntityClassSet() + "), check your Solution implementation's annotated methods.\n" + "If it is, check your solver configuration."); } return entityDescriptor; } public EntityDescriptor<Solution_> findEntityDescriptor(Class<?> entitySubclass) { return lowestEntityDescriptorCache.computeIfAbsent(entitySubclass, key -> { // Reverse order to find the nearest ancestor for (Class<?> entityClass : reversedEntityClassList) { if (entityClass.isAssignableFrom(entitySubclass)) { return entityDescriptorMap.get(entityClass); } } return null; }); } public GenuineVariableDescriptor<Solution_> findGenuineVariableDescriptor(Object entity, String variableName) { EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); return entityDescriptor.getGenuineVariableDescriptor(variableName); } public GenuineVariableDescriptor<Solution_> findGenuineVariableDescriptorOrFail(Object entity, String variableName) { EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); GenuineVariableDescriptor<Solution_> variableDescriptor = entityDescriptor.getGenuineVariableDescriptor(variableName); if (variableDescriptor == null) { throw new IllegalArgumentException(entityDescriptor.buildInvalidVariableNameExceptionMessage(variableName)); } return variableDescriptor; } public VariableDescriptor<Solution_> findVariableDescriptor(Object entity, String variableName) { EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); return entityDescriptor.getVariableDescriptor(variableName); } public VariableDescriptor<Solution_> findVariableDescriptorOrFail(Object entity, String variableName) { EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); VariableDescriptor<Solution_> variableDescriptor = entityDescriptor.getVariableDescriptor(variableName); if (variableDescriptor == null) { throw new IllegalArgumentException(entityDescriptor.buildInvalidVariableNameExceptionMessage(variableName)); } return variableDescriptor; } // ************************************************************************ // Look up methods // ************************************************************************ public LookUpStrategyResolver getLookUpStrategyResolver() { return lookUpStrategyResolver; } // ************************************************************************ // Extraction methods // ************************************************************************ public Collection<Object> getAllFacts(Solution_ solution) { Collection<Object> facts = new ArrayList<>(); // Adds both entities and facts Arrays.asList(entityMemberAccessorMap, problemFactMemberAccessorMap) .forEach(map -> map.forEach((key, memberAccessor) -> { Object object = extractMemberObject(memberAccessor, solution); if (object != null) { facts.add(object); } })); entityCollectionMemberAccessorMap.forEach( (key, memberAccessor) -> facts.addAll(extractMemberCollection(memberAccessor, solution, false))); problemFactCollectionMemberAccessorMap.forEach( (key, memberAccessor) -> facts.addAll(extractMemberCollection(memberAccessor, solution, true))); return facts; } /** * @param solution never null * @return {@code >= 0} */ public int getEntityCount(Solution_ solution) { int entityCount = 0; for (MemberAccessor entityMemberAccessor : entityMemberAccessorMap.values()) { Object entity = extractMemberObject(entityMemberAccessor, solution); if (entity != null) { entityCount++; } } for (MemberAccessor entityCollectionMemberAccessor : entityCollectionMemberAccessorMap.values()) { Collection<Object> entityCollection = extractMemberCollection(entityCollectionMemberAccessor, solution, false); entityCount += entityCollection.size(); } return entityCount; } public List<Object> getEntityList(Solution_ solution) { List<Object> entityList = new ArrayList<>(); for (MemberAccessor entityMemberAccessor : entityMemberAccessorMap.values()) { Object entity = extractMemberObject(entityMemberAccessor, solution); if (entity != null) { entityList.add(entity); } } for (MemberAccessor entityCollectionMemberAccessor : entityCollectionMemberAccessorMap.values()) { Collection<Object> entityCollection = extractMemberCollection(entityCollectionMemberAccessor, solution, false); entityList.addAll(entityCollection); } return entityList; } public List<Object> getEntityListByEntityClass(Solution_ solution, Class<?> entityClass) { List<Object> entityList = new ArrayList<>(); for (MemberAccessor entityMemberAccessor : entityMemberAccessorMap.values()) { if (entityMemberAccessor.getType().isAssignableFrom(entityClass)) { Object entity = extractMemberObject(entityMemberAccessor, solution); if (entity != null && entityClass.isInstance(entity)) { entityList.add(entity); } } } for (MemberAccessor entityCollectionMemberAccessor : entityCollectionMemberAccessorMap.values()) { // TODO if (entityCollectionPropertyAccessor.getPropertyType().getElementType().isAssignableFrom(entityClass)) { Collection<Object> entityCollection = extractMemberCollection(entityCollectionMemberAccessor, solution, false); for (Object entity : entityCollection) { if (entityClass.isInstance(entity)) { entityList.add(entity); } } } return entityList; } /** * @param solution never null * @return {@code >= 0} */ public long getGenuineVariableCount(Solution_ solution) { long variableCount = 0L; for (Iterator<Object> it = extractAllEntitiesIterator(solution); it.hasNext(); ) { Object entity = it.next(); EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); variableCount += entityDescriptor.getGenuineVariableCount(); } return variableCount; } public long getMaximumValueCount(Solution_ solution) { long maximumValueCount = 0L; for (Iterator<Object> it = extractAllEntitiesIterator(solution); it.hasNext(); ) { Object entity = it.next(); EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); maximumValueCount = Math.max(maximumValueCount, entityDescriptor.getMaximumValueCount(solution, entity)); } return maximumValueCount; } /** * @param solution never null * @return {@code >= 0} */ public int getValueCount(Solution_ solution) { int valueCount = 0; // TODO FIXME for ValueRatioTabuSizeStrategy (or reuse maximumValueCount() for that variable descriptor?) throw new UnsupportedOperationException( "getValueCount is not yet supported - this blocks ValueRatioTabuSizeStrategy"); // return valueCount; } /** * Calculates an indication on how big this problem instance is. * This is intentionally very loosely defined for now. * @param solution never null * @return {@code >= 0} */ public long getProblemScale(Solution_ solution) { long problemScale = 0L; for (Iterator<Object> it = extractAllEntitiesIterator(solution); it.hasNext(); ) { Object entity = it.next(); EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); problemScale += entityDescriptor.getProblemScale(solution, entity); } return problemScale; } public int countUninitializedVariables(Solution_ solution) { int count = 0; for (Iterator<Object> it = extractAllEntitiesIterator(solution); it.hasNext(); ) { Object entity = it.next(); EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); count += entityDescriptor.countUninitializedVariables(entity); } return count; } public int countReinitializableVariables(ScoreDirector<Solution_> scoreDirector, Solution_ solution) { int count = 0; for (Iterator<Object> it = extractAllEntitiesIterator(solution); it.hasNext(); ) { Object entity = it.next(); EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); count += entityDescriptor.countReinitializableVariables(scoreDirector, entity); } return count; } public Iterator<Object> extractAllEntitiesIterator(Solution_ solution) { List<Iterator<Object>> iteratorList = new ArrayList<>( entityMemberAccessorMap.size() + entityCollectionMemberAccessorMap.size()); for (MemberAccessor entityMemberAccessor : entityMemberAccessorMap.values()) { Object entity = extractMemberObject(entityMemberAccessor, solution); if (entity != null) { iteratorList.add(Collections.singletonList(entity).iterator()); } } for (MemberAccessor entityCollectionMemberAccessor : entityCollectionMemberAccessorMap.values()) { Collection<Object> entityCollection = extractMemberCollection(entityCollectionMemberAccessor, solution, false); iteratorList.add(entityCollection.iterator()); } return Iterators.concat(iteratorList.iterator()); } private Object extractMemberObject(MemberAccessor memberAccessor, Solution_ solution) { return memberAccessor.executeGetter(solution); } private Collection<Object> extractMemberCollection(MemberAccessor collectionMemberAccessor, Solution_ solution, boolean isFact) { Collection<Object> collection = (Collection<Object>) collectionMemberAccessor.executeGetter(solution); if (collection == null) { throw new IllegalArgumentException("The solutionClass (" + solutionClass + ")'s " + (isFact ? "factCollectionProperty" : "entityCollectionProperty") + " (" + collectionMemberAccessor + ") should never return null.\n" + (collectionMemberAccessor instanceof FieldMemberAccessor ? "" : "Maybe the getter/method always returns null instead of the actual data.\n") + "Maybe the value is null instead of an empty collection."); } return collection; } /** * @param solution never null * @return sometimes null, if the {@link Score} hasn't been calculated yet */ public Score getScore(Solution_ solution) { return (Score) scoreMemberAccessor.executeGetter(solution); } /** * Called when the {@link Score} has been calculated or predicted. * @param solution never null * @param score sometimes null, in rare occasions to indicate that the old {@link Score} is stale, * but no new ones has been calculated */ public void setScore(Solution_ solution, Score score) { scoreMemberAccessor.executeSetter(solution, score); } @Override public String toString() { return getClass().getSimpleName() + "(" + solutionClass.getName() + ")"; } }
optaplanner-core/src/main/java/org/optaplanner/core/impl/domain/solution/descriptor/SolutionDescriptor.java
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * 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.optaplanner.core.impl.domain.solution.descriptor; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Collectors; import com.google.common.collect.Collections2; import com.google.common.collect.Iterators; import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.Pair; import org.optaplanner.core.api.domain.autodiscover.AutoDiscoverMemberType; import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty; import org.optaplanner.core.api.domain.solution.PlanningEntityProperty; import org.optaplanner.core.api.domain.solution.PlanningScore; import org.optaplanner.core.api.domain.solution.PlanningSolution; import org.optaplanner.core.api.domain.solution.Solution; import org.optaplanner.core.api.domain.solution.cloner.SolutionCloner; import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty; import org.optaplanner.core.api.domain.solution.drools.ProblemFactProperty; import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider; import org.optaplanner.core.api.score.AbstractBendableScore; import org.optaplanner.core.api.score.Score; import org.optaplanner.core.api.score.buildin.bendable.BendableScore; import org.optaplanner.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore; import org.optaplanner.core.api.score.buildin.bendablelong.BendableLongScore; import org.optaplanner.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore; import org.optaplanner.core.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScore; import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; import org.optaplanner.core.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScore; import org.optaplanner.core.api.score.buildin.hardsoftdouble.HardSoftDoubleScore; import org.optaplanner.core.api.score.buildin.hardsoftlong.HardSoftLongScore; import org.optaplanner.core.api.score.buildin.simple.SimpleScore; import org.optaplanner.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore; import org.optaplanner.core.api.score.buildin.simpledouble.SimpleDoubleScore; import org.optaplanner.core.api.score.buildin.simplelong.SimpleLongScore; import org.optaplanner.core.config.util.ConfigUtils; import org.optaplanner.core.impl.domain.common.ReflectionHelper; import org.optaplanner.core.impl.domain.common.accessor.BeanPropertyMemberAccessor; import org.optaplanner.core.impl.domain.common.accessor.FieldMemberAccessor; import org.optaplanner.core.impl.domain.common.accessor.MemberAccessor; import org.optaplanner.core.impl.domain.entity.descriptor.EntityDescriptor; import org.optaplanner.core.impl.domain.lookup.LookUpStrategyResolver; import org.optaplanner.core.impl.domain.policy.DescriptorPolicy; import org.optaplanner.core.impl.domain.solution.AbstractSolution; import org.optaplanner.core.impl.domain.solution.cloner.FieldAccessingSolutionCloner; import org.optaplanner.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import org.optaplanner.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; import org.optaplanner.core.impl.domain.variable.descriptor.VariableDescriptor; import org.optaplanner.core.impl.score.buildin.bendable.BendableScoreDefinition; import org.optaplanner.core.impl.score.buildin.bendablebigdecimal.BendableBigDecimalScoreDefinition; import org.optaplanner.core.impl.score.buildin.bendablelong.BendableLongScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardmediumsoft.HardMediumSoftScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardmediumsoftlong.HardMediumSoftLongScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardsoft.HardSoftScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardsoftdouble.HardSoftDoubleScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardsoftlong.HardSoftLongScoreDefinition; import org.optaplanner.core.impl.score.buildin.simple.SimpleScoreDefinition; import org.optaplanner.core.impl.score.buildin.simplebigdecimal.SimpleBigDecimalScoreDefinition; import org.optaplanner.core.impl.score.buildin.simpledouble.SimpleDoubleScoreDefinition; import org.optaplanner.core.impl.score.buildin.simplelong.SimpleLongScoreDefinition; import org.optaplanner.core.impl.score.definition.ScoreDefinition; import org.optaplanner.core.impl.score.director.ScoreDirector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.optaplanner.core.config.util.ConfigUtils.MemberAccessorType.*; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class SolutionDescriptor<Solution_> { public static <Solution_> SolutionDescriptor<Solution_> buildSolutionDescriptor(Class<Solution_> solutionClass, Class<?>... entityClasses) { return buildSolutionDescriptor(solutionClass, Arrays.asList(entityClasses), null); } public static <Solution_> SolutionDescriptor<Solution_> buildSolutionDescriptor(Class<Solution_> solutionClass, List<Class<?>> entityClassList, ScoreDefinition deprecatedScoreDefinition) { DescriptorPolicy descriptorPolicy = new DescriptorPolicy(); SolutionDescriptor<Solution_> solutionDescriptor = new SolutionDescriptor<>(solutionClass); solutionDescriptor.processAnnotations(descriptorPolicy, deprecatedScoreDefinition, entityClassList); for (Class<?> entityClass : sortEntityClassList(entityClassList)) { EntityDescriptor<Solution_> entityDescriptor = new EntityDescriptor<>(solutionDescriptor, entityClass); solutionDescriptor.addEntityDescriptor(entityDescriptor); entityDescriptor.processAnnotations(descriptorPolicy); } solutionDescriptor.afterAnnotationsProcessed(descriptorPolicy); return solutionDescriptor; } private static List<Class<?>> sortEntityClassList(List<Class<?>> entityClassList) { List<Class<?>> sortedEntityClassList = new ArrayList<>(entityClassList.size()); for (Class<?> entityClass : entityClassList) { boolean added = false; for (int i = 0; i < sortedEntityClassList.size(); i++) { Class<?> sortedEntityClass = sortedEntityClassList.get(i); if (entityClass.isAssignableFrom(sortedEntityClass)) { sortedEntityClassList.add(i, entityClass); added = true; break; } } if (!added) { sortedEntityClassList.add(entityClass); } } return sortedEntityClassList; } // ************************************************************************ // Non-static members // ************************************************************************ protected final transient Logger logger = LoggerFactory.getLogger(getClass()); private final Class<Solution_> solutionClass; private SolutionCloner<Solution_> solutionCloner; private AutoDiscoverMemberType autoDiscoverMemberType; private final Map<String, MemberAccessor> problemFactMemberAccessorMap; private final Map<String, MemberAccessor> problemFactCollectionMemberAccessorMap; private final Map<String, MemberAccessor> entityMemberAccessorMap; private final Map<String, MemberAccessor> entityCollectionMemberAccessorMap; private MemberAccessor scoreMemberAccessor; private ScoreDefinition scoreDefinition; private final Map<Class<?>, EntityDescriptor<Solution_>> entityDescriptorMap; private final List<Class<?>> reversedEntityClassList; private final ConcurrentMap<Class<?>, EntityDescriptor<Solution_>> lowestEntityDescriptorCache = new ConcurrentHashMap<>(); private LookUpStrategyResolver lookUpStrategyResolver = null; public SolutionDescriptor(Class<Solution_> solutionClass) { this.solutionClass = solutionClass; problemFactMemberAccessorMap = new LinkedHashMap<>(); problemFactCollectionMemberAccessorMap = new LinkedHashMap<>(); entityMemberAccessorMap = new LinkedHashMap<>(); entityCollectionMemberAccessorMap = new LinkedHashMap<>(); entityDescriptorMap = new LinkedHashMap<>(); reversedEntityClassList = new ArrayList<>(); } public void addEntityDescriptor(EntityDescriptor<Solution_> entityDescriptor) { Class<?> entityClass = entityDescriptor.getEntityClass(); for (Class<?> otherEntityClass : entityDescriptorMap.keySet()) { if (entityClass.isAssignableFrom(otherEntityClass)) { throw new IllegalArgumentException("An earlier entityClass (" + otherEntityClass + ") should not be a subclass of a later entityClass (" + entityClass + "). Switch their declaration so superclasses are defined earlier."); } } entityDescriptorMap.put(entityClass, entityDescriptor); reversedEntityClassList.add(0, entityClass); lowestEntityDescriptorCache.put(entityClass, entityDescriptor); } public void processAnnotations(DescriptorPolicy descriptorPolicy, ScoreDefinition deprecatedScoreDefinition, List<Class<?>> entityClassList) { processSolutionAnnotations(descriptorPolicy); ArrayList<Method> potentiallyOverwrittenMethodList = new ArrayList<>(); // Iterate inherited members too (unlike for EntityDescriptor where each one is declared) // to make sure each one is registered for (Class<?> lineageClass : ConfigUtils.getAllAnnotatedLineageClasses(solutionClass, PlanningSolution.class)) { List<Member> memberList = ConfigUtils.getDeclaredMembers(lineageClass); for (Member member : memberList) { if (member instanceof Method && potentiallyOverwrittenMethodList.stream().anyMatch( m -> member.getName().equals(m.getName()) && ReflectionHelper.isMethodOverwritten((Method) member, m.getDeclaringClass()))) { continue; } processValueRangeProviderAnnotation(descriptorPolicy, member); processFactEntityOrScoreAnnotation(descriptorPolicy, member, deprecatedScoreDefinition, entityClassList); } potentiallyOverwrittenMethodList.ensureCapacity(potentiallyOverwrittenMethodList.size() + memberList.size()); memberList.stream().filter(member -> member instanceof Method) .forEach(member -> potentiallyOverwrittenMethodList.add((Method) member)); } if (entityCollectionMemberAccessorMap.isEmpty() && entityMemberAccessorMap.isEmpty()) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") must have at least 1 member with a " + PlanningEntityCollectionProperty.class.getSimpleName() + " annotation or a " + PlanningEntityProperty.class.getSimpleName() + " annotation."); } if (Solution.class.isAssignableFrom(solutionClass)) { processLegacySolution(descriptorPolicy, deprecatedScoreDefinition); return; } // Do not check if problemFactCollectionMemberAccessorMap and problemFactMemberAccessorMap are empty // because they are only required for Drools score calculation. if (scoreMemberAccessor == null) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") must have 1 member with a " + PlanningScore.class.getSimpleName() + " annotation.\n" + "Maybe add a getScore() method with a " + PlanningScore.class.getSimpleName() + " annotation."); } } private void processLegacySolution(DescriptorPolicy descriptorPolicy, ScoreDefinition deprecatedScoreDefinition) { if (!problemFactMemberAccessorMap.isEmpty()) { MemberAccessor memberAccessor = problemFactMemberAccessorMap.values().iterator().next(); throw new IllegalStateException("The solutionClass (" + solutionClass + ") which implements the legacy interface " + Solution.class.getSimpleName() + ") must not have a member (" + memberAccessor.getName() + ") with a " + ProblemFactProperty.class.getSimpleName() + " annotation.\n" + "Maybe remove the use of the legacy interface."); } if (!problemFactCollectionMemberAccessorMap.isEmpty()) { MemberAccessor memberAccessor = problemFactCollectionMemberAccessorMap.values().iterator().next(); throw new IllegalStateException("The solutionClass (" + solutionClass + ") which implements the legacy interface " + Solution.class.getSimpleName() + ") must not have a member (" + memberAccessor.getName() + ") with a " + ProblemFactCollectionProperty.class.getSimpleName() + " annotation.\n" + "Maybe remove the use of the legacy interface."); } try { Method getProblemFactsMethod = solutionClass.getMethod("getProblemFacts"); MemberAccessor problemFactsMemberAccessor = new BeanPropertyMemberAccessor(getProblemFactsMethod); problemFactCollectionMemberAccessorMap.put( problemFactsMemberAccessor.getName(), problemFactsMemberAccessor); } catch (NoSuchMethodException e) { throw new IllegalStateException("Impossible situation: the solutionClass (" + solutionClass + ") which implements the legacy interface " + Solution.class.getSimpleName() + ", lacks its getProblemFacts() method.", e); } if (scoreMemberAccessor != null) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") which implements the legacy interface " + Solution.class.getSimpleName() + ") must not have a member (" + scoreMemberAccessor.getName() + ") with a " + PlanningScore.class.getSimpleName() + " annotation.\n" + "Maybe remove the use of the legacy interface."); } try { Method getScoreMethod = solutionClass.getMethod("getScore"); scoreMemberAccessor = new BeanPropertyMemberAccessor(getScoreMethod); } catch (NoSuchMethodException e) { throw new IllegalStateException("Impossible situation: the solutionClass (" + solutionClass + ") which implements the legacy interface " + Solution.class.getSimpleName() + ", lacks its getScore() method.", e); } if (deprecatedScoreDefinition == null) { deprecatedScoreDefinition = new SimpleScoreDefinition(); } scoreDefinition = deprecatedScoreDefinition; Class<? extends Score> scoreClass = extractScoreClass(); if (!scoreClass.isAssignableFrom(scoreDefinition.getScoreClass())) { throw new IllegalArgumentException("The scoreClass (" + scoreClass + ") of solutionClass (" + solutionClass + ") is not the same or a superclass as the scoreDefinition's scoreClass (" + scoreDefinition.getScoreClass() + ")."); } } /** * Only called if Drools score calculation is used. */ public void checkIfProblemFactsExist() { if (problemFactCollectionMemberAccessorMap.isEmpty() && problemFactMemberAccessorMap.isEmpty()) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") must have at least 1 member with a " + ProblemFactCollectionProperty.class.getSimpleName() + " annotation or a " + ProblemFactProperty.class.getSimpleName() + " annotation" + " when used with Drools score calculation."); } } private void processSolutionAnnotations(DescriptorPolicy descriptorPolicy) { PlanningSolution solutionAnnotation = solutionClass.getAnnotation(PlanningSolution.class); if (solutionAnnotation == null) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") has been specified as a solution in the configuration," + " but does not have a " + PlanningSolution.class.getSimpleName() + " annotation."); } autoDiscoverMemberType = solutionAnnotation.autoDiscoverMemberType(); processSolutionCloner(descriptorPolicy, solutionAnnotation); lookUpStrategyResolver = new LookUpStrategyResolver(solutionAnnotation.lookUpStrategyType()); } private void processSolutionCloner(DescriptorPolicy descriptorPolicy, PlanningSolution solutionAnnotation) { Class<? extends SolutionCloner> solutionClonerClass = solutionAnnotation.solutionCloner(); if (solutionClonerClass == PlanningSolution.NullSolutionCloner.class) { solutionClonerClass = null; } if (solutionClonerClass != null) { solutionCloner = ConfigUtils.newInstance(this, "solutionClonerClass", solutionClonerClass); } else { solutionCloner = new FieldAccessingSolutionCloner<>(this); } } private void processValueRangeProviderAnnotation(DescriptorPolicy descriptorPolicy, Member member) { if (((AnnotatedElement) member).isAnnotationPresent(ValueRangeProvider.class)) { MemberAccessor memberAccessor = ConfigUtils.buildMemberAccessor( member, FIELD_OR_READ_METHOD, ValueRangeProvider.class); descriptorPolicy.addFromSolutionValueRangeProvider(memberAccessor); } } private void processFactEntityOrScoreAnnotation(DescriptorPolicy descriptorPolicy, Member member, ScoreDefinition deprecatedScoreDefinition, List<Class<?>> entityClassList) { Class<? extends Annotation> annotationClass = extractFactEntityOrScoreAnnotationClassOrAutoDiscover( member, entityClassList); if (annotationClass == null) { return; } else if (annotationClass.equals(ProblemFactProperty.class) || annotationClass.equals(ProblemFactCollectionProperty.class)) { processProblemFactPropertyAnnotation(descriptorPolicy, member, annotationClass); } else if (annotationClass.equals(PlanningEntityProperty.class) || annotationClass.equals(PlanningEntityCollectionProperty.class)) { processPlanningEntityPropertyAnnotation(descriptorPolicy, member, annotationClass); } else if (annotationClass.equals(PlanningScore.class)) { processScoreAnnotation(descriptorPolicy, member, annotationClass, deprecatedScoreDefinition); } } private Class<? extends Annotation> extractFactEntityOrScoreAnnotationClassOrAutoDiscover( Member member, List<Class<?>> entityClassList) { Class<? extends Annotation> annotationClass = ConfigUtils.extractAnnotationClass(member, ProblemFactProperty.class, ProblemFactCollectionProperty.class, PlanningEntityProperty.class, PlanningEntityCollectionProperty.class, PlanningScore.class); if (annotationClass == null) { Class<?> type; if (autoDiscoverMemberType == AutoDiscoverMemberType.FIELD && member instanceof Field) { Field field = (Field) member; type = field.getType(); } else if (autoDiscoverMemberType == AutoDiscoverMemberType.GETTER && (member instanceof Method) && ReflectionHelper.isGetterMethod((Method) member)) { Method method = (Method) member; type = method.getReturnType(); } else { type = null; } if (type != null) { if (Score.class.isAssignableFrom(type)) { annotationClass = PlanningScore.class; } else if (Collection.class.isAssignableFrom(type)) { Type genericType = (member instanceof Field) ? ((Field) member).getGenericType() : ((Method) member).getGenericReturnType(); Class<?> elementType = ConfigUtils.extractCollectionGenericTypeParameter( "solutionClass", solutionClass, type, genericType, null, member.getName()); if (entityClassList.stream().anyMatch(entityClass -> entityClass.isAssignableFrom(elementType))) { annotationClass = PlanningEntityCollectionProperty.class; } else { annotationClass = ProblemFactCollectionProperty.class; } } else if (Map.class.isAssignableFrom(type)) { throw new IllegalStateException("The autoDiscoverMemberType (" + autoDiscoverMemberType + ") does not yet support the member (" + member + ") of type (" + type + ") which is an implementation of " + Map.class.getSimpleName() + "."); } else if (entityClassList.stream().anyMatch(entityClass -> entityClass.isAssignableFrom(type))) { annotationClass = PlanningEntityProperty.class; } else { annotationClass = ProblemFactProperty.class; } } } return annotationClass; } private void processProblemFactPropertyAnnotation(DescriptorPolicy descriptorPolicy, Member member, Class<? extends Annotation> annotationClass) { MemberAccessor memberAccessor = ConfigUtils.buildMemberAccessor( member, FIELD_OR_READ_METHOD, annotationClass); assertUnexistingProblemFactOrPlanningEntityProperty(memberAccessor, annotationClass); if (annotationClass == ProblemFactProperty.class) { problemFactMemberAccessorMap.put(memberAccessor.getName(), memberAccessor); } else if (annotationClass == ProblemFactCollectionProperty.class) { if (!Collection.class.isAssignableFrom(memberAccessor.getType())) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") has a " + ProblemFactCollectionProperty.class.getSimpleName() + " annotated member (" + member + ") that does not return a " + Collection.class.getSimpleName() + "."); } problemFactCollectionMemberAccessorMap.put(memberAccessor.getName(), memberAccessor); } else { throw new IllegalStateException("Impossible situation with annotationClass (" + annotationClass + ")."); } } private void processPlanningEntityPropertyAnnotation(DescriptorPolicy descriptorPolicy, Member member, Class<? extends Annotation> annotationClass) { MemberAccessor memberAccessor = ConfigUtils.buildMemberAccessor( member, FIELD_OR_GETTER_METHOD, annotationClass); assertUnexistingProblemFactOrPlanningEntityProperty(memberAccessor, annotationClass); if (annotationClass == PlanningEntityProperty.class) { entityMemberAccessorMap.put(memberAccessor.getName(), memberAccessor); } else if (annotationClass == PlanningEntityCollectionProperty.class) { if (!Collection.class.isAssignableFrom(memberAccessor.getType())) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") has a " + PlanningEntityCollectionProperty.class.getSimpleName() + " annotated member (" + member + ") that does not return a " + Collection.class.getSimpleName() + "."); } entityCollectionMemberAccessorMap.put(memberAccessor.getName(), memberAccessor); } else { throw new IllegalStateException("Impossible situation with annotationClass (" + annotationClass + ")."); } } private void assertUnexistingProblemFactOrPlanningEntityProperty( MemberAccessor memberAccessor, Class<? extends Annotation> annotationClass) { MemberAccessor duplicate; Class<? extends Annotation> otherAnnotationClass; String memberName = memberAccessor.getName(); if (problemFactMemberAccessorMap.containsKey(memberName)) { duplicate = problemFactMemberAccessorMap.get(memberName); otherAnnotationClass = ProblemFactProperty.class; } else if (problemFactCollectionMemberAccessorMap.containsKey(memberName)) { duplicate = problemFactCollectionMemberAccessorMap.get(memberName); otherAnnotationClass = ProblemFactCollectionProperty.class; } else if (entityMemberAccessorMap.containsKey(memberName)) { duplicate = entityMemberAccessorMap.get(memberName); otherAnnotationClass = PlanningEntityProperty.class; } else if (entityCollectionMemberAccessorMap.containsKey(memberName)) { duplicate = entityCollectionMemberAccessorMap.get(memberName); otherAnnotationClass = PlanningEntityCollectionProperty.class; } else { return; } throw new IllegalStateException("The solutionClass (" + solutionClass + ") has a " + annotationClass.getSimpleName() + " annotated member (" + memberAccessor + ") that is duplicated by a " + otherAnnotationClass.getSimpleName() + " annotated member (" + duplicate + ").\n" + (annotationClass.equals(otherAnnotationClass) ? "Maybe the annotation is defined on both the field and its getter." : "Maybe 2 mutually exclusive annotations are configured.")); } private void processScoreAnnotation(DescriptorPolicy descriptorPolicy, Member member, Class<? extends Annotation> annotationClass, ScoreDefinition deprecatedScoreDefinition) { MemberAccessor memberAccessor = ConfigUtils.buildMemberAccessor( member, FIELD_OR_GETTER_METHOD_WITH_SETTER, PlanningScore.class); if (deprecatedScoreDefinition != null) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + memberAccessor + ") but the solver configuration still has a deprecated scoreDefinitionType" + " or scoreDefinitionClass element.\n" + "Maybe remove the <scoreDefinitionType>, <bendableHardLevelsSize>, <bendableSoftLevelsSize> and <scoreDefinitionClass> elements from the solver configuration."); } if (!Score.class.isAssignableFrom(memberAccessor.getType())) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + memberAccessor + ") that does not return a subtype of Score."); } if (scoreMemberAccessor != null) { if (!scoreMemberAccessor.getName().equals(memberAccessor.getName()) || !scoreMemberAccessor.getClass().equals(memberAccessor.getClass())) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + memberAccessor + ") that is duplicated by another member (" + scoreMemberAccessor + ").\n" + " Verify that the annotation is not defined on both the field and its getter."); } // Bottom class wins. Bottom classes are parsed first due to ConfigUtil.getAllAnnotatedLineageClasses() return; } scoreMemberAccessor = memberAccessor; Class<? extends Score> scoreType = (Class<? extends Score>) scoreMemberAccessor.getType(); PlanningScore annotation = scoreMemberAccessor.getAnnotation(PlanningScore.class); if (annotation == null) { // The member was autodiscovered try { annotation = AutoDiscoverAnnotationDefaults.class.getDeclaredField("PLANNING_SCORE").getAnnotation(PlanningScore.class); } catch (NoSuchFieldException e) { throw new IllegalStateException("Impossible situation: the field (PLANNING_SCORE) must exist.", e); } } scoreDefinition = buildScoreDefinition(scoreType, annotation); } private static class AutoDiscoverAnnotationDefaults { @PlanningScore private static final Object PLANNING_SCORE = new Object(); } public ScoreDefinition buildScoreDefinition(Class<? extends Score> scoreType, PlanningScore annotation) { Class<? extends ScoreDefinition> scoreDefinitionClass = annotation.scoreDefinitionClass(); if (scoreDefinitionClass != PlanningScore.NullScoreDefinition.class) { if (annotation.bendableHardLevelsSize() != PlanningScore.NO_LEVEL_SIZE || annotation.bendableSoftLevelsSize() != PlanningScore.NO_LEVEL_SIZE) { throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor + ") that has a scoreDefinition (" + scoreDefinitionClass + ") that must not have a bendableHardLevelsSize (" + annotation.bendableHardLevelsSize() + ") or a bendableSoftLevelsSize (" + annotation.bendableSoftLevelsSize() + ")."); } return ConfigUtils.newInstance(this, "scoreDefinitionClass", scoreDefinitionClass); } if (scoreType == Score.class) { if (!AbstractSolution.class.isAssignableFrom(solutionClass)) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor + ") that doesn't return a non-abstract " + Score.class.getSimpleName() + " class.\n" + "Maybe make it return " + HardSoftScore.class.getSimpleName() + " or another specific " + Score.class.getSimpleName() + " implementation."); } else { // Magic to support AbstractSolution if (solutionClass == AbstractSolution.class) { throw new IllegalArgumentException( "The solutionClass (" + solutionClass + ") cannot be directly a " + AbstractSolution.class.getSimpleName() + ", but a subclass would be ok."); } Class<?> baseClass = solutionClass; while (baseClass.getSuperclass() != AbstractSolution.class) { baseClass = baseClass.getSuperclass(); if (baseClass == null) { throw new IllegalStateException( "Impossible situation because the solutionClass (" + solutionClass + ") is assignable from " + AbstractSolution.class.getSimpleName() + "."); } } Type genericAbstractSolution = solutionClass.getGenericSuperclass(); if (!(genericAbstractSolution instanceof ParameterizedType)) { throw new IllegalStateException( "Impossible situation because the genericAbstractSolution (" + genericAbstractSolution + ") is a " + AbstractSolution.class.getSimpleName() + "."); } ParameterizedType parameterizedAbstractSolution = (ParameterizedType) genericAbstractSolution; Type[] typeArguments = parameterizedAbstractSolution.getActualTypeArguments(); if (typeArguments.length != 1) { throw new IllegalStateException( "Impossible situation because the parameterizedAbstractSolution (" + parameterizedAbstractSolution + ") is a " + AbstractSolution.class.getSimpleName() + "."); } Type typeArgument = typeArguments[0]; if (!(typeArgument instanceof Class)) { throw new IllegalStateException( "Impossible situation because a (" + AbstractSolution.class.getSimpleName() + "'s typeArgument (" + typeArgument + ") must be a " + Score.class.getSimpleName() + "."); } scoreType = (Class<? extends Score>) typeArgument; } } if (!AbstractBendableScore.class.isAssignableFrom(scoreType)) { if (annotation.bendableHardLevelsSize() != PlanningScore.NO_LEVEL_SIZE || annotation.bendableSoftLevelsSize() != PlanningScore.NO_LEVEL_SIZE) { throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor + ") that returns a scoreType (" + scoreType + ") that must not have a bendableHardLevelsSize (" + annotation.bendableHardLevelsSize() + ") or a bendableSoftLevelsSize (" + annotation.bendableSoftLevelsSize() + ")."); } if (scoreType.equals(SimpleScore.class)) { return new SimpleScoreDefinition(); } else if (scoreType.equals(SimpleLongScore.class)) { return new SimpleLongScoreDefinition(); } else if (scoreType.equals(SimpleDoubleScore.class)) { return new SimpleDoubleScoreDefinition(); } else if (scoreType.equals(SimpleBigDecimalScore.class)) { return new SimpleBigDecimalScoreDefinition(); } else if (scoreType.equals(HardSoftScore.class)) { return new HardSoftScoreDefinition(); } else if (scoreType.equals(HardSoftLongScore.class)) { return new HardSoftLongScoreDefinition(); } else if (scoreType.equals(HardSoftDoubleScore.class)) { return new HardSoftDoubleScoreDefinition(); } else if (scoreType.equals(HardSoftBigDecimalScore.class)) { return new HardSoftBigDecimalScoreDefinition(); } else if (scoreType.equals(HardMediumSoftScore.class)) { return new HardMediumSoftScoreDefinition(); } else if (scoreType.equals(HardMediumSoftLongScore.class)) { return new HardMediumSoftLongScoreDefinition(); } else { throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor + ") that returns a scoreType (" + scoreType + ") that is not recognized as a default " + Score.class.getSimpleName() + " implementation.\n" + " If you intend to use a custom implementation," + " maybe set a scoreDefinition in the " + PlanningScore.class.getSimpleName() + " annotation."); } } else { int bendableHardLevelsSize = annotation.bendableHardLevelsSize(); int bendableSoftLevelsSize = annotation.bendableSoftLevelsSize(); if (bendableHardLevelsSize == PlanningScore.NO_LEVEL_SIZE || bendableSoftLevelsSize == PlanningScore.NO_LEVEL_SIZE) { throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor + ") that returns a scoreType (" + scoreType + ") that must have a bendableHardLevelsSize (" + annotation.bendableHardLevelsSize() + ") and a bendableSoftLevelsSize (" + annotation.bendableSoftLevelsSize() + ")."); } if (scoreType.equals(BendableScore.class)) { return new BendableScoreDefinition(bendableHardLevelsSize, bendableSoftLevelsSize); } else if (scoreType.equals(BendableLongScore.class)) { return new BendableLongScoreDefinition(bendableHardLevelsSize, bendableSoftLevelsSize); } else if (scoreType.equals(BendableBigDecimalScore.class)) { return new BendableBigDecimalScoreDefinition(bendableHardLevelsSize, bendableSoftLevelsSize); } else { throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a " + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor + ") that returns a bendable scoreType (" + scoreType + ") that is not recognized as a default " + Score.class.getSimpleName() + " implementation.\n" + " If you intend to use a custom implementation," + " maybe set a scoreDefinition in the annotation."); } } } public void afterAnnotationsProcessed(DescriptorPolicy descriptorPolicy) { for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) { entityDescriptor.linkInheritedEntityDescriptors(descriptorPolicy); } for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) { entityDescriptor.linkShadowSources(descriptorPolicy); } determineGlobalShadowOrder(); if (logger.isTraceEnabled()) { logger.trace(" Model annotations parsed for Solution {}:", solutionClass.getSimpleName()); for (Map.Entry<Class<?>, EntityDescriptor<Solution_>> entry : entityDescriptorMap.entrySet()) { EntityDescriptor<Solution_> entityDescriptor = entry.getValue(); logger.trace(" Entity {}:", entityDescriptor.getEntityClass().getSimpleName()); for (VariableDescriptor<Solution_> variableDescriptor : entityDescriptor.getDeclaredVariableDescriptors()) { logger.trace(" Variable {} ({})", variableDescriptor.getVariableName(), variableDescriptor instanceof GenuineVariableDescriptor ? "genuine" : "shadow"); } } } } private void determineGlobalShadowOrder() { // Topological sorting with Kahn's algorithm List<Pair<ShadowVariableDescriptor<Solution_>, Integer>> pairList = new ArrayList<>(); Map<ShadowVariableDescriptor<Solution_>, Pair<ShadowVariableDescriptor<Solution_>, Integer>> shadowToPairMap = new HashMap<>(); for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) { for (ShadowVariableDescriptor<Solution_> shadow : entityDescriptor.getDeclaredShadowVariableDescriptors()) { int sourceSize = shadow.getSourceVariableDescriptorList().size(); Pair<ShadowVariableDescriptor<Solution_>, Integer> pair = MutablePair.of(shadow, sourceSize); pairList.add(pair); shadowToPairMap.put(shadow, pair); } } for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) { for (GenuineVariableDescriptor<Solution_> genuine : entityDescriptor.getDeclaredGenuineVariableDescriptors()) { for (ShadowVariableDescriptor<Solution_> sink : genuine.getSinkVariableDescriptorList()) { Pair<ShadowVariableDescriptor<Solution_>, Integer> sinkPair = shadowToPairMap.get(sink); sinkPair.setValue(sinkPair.getValue() - 1); } } } int globalShadowOrder = 0; while (!pairList.isEmpty()) { pairList.sort(Comparator.comparingInt(Pair::getValue)); Pair<ShadowVariableDescriptor<Solution_>, Integer> pair = pairList.remove(0); ShadowVariableDescriptor<Solution_> shadow = pair.getKey(); if (pair.getValue() != 0) { if (pair.getValue() < 0) { throw new IllegalStateException("Impossible state because the shadowVariable (" + shadow.getSimpleEntityAndVariableName() + ") can not be used more as a sink than it has sources."); } throw new IllegalStateException("There is a cyclic shadow variable path" + " that involves the shadowVariable (" + shadow.getSimpleEntityAndVariableName() + ") because it must be later than its sources (" + shadow.getSourceVariableDescriptorList() + ") and also earlier than its sinks (" + shadow.getSinkVariableDescriptorList() + ")."); } for (ShadowVariableDescriptor<Solution_> sink : shadow.getSinkVariableDescriptorList()) { Pair<ShadowVariableDescriptor<Solution_>, Integer> sinkPair = shadowToPairMap.get(sink); sinkPair.setValue(sinkPair.getValue() - 1); } shadow.setGlobalShadowOrder(globalShadowOrder); globalShadowOrder++; } } public Class<Solution_> getSolutionClass() { return solutionClass; } /** * @return the {@link Class} of {@link PlanningScore} */ public Class<? extends Score> extractScoreClass() { return (Class<? extends Score>) scoreMemberAccessor.getType(); } public ScoreDefinition getScoreDefinition() { return scoreDefinition; } public SolutionCloner<Solution_> getSolutionCloner() { return solutionCloner; } public Map<String, MemberAccessor> getProblemFactMemberAccessorMap() { return problemFactMemberAccessorMap; } public Map<String, MemberAccessor> getProblemFactCollectionMemberAccessorMap() { return problemFactCollectionMemberAccessorMap; } public List<String> getProblemFactMemberAndProblemFactCollectionMemberNames() { List<String> memberNames = new ArrayList<>(problemFactMemberAccessorMap.size() + problemFactCollectionMemberAccessorMap.size()); memberNames.addAll(problemFactMemberAccessorMap.keySet()); memberNames.addAll(problemFactCollectionMemberAccessorMap.keySet()); return memberNames; } public Map<String, MemberAccessor> getEntityMemberAccessorMap() { return entityMemberAccessorMap; } public Map<String, MemberAccessor> getEntityCollectionMemberAccessorMap() { return entityCollectionMemberAccessorMap; } public List<String> getEntityMemberAndEntityCollectionMemberNames() { List<String> memberNames = new ArrayList<>(entityMemberAccessorMap.size() + entityCollectionMemberAccessorMap.size()); memberNames.addAll(entityMemberAccessorMap.keySet()); memberNames.addAll(entityCollectionMemberAccessorMap.keySet()); return memberNames; } // ************************************************************************ // Model methods // ************************************************************************ public Set<Class<?>> getEntityClassSet() { return entityDescriptorMap.keySet(); } public Collection<EntityDescriptor<Solution_>> getEntityDescriptors() { return entityDescriptorMap.values(); } public Collection<EntityDescriptor<Solution_>> getGenuineEntityDescriptors() { List<EntityDescriptor<Solution_>> genuineEntityDescriptorList = new ArrayList<>(entityDescriptorMap.size()); for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) { if (entityDescriptor.hasAnyDeclaredGenuineVariableDescriptor()) { genuineEntityDescriptorList.add(entityDescriptor); } } return genuineEntityDescriptorList; } public boolean hasEntityDescriptorStrict(Class<?> entityClass) { return entityDescriptorMap.containsKey(entityClass); } public EntityDescriptor<Solution_> getEntityDescriptorStrict(Class<?> entityClass) { return entityDescriptorMap.get(entityClass); } public boolean hasEntityDescriptor(Class<?> entitySubclass) { EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptor(entitySubclass); return entityDescriptor != null; } public EntityDescriptor<Solution_> findEntityDescriptorOrFail(Class<?> entitySubclass) { EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptor(entitySubclass); if (entityDescriptor == null) { throw new IllegalArgumentException("A planning entity is an instance of an entitySubclass (" + entitySubclass + ") that is not configured as a planning entity.\n" + "If that class (" + entitySubclass.getSimpleName() + ") (or superclass thereof) is not a entityClass (" + getEntityClassSet() + "), check your Solution implementation's annotated methods.\n" + "If it is, check your solver configuration."); } return entityDescriptor; } public EntityDescriptor<Solution_> findEntityDescriptor(Class<?> entitySubclass) { return lowestEntityDescriptorCache.computeIfAbsent(entitySubclass, key -> { // Reverse order to find the nearest ancestor for (Class<?> entityClass : reversedEntityClassList) { if (entityClass.isAssignableFrom(entitySubclass)) { return entityDescriptorMap.get(entityClass); } } return null; }); } public GenuineVariableDescriptor<Solution_> findGenuineVariableDescriptor(Object entity, String variableName) { EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); return entityDescriptor.getGenuineVariableDescriptor(variableName); } public GenuineVariableDescriptor<Solution_> findGenuineVariableDescriptorOrFail(Object entity, String variableName) { EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); GenuineVariableDescriptor<Solution_> variableDescriptor = entityDescriptor.getGenuineVariableDescriptor(variableName); if (variableDescriptor == null) { throw new IllegalArgumentException(entityDescriptor.buildInvalidVariableNameExceptionMessage(variableName)); } return variableDescriptor; } public VariableDescriptor<Solution_> findVariableDescriptor(Object entity, String variableName) { EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); return entityDescriptor.getVariableDescriptor(variableName); } public VariableDescriptor<Solution_> findVariableDescriptorOrFail(Object entity, String variableName) { EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); VariableDescriptor<Solution_> variableDescriptor = entityDescriptor.getVariableDescriptor(variableName); if (variableDescriptor == null) { throw new IllegalArgumentException(entityDescriptor.buildInvalidVariableNameExceptionMessage(variableName)); } return variableDescriptor; } // ************************************************************************ // Look up methods // ************************************************************************ public LookUpStrategyResolver getLookUpStrategyResolver() { return lookUpStrategyResolver; } // ************************************************************************ // Extraction methods // ************************************************************************ public Collection<Object> getAllFacts(Solution_ solution) { Collection<Object> facts = new ArrayList<>(); // Adds both entities and facts Arrays.asList(entityMemberAccessorMap, problemFactMemberAccessorMap) .forEach(map -> map.forEach((key, memberAccessor) -> { Object object = extractMemberObject(memberAccessor, solution); if (object != null) { facts.add(object); } })); entityCollectionMemberAccessorMap.forEach( (key, memberAccessor) -> facts.addAll(extractMemberCollection(memberAccessor, solution, false))); problemFactCollectionMemberAccessorMap.forEach( (key, memberAccessor) -> facts.addAll(extractMemberCollection(memberAccessor, solution, true))); return facts; } /** * @param solution never null * @return {@code >= 0} */ public int getEntityCount(Solution_ solution) { int entityCount = 0; for (MemberAccessor entityMemberAccessor : entityMemberAccessorMap.values()) { Object entity = extractMemberObject(entityMemberAccessor, solution); if (entity != null) { entityCount++; } } for (MemberAccessor entityCollectionMemberAccessor : entityCollectionMemberAccessorMap.values()) { Collection<Object> entityCollection = extractMemberCollection(entityCollectionMemberAccessor, solution, false); entityCount += entityCollection.size(); } return entityCount; } public List<Object> getEntityList(Solution_ solution) { List<Object> entityList = new ArrayList<>(); for (MemberAccessor entityMemberAccessor : entityMemberAccessorMap.values()) { Object entity = extractMemberObject(entityMemberAccessor, solution); if (entity != null) { entityList.add(entity); } } for (MemberAccessor entityCollectionMemberAccessor : entityCollectionMemberAccessorMap.values()) { Collection<Object> entityCollection = extractMemberCollection(entityCollectionMemberAccessor, solution, false); entityList.addAll(entityCollection); } return entityList; } public List<Object> getEntityListByEntityClass(Solution_ solution, Class<?> entityClass) { List<Object> entityList = new ArrayList<>(); for (MemberAccessor entityMemberAccessor : entityMemberAccessorMap.values()) { if (entityMemberAccessor.getType().isAssignableFrom(entityClass)) { Object entity = extractMemberObject(entityMemberAccessor, solution); if (entity != null && entityClass.isInstance(entity)) { entityList.add(entity); } } } for (MemberAccessor entityCollectionMemberAccessor : entityCollectionMemberAccessorMap.values()) { // TODO if (entityCollectionPropertyAccessor.getPropertyType().getElementType().isAssignableFrom(entityClass)) { Collection<Object> entityCollection = extractMemberCollection(entityCollectionMemberAccessor, solution, false); for (Object entity : entityCollection) { if (entityClass.isInstance(entity)) { entityList.add(entity); } } } return entityList; } /** * @param solution never null * @return {@code >= 0} */ public long getGenuineVariableCount(Solution_ solution) { long variableCount = 0L; for (Iterator<Object> it = extractAllEntitiesIterator(solution); it.hasNext(); ) { Object entity = it.next(); EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); variableCount += entityDescriptor.getGenuineVariableCount(); } return variableCount; } public long getMaximumValueCount(Solution_ solution) { long maximumValueCount = 0L; for (Iterator<Object> it = extractAllEntitiesIterator(solution); it.hasNext(); ) { Object entity = it.next(); EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); maximumValueCount = Math.max(maximumValueCount, entityDescriptor.getMaximumValueCount(solution, entity)); } return maximumValueCount; } /** * @param solution never null * @return {@code >= 0} */ public int getValueCount(Solution_ solution) { int valueCount = 0; // TODO FIXME for ValueRatioTabuSizeStrategy (or reuse maximumValueCount() for that variable descriptor?) throw new UnsupportedOperationException( "getValueCount is not yet supported - this blocks ValueRatioTabuSizeStrategy"); // return valueCount; } /** * Calculates an indication on how big this problem instance is. * This is intentionally very loosely defined for now. * @param solution never null * @return {@code >= 0} */ public long getProblemScale(Solution_ solution) { long problemScale = 0L; for (Iterator<Object> it = extractAllEntitiesIterator(solution); it.hasNext(); ) { Object entity = it.next(); EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); problemScale += entityDescriptor.getProblemScale(solution, entity); } return problemScale; } public int countUninitializedVariables(Solution_ solution) { int count = 0; for (Iterator<Object> it = extractAllEntitiesIterator(solution); it.hasNext(); ) { Object entity = it.next(); EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); count += entityDescriptor.countUninitializedVariables(entity); } return count; } public int countReinitializableVariables(ScoreDirector<Solution_> scoreDirector, Solution_ solution) { int count = 0; for (Iterator<Object> it = extractAllEntitiesIterator(solution); it.hasNext(); ) { Object entity = it.next(); EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); count += entityDescriptor.countReinitializableVariables(scoreDirector, entity); } return count; } public Iterator<Object> extractAllEntitiesIterator(Solution_ solution) { List<Iterator<Object>> iteratorList = new ArrayList<>( entityMemberAccessorMap.size() + entityCollectionMemberAccessorMap.size()); for (MemberAccessor entityMemberAccessor : entityMemberAccessorMap.values()) { Object entity = extractMemberObject(entityMemberAccessor, solution); if (entity != null) { iteratorList.add(Collections.singletonList(entity).iterator()); } } for (MemberAccessor entityCollectionMemberAccessor : entityCollectionMemberAccessorMap.values()) { Collection<Object> entityCollection = extractMemberCollection(entityCollectionMemberAccessor, solution, false); iteratorList.add(entityCollection.iterator()); } return Iterators.concat(iteratorList.iterator()); } private Object extractMemberObject(MemberAccessor memberAccessor, Solution_ solution) { return memberAccessor.executeGetter(solution); } private Collection<Object> extractMemberCollection(MemberAccessor collectionMemberAccessor, Solution_ solution, boolean isFact) { Collection<Object> collection = (Collection<Object>) collectionMemberAccessor.executeGetter(solution); if (collection == null) { throw new IllegalArgumentException("The solutionClass (" + solutionClass + ")'s " + (isFact ? "factCollectionProperty" : "entityCollectionProperty") + " (" + collectionMemberAccessor + ") should never return null.\n" + (collectionMemberAccessor instanceof FieldMemberAccessor ? "" : "Maybe the getter/method always returns null instead of the actual data.\n") + "Maybe the value is null instead of an empty collection."); } return collection; } /** * @param solution never null * @return sometimes null, if the {@link Score} hasn't been calculated yet */ public Score getScore(Solution_ solution) { return (Score) scoreMemberAccessor.executeGetter(solution); } /** * Called when the {@link Score} has been calculated or predicted. * @param solution never null * @param score sometimes null, in rare occasions to indicate that the old {@link Score} is stale, * but no new ones has been calculated */ public void setScore(Solution_ solution, Score score) { scoreMemberAccessor.executeSetter(solution, score); } @Override public String toString() { return getClass().getSimpleName() + "(" + solutionClass.getName() + ")"; } }
PLANNER-831 code comments
optaplanner-core/src/main/java/org/optaplanner/core/impl/domain/solution/descriptor/SolutionDescriptor.java
PLANNER-831 code comments
<ide><path>ptaplanner-core/src/main/java/org/optaplanner/core/impl/domain/solution/descriptor/SolutionDescriptor.java <ide> <ide> public void processAnnotations(DescriptorPolicy descriptorPolicy, ScoreDefinition deprecatedScoreDefinition, List<Class<?>> entityClassList) { <ide> processSolutionAnnotations(descriptorPolicy); <del> ArrayList<Method> potentiallyOverwrittenMethodList = new ArrayList<>(); <add> ArrayList<Method> potentiallyOverwritingMethodList = new ArrayList<>(); <ide> // Iterate inherited members too (unlike for EntityDescriptor where each one is declared) <ide> // to make sure each one is registered <ide> for (Class<?> lineageClass : ConfigUtils.getAllAnnotatedLineageClasses(solutionClass, PlanningSolution.class)) { <ide> List<Member> memberList = ConfigUtils.getDeclaredMembers(lineageClass); <ide> for (Member member : memberList) { <del> if (member instanceof Method && potentiallyOverwrittenMethodList.stream().anyMatch( <del> m -> member.getName().equals(m.getName()) <add> if (member instanceof Method && potentiallyOverwritingMethodList.stream().anyMatch( <add> m -> member.getName().equals(m.getName()) // Short cut to discard negatives faster <ide> && ReflectionHelper.isMethodOverwritten((Method) member, m.getDeclaringClass()))) { <add> // Ignore member because it is an overwritten method <ide> continue; <ide> } <ide> processValueRangeProviderAnnotation(descriptorPolicy, member); <ide> processFactEntityOrScoreAnnotation(descriptorPolicy, member, deprecatedScoreDefinition, entityClassList); <ide> } <del> potentiallyOverwrittenMethodList.ensureCapacity(potentiallyOverwrittenMethodList.size() + memberList.size()); <add> potentiallyOverwritingMethodList.ensureCapacity(potentiallyOverwritingMethodList.size() + memberList.size()); <ide> memberList.stream().filter(member -> member instanceof Method) <del> .forEach(member -> potentiallyOverwrittenMethodList.add((Method) member)); <add> .forEach(member -> potentiallyOverwritingMethodList.add((Method) member)); <ide> } <ide> if (entityCollectionMemberAccessorMap.isEmpty() && entityMemberAccessorMap.isEmpty()) { <ide> throw new IllegalStateException("The solutionClass (" + solutionClass
Java
apache-2.0
2a7bb79375e0b47f0d0df11f7c38f903c40d1ada
0
phax/ph-commons
/** * Copyright (C) 2014-2015 Philip Helger (www.helger.com) * philip[at]helger[dot]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 com.helger.commons.xml.serialize.write; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.dom.DOMSource; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; import com.helger.commons.charset.CCharset; import com.helger.commons.io.stream.NonBlockingByteArrayOutputStream; import com.helger.commons.mock.AbstractCommonsTestCase; import com.helger.commons.mock.CommonsTestHelper; import com.helger.commons.system.ENewLineMode; import com.helger.commons.xml.DefaultXMLIterationHandler; import com.helger.commons.xml.EXMLVersion; import com.helger.commons.xml.XMLFactory; import com.helger.commons.xml.namespace.MapBasedNamespaceContext; import com.helger.commons.xml.serialize.read.DOMReader; import com.helger.commons.xml.transform.StringStreamResult; import com.helger.commons.xml.transform.XMLTransformerFactory; /** * Test class for {@link XMLWriter} * * @author Philip Helger */ public final class XMLWriterTest extends AbstractCommonsTestCase { private static final String DOCTYPE_XHTML10_QNAME = "-//W3C//DTD XHTML 1.0 Strict//EN"; private static final String DOCTYPE_XHTML10_URI = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"; private static final String CRLF = ENewLineMode.DEFAULT.getText (); @Test public void testGetXHTMLString () { final String sSPACER = " "; final String sINDENT = XMLWriterSettings.DEFAULT_INDENTATION_STRING; final String sTAGNAME = "notext"; // Java 1.6 JAXP handles things differently final String sSerTagName = "<" + sTAGNAME + "></" + sTAGNAME + ">"; final Document doc = XMLFactory.newDocument ("html", DOCTYPE_XHTML10_QNAME, DOCTYPE_XHTML10_URI); final Element aHead = (Element) doc.getDocumentElement ().appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, "head")); aHead.appendChild (doc.createTextNode ("Hallo")); final Element aNoText = (Element) doc.getDocumentElement ().appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, sTAGNAME)); aNoText.appendChild (doc.createTextNode ("")); // test including doc type { final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ()); assertEquals ("<!DOCTYPE html PUBLIC \"" + DOCTYPE_XHTML10_QNAME + "\"" + sSPACER + "\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + sSerTagName + CRLF + "</html>" + CRLF, sResult); assertEquals (sResult, XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ())); } // test without doc type { final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML () .setSerializeDocType (EXMLSerializeDocType.IGNORE)); assertEquals ("<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + sSerTagName + CRLF + "</html>" + CRLF, sResult); } { final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML () .setSerializeDocType (EXMLSerializeDocType.IGNORE) .setIndent (EXMLSerializeIndent.NONE)); assertEquals ("<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\"><head>Hallo</head>" + sSerTagName + "</html>", sResult); assertEquals (sResult, XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML () .setSerializeDocType (EXMLSerializeDocType.IGNORE) .setIndent (EXMLSerializeIndent.NONE))); } // add text element aNoText.appendChild (doc.createTextNode ("Hallo ")); final Element b = (Element) aNoText.appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, "strong")); b.appendChild (doc.createTextNode ("Welt")); aNoText.appendChild (doc.createCDATASection ("!!!")); aNoText.appendChild (doc.createComment ("No")); // test without doc type { final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML () .setSerializeDocType (EXMLSerializeDocType.IGNORE) .setIndent (EXMLSerializeIndent.INDENT_AND_ALIGN)); assertEquals ("<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + "<notext>Hallo <strong>Welt</strong><![CDATA[!!!]]><!--No--></notext>" + CRLF + "</html>" + CRLF, sResult); } // test as XML (with doc type and indent) { final String sResult = XMLWriter.getXMLString (doc); assertEquals ("<?xml version=\"1.0\" encoding=\"" + CCharset.CHARSET_UTF_8 + "\"?>" + CRLF + "<!DOCTYPE html PUBLIC \"" + DOCTYPE_XHTML10_QNAME + "\"" + sSPACER + "\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + "<notext>Hallo <strong>Welt</strong><![CDATA[!!!]]><!--No--></notext>" + CRLF + "</html>" + CRLF, sResult); } // test as XML (without doc type and comments but indented) { final String sResult = XMLWriter.getNodeAsString (doc, new XMLWriterSettings ().setSerializeDocType (EXMLSerializeDocType.IGNORE) .setSerializeComments (EXMLSerializeComments.IGNORE) .setIndent (EXMLSerializeIndent.INDENT_AND_ALIGN)); assertEquals ("<?xml version=\"1.0\" encoding=\"" + CCharset.CHARSET_UTF_8 + "\"?>" + CRLF + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + "<notext>Hallo <strong>Welt</strong><![CDATA[!!!]]></notext>" + CRLF + "</html>" + CRLF, sResult); } // test as XML (without doc type and comments but indented) with different // newline String { final String sResult = XMLWriter.getNodeAsString (doc, new XMLWriterSettings ().setSerializeDocType (EXMLSerializeDocType.IGNORE) .setSerializeComments (EXMLSerializeComments.IGNORE) .setIndent (EXMLSerializeIndent.INDENT_AND_ALIGN) .setNewLineMode (ENewLineMode.UNIX)); assertEquals ("<?xml version=\"1.0\" encoding=\"" + CCharset.CHARSET_UTF_8 + "\"?>\n" + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">\n" + sINDENT + "<head>Hallo</head>\n" + sINDENT + "<notext>Hallo <strong>Welt</strong><![CDATA[!!!]]></notext>\n" + "</html>\n", sResult); } // test as XML (without doc type and comments but indented) with different // newline String and different indent { final String sResult = XMLWriter.getNodeAsString (doc, new XMLWriterSettings ().setSerializeDocType (EXMLSerializeDocType.IGNORE) .setSerializeComments (EXMLSerializeComments.IGNORE) .setIndent (EXMLSerializeIndent.INDENT_AND_ALIGN) .setNewLineMode (ENewLineMode.UNIX) .setIndentationString ("\t")); assertEquals ("<?xml version=\"1.0\" encoding=\"" + CCharset.CHARSET_UTF_8 + "\"?>\n" + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">\n" + "\t<head>Hallo</head>\n" + "\t<notext>Hallo <strong>Welt</strong><![CDATA[!!!]]></notext>\n" + "</html>\n", sResult); } assertTrue (XMLWriter.writeToStream (doc, new NonBlockingByteArrayOutputStream ()).isSuccess ()); new XMLSerializerCommons ().write (doc, new DefaultXMLIterationHandler ()); } @Test public void testWriteXMLMultiThreaded () { final String sSPACER = " "; final String sINDENT = XMLWriterSettings.DEFAULT_INDENTATION_STRING; final String sTAGNAME = "notext"; CommonsTestHelper.testInParallel (1000, new Runnable () { public void run () { // Java 1.6 JAXP handles things differently final String sSerTagName = "<" + sTAGNAME + "></" + sTAGNAME + ">"; final Document doc = XMLFactory.newDocument ("html", DOCTYPE_XHTML10_QNAME, DOCTYPE_XHTML10_URI); final Element aHead = (Element) doc.getDocumentElement () .appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, "head")); aHead.appendChild (doc.createTextNode ("Hallo")); final Element aNoText = (Element) doc.getDocumentElement () .appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, sTAGNAME)); aNoText.appendChild (doc.createTextNode ("")); // test including doc type final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ()); assertEquals ("<!DOCTYPE html PUBLIC \"" + DOCTYPE_XHTML10_QNAME + "\"" + sSPACER + "\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + sSerTagName + CRLF + "</html>" + CRLF, sResult); assertEquals (sResult, XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ())); } }); } @Test public void testNestedCDATAs () { final Document doc = XMLFactory.newDocument (); // Containing the forbidden CDATA end marker Element e = doc.createElement ("a"); e.appendChild (doc.createCDATASection ("a]]>b")); assertEquals ("<a><![CDATA[a]]]]><![CDATA[>b]]></a>" + CRLF, XMLWriter.getXMLString (e)); // Containing more than one forbidden CDATA end marker e = doc.createElement ("a"); e.appendChild (doc.createCDATASection ("a]]>b]]>c")); assertEquals ("<a><![CDATA[a]]]]><![CDATA[>b]]]]><![CDATA[>c]]></a>" + CRLF, XMLWriter.getXMLString (e)); // Containing a complete CDATA section e = doc.createElement ("a"); e.appendChild (doc.createCDATASection ("a<![CDATA[x]]>b")); assertEquals ("<a><![CDATA[a<![CDATA[x]]]]><![CDATA[>b]]></a>" + CRLF, XMLWriter.getXMLString (e)); } @Test public void testWithNamespaceContext () { final Document aDoc = XMLFactory.newDocument (); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElementNS ("ns1url", "root")); eRoot.appendChild (aDoc.createElementNS ("ns2url", "child1")); eRoot.appendChild (aDoc.createElementNS ("ns2url", "child2")); final XMLWriterSettings aSettings = new XMLWriterSettings ().setCharset (CCharset.CHARSET_ISO_8859_1_OBJ) .setIndent (EXMLSerializeIndent.NONE); String s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<root xmlns=\"ns1url\">" + "<ns0:child1 xmlns:ns0=\"ns2url\" />" + "<ns0:child2 xmlns:ns0=\"ns2url\" />" + "</root>", s); final MapBasedNamespaceContext aCtx = new MapBasedNamespaceContext (); aCtx.addMapping ("a", "ns1url"); aSettings.setNamespaceContext (aCtx); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<a:root xmlns:a=\"ns1url\">" + "<ns0:child1 xmlns:ns0=\"ns2url\" />" + "<ns0:child2 xmlns:ns0=\"ns2url\" />" + "</a:root>", s); aCtx.addMapping ("xy", "ns2url"); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<a:root xmlns:a=\"ns1url\">" + "<xy:child1 xmlns:xy=\"ns2url\" />" + "<xy:child2 xmlns:xy=\"ns2url\" />" + "</a:root>", s); aSettings.setUseDoubleQuotesForAttributes (false); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='yes'?>" + "<a:root xmlns:a='ns1url'>" + "<xy:child1 xmlns:xy='ns2url' />" + "<xy:child2 xmlns:xy='ns2url' />" + "</a:root>", s); aSettings.setSpaceOnSelfClosedElement (false); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='yes'?>" + "<a:root xmlns:a='ns1url'>" + "<xy:child1 xmlns:xy='ns2url'/>" + "<xy:child2 xmlns:xy='ns2url'/>" + "</a:root>", s); aSettings.setPutNamespaceContextPrefixesInRoot (true); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='yes'?>" + "<a:root xmlns:a='ns1url' xmlns:xy='ns2url'>" + "<xy:child1/>" + "<xy:child2/>" + "</a:root>", s); eRoot.appendChild (aDoc.createElementNS ("ns3url", "zz")); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='yes'?>" + "<a:root xmlns:a='ns1url' xmlns:xy='ns2url'>" + "<xy:child1/>" + "<xy:child2/>" + "<ns0:zz xmlns:ns0='ns3url'/>" + "</a:root>", s); } @Test public void testWithoutEmitNamespaces () { final Document aDoc = XMLFactory.newDocument (); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElementNS ("ns1url", "root")); eRoot.appendChild (aDoc.createElementNS ("ns2url", "child1")); eRoot.appendChild (aDoc.createElementNS ("ns2url", "child2")); final XMLWriterSettings aSettings = new XMLWriterSettings ().setCharset (CCharset.CHARSET_ISO_8859_1_OBJ) .setIndent (EXMLSerializeIndent.NONE); String s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<root xmlns=\"ns1url\">" + "<ns0:child1 xmlns:ns0=\"ns2url\" />" + "<ns0:child2 xmlns:ns0=\"ns2url\" />" + "</root>", s); aSettings.setEmitNamespaces (false); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<root>" + "<child1 />" + "<child2 />" + "</root>", s); aSettings.setPutNamespaceContextPrefixesInRoot (true); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<root>" + "<child1 />" + "<child2 />" + "</root>", s); } @Test public void testXMLVersionNumber () { Document aDoc = XMLFactory.newDocument (EXMLVersion.XML_10); aDoc.appendChild (aDoc.createElement ("any")); String sXML = XMLWriter.getXMLString (aDoc); assertEquals ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + CRLF + "<any />" + CRLF, sXML); aDoc = XMLFactory.newDocument (EXMLVersion.XML_11); aDoc.appendChild (aDoc.createElement ("any")); sXML = XMLWriter.getXMLString (aDoc); assertEquals ("<?xml version=\"1.1\" encoding=\"UTF-8\" standalone=\"yes\"?>" + CRLF + "<any />" + CRLF, sXML); } @Test public void testNumericReferencesXML10 () throws SAXException, TransformerException { for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; ++i) if (!XMLCharHelper.isInvalidXMLTextChar (EXMLSerializeVersion.XML_10, (char) i)) { final String sText = "abc" + (char) i + "def"; final Document aDoc = XMLFactory.newDocument (EXMLVersion.XML_10); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElement ("root")); eRoot.appendChild (aDoc.createTextNode (sText)); // Use regular transformer final Transformer aTransformer = XMLTransformerFactory.newTransformer (); aTransformer.setOutputProperty (OutputKeys.ENCODING, CCharset.CHARSET_UTF_8); aTransformer.setOutputProperty (OutputKeys.INDENT, "yes"); aTransformer.setOutputProperty (OutputKeys.VERSION, EXMLVersion.XML_10.getVersion ()); final StringStreamResult aRes = new StringStreamResult (); aTransformer.transform (new DOMSource (aDoc), aRes); final String sXML = aRes.getAsString (); final Document aDoc2 = DOMReader.readXMLDOM (sXML); assertNotNull (aDoc2); } } @Test public void testNumericReferencesXML11 () throws SAXException, TransformerException { for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; ++i) if (!XMLCharHelper.isInvalidXMLTextChar (EXMLSerializeVersion.XML_11, (char) i)) { final String sText = "abc" + (char) i + "def"; final Document aDoc = XMLFactory.newDocument (EXMLVersion.XML_11); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElement ("root")); eRoot.appendChild (aDoc.createTextNode (sText)); final Transformer aTransformer = XMLTransformerFactory.newTransformer (); aTransformer.setOutputProperty (OutputKeys.ENCODING, CCharset.CHARSET_UTF_8); aTransformer.setOutputProperty (OutputKeys.INDENT, "no"); aTransformer.setOutputProperty (OutputKeys.VERSION, EXMLVersion.XML_11.getVersion ()); final StringStreamResult aRes = new StringStreamResult (); aTransformer.transform (new DOMSource (aDoc), aRes); final String sXML = aRes.getAsString (); final Document aDoc2 = DOMReader.readXMLDOM (sXML); assertNotNull (aDoc2); } } @Test public void testAttributesWithNamespaces () throws SAXException { final XMLWriterSettings aSettings = new XMLWriterSettings ().setIndent (EXMLSerializeIndent.NONE) .setCharset (CCharset.CHARSET_ISO_8859_1_OBJ); final Document aDoc = XMLFactory.newDocument (); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElementNS ("ns1url", "root")); final Element e1 = (Element) eRoot.appendChild (aDoc.createElementNS ("ns2url", "child1")); e1.setAttributeNS ("ns2url", "attr1", "value1"); final Element e2 = (Element) eRoot.appendChild (aDoc.createElementNS ("ns2url", "child2")); e2.setAttributeNS ("ns3url", "attr2", "value2"); String s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<root xmlns=\"ns1url\">" + "<ns0:child1 xmlns:ns0=\"ns2url\" ns0:attr1=\"value1\" />" + "<ns0:child2 xmlns:ns0=\"ns2url\" xmlns:ns1=\"ns3url\" ns1:attr2=\"value2\" />" + "</root>", s); assertEquals (s, XMLWriter.getNodeAsString (DOMReader.readXMLDOM (s), aSettings)); aSettings.setEmitNamespaces (false); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<root>" + "<child1 attr1=\"value1\" />" + "<child2 attr2=\"value2\" />" + "</root>", s); } @Test public void testHTML4BracketMode () { final String sINDENT = XMLWriterSettings.DEFAULT_INDENTATION_STRING; final Document doc = XMLFactory.newDocument ("html", DOCTYPE_XHTML10_QNAME, DOCTYPE_XHTML10_URI); final Element aHead = (Element) doc.getDocumentElement ().appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, "head")); aHead.appendChild (doc.createTextNode ("Hallo")); final Element aNoText = (Element) doc.getDocumentElement ().appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, "body")); aNoText.appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, "img")); // test including doc type final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ()); assertEquals ("<!DOCTYPE html PUBLIC \"" + DOCTYPE_XHTML10_QNAME + "\" \"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + "<body>" + CRLF + sINDENT + sINDENT + // Unclosed img :) "<img>" + CRLF + sINDENT + "</body>" + CRLF + "</html>" + CRLF, sResult); } }
src/test/java/com/helger/commons/xml/serialize/write/XMLWriterTest.java
/** * Copyright (C) 2014-2015 Philip Helger (www.helger.com) * philip[at]helger[dot]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 com.helger.commons.xml.serialize.write; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.dom.DOMSource; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; import com.helger.commons.charset.CCharset; import com.helger.commons.io.stream.NonBlockingByteArrayOutputStream; import com.helger.commons.mock.AbstractCommonsTestCase; import com.helger.commons.mock.CommonsTestHelper; import com.helger.commons.system.ENewLineMode; import com.helger.commons.xml.DefaultXMLIterationHandler; import com.helger.commons.xml.EXMLVersion; import com.helger.commons.xml.XMLFactory; import com.helger.commons.xml.namespace.MapBasedNamespaceContext; import com.helger.commons.xml.serialize.read.DOMReader; import com.helger.commons.xml.transform.StringStreamResult; import com.helger.commons.xml.transform.XMLTransformerFactory; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * Test class for {@link XMLWriter} * * @author Philip Helger */ public final class XMLWriterTest extends AbstractCommonsTestCase { private static final String DOCTYPE_XHTML10_QNAME = "-//W3C//DTD XHTML 1.0 Strict//EN"; private static final String DOCTYPE_XHTML10_URI = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"; private static final String CRLF = ENewLineMode.DEFAULT.getText (); /** * Test the method getXHTMLString */ @SuppressFBWarnings ("NP_NONNULL_PARAM_VIOLATION") @Test public void testGetXHTMLString () { final String sSPACER = " "; final String sINDENT = XMLWriterSettings.DEFAULT_INDENTATION_STRING; final String sTAGNAME = "notext"; // Java 1.6 JAXP handles things differently final String sSerTagName = "<" + sTAGNAME + "></" + sTAGNAME + ">"; final Document doc = XMLFactory.newDocument ("html", DOCTYPE_XHTML10_QNAME, DOCTYPE_XHTML10_URI); final Element aHead = (Element) doc.getDocumentElement ().appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, "head")); aHead.appendChild (doc.createTextNode ("Hallo")); final Element aNoText = (Element) doc.getDocumentElement ().appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, sTAGNAME)); aNoText.appendChild (doc.createTextNode ("")); // test including doc type { final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ()); assertEquals ("<!DOCTYPE html PUBLIC \"" + DOCTYPE_XHTML10_QNAME + "\"" + sSPACER + "\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + sSerTagName + CRLF + "</html>" + CRLF, sResult); assertEquals (sResult, XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ())); } // test without doc type { final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML () .setSerializeDocType (EXMLSerializeDocType.IGNORE)); assertEquals ("<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + sSerTagName + CRLF + "</html>" + CRLF, sResult); } { final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML () .setSerializeDocType (EXMLSerializeDocType.IGNORE) .setIndent (EXMLSerializeIndent.NONE)); assertEquals ("<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\"><head>Hallo</head>" + sSerTagName + "</html>", sResult); assertEquals (sResult, XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML () .setSerializeDocType (EXMLSerializeDocType.IGNORE) .setIndent (EXMLSerializeIndent.NONE))); } // add text element aNoText.appendChild (doc.createTextNode ("Hallo ")); final Element b = (Element) aNoText.appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, "strong")); b.appendChild (doc.createTextNode ("Welt")); aNoText.appendChild (doc.createCDATASection ("!!!")); aNoText.appendChild (doc.createComment ("No")); // test without doc type { final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML () .setSerializeDocType (EXMLSerializeDocType.IGNORE) .setIndent (EXMLSerializeIndent.INDENT_AND_ALIGN)); assertEquals ("<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + "<notext>Hallo <strong>Welt</strong><![CDATA[!!!]]><!--No--></notext>" + CRLF + "</html>" + CRLF, sResult); } // test as XML (with doc type and indent) { final String sResult = XMLWriter.getXMLString (doc); assertEquals ("<?xml version=\"1.0\" encoding=\"" + CCharset.CHARSET_UTF_8 + "\"?>" + CRLF + "<!DOCTYPE html PUBLIC \"" + DOCTYPE_XHTML10_QNAME + "\"" + sSPACER + "\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + "<notext>Hallo <strong>Welt</strong><![CDATA[!!!]]><!--No--></notext>" + CRLF + "</html>" + CRLF, sResult); } // test as XML (without doc type and comments but indented) { final String sResult = XMLWriter.getNodeAsString (doc, new XMLWriterSettings ().setSerializeDocType (EXMLSerializeDocType.IGNORE) .setSerializeComments (EXMLSerializeComments.IGNORE) .setIndent (EXMLSerializeIndent.INDENT_AND_ALIGN)); assertEquals ("<?xml version=\"1.0\" encoding=\"" + CCharset.CHARSET_UTF_8 + "\"?>" + CRLF + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + "<notext>Hallo <strong>Welt</strong><![CDATA[!!!]]></notext>" + CRLF + "</html>" + CRLF, sResult); } // test as XML (without doc type and comments but indented) with different // newline String { final String sResult = XMLWriter.getNodeAsString (doc, new XMLWriterSettings ().setSerializeDocType (EXMLSerializeDocType.IGNORE) .setSerializeComments (EXMLSerializeComments.IGNORE) .setIndent (EXMLSerializeIndent.INDENT_AND_ALIGN) .setNewLineMode (ENewLineMode.UNIX)); assertEquals ("<?xml version=\"1.0\" encoding=\"" + CCharset.CHARSET_UTF_8 + "\"?>\n" + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">\n" + sINDENT + "<head>Hallo</head>\n" + sINDENT + "<notext>Hallo <strong>Welt</strong><![CDATA[!!!]]></notext>\n" + "</html>\n", sResult); } // test as XML (without doc type and comments but indented) with different // newline String and different indent { final String sResult = XMLWriter.getNodeAsString (doc, new XMLWriterSettings ().setSerializeDocType (EXMLSerializeDocType.IGNORE) .setSerializeComments (EXMLSerializeComments.IGNORE) .setIndent (EXMLSerializeIndent.INDENT_AND_ALIGN) .setNewLineMode (ENewLineMode.UNIX) .setIndentationString ("\t")); assertEquals ("<?xml version=\"1.0\" encoding=\"" + CCharset.CHARSET_UTF_8 + "\"?>\n" + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">\n" + "\t<head>Hallo</head>\n" + "\t<notext>Hallo <strong>Welt</strong><![CDATA[!!!]]></notext>\n" + "</html>\n", sResult); } assertTrue (XMLWriter.writeToStream (doc, new NonBlockingByteArrayOutputStream ()).isSuccess ()); new XMLSerializerCommons ().write (doc, new DefaultXMLIterationHandler ()); } @Test public void testWriteXMLMultiThreaded () { final String sSPACER = " "; final String sINDENT = XMLWriterSettings.DEFAULT_INDENTATION_STRING; final String sTAGNAME = "notext"; CommonsTestHelper.testInParallel (1000, new Runnable () { public void run () { // Java 1.6 JAXP handles things differently final String sSerTagName = "<" + sTAGNAME + "></" + sTAGNAME + ">"; final Document doc = XMLFactory.newDocument ("html", DOCTYPE_XHTML10_QNAME, DOCTYPE_XHTML10_URI); final Element aHead = (Element) doc.getDocumentElement () .appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, "head")); aHead.appendChild (doc.createTextNode ("Hallo")); final Element aNoText = (Element) doc.getDocumentElement () .appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, sTAGNAME)); aNoText.appendChild (doc.createTextNode ("")); // test including doc type final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ()); assertEquals ("<!DOCTYPE html PUBLIC \"" + DOCTYPE_XHTML10_QNAME + "\"" + sSPACER + "\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + sSerTagName + CRLF + "</html>" + CRLF, sResult); assertEquals (sResult, XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ())); } }); } @Test public void testNestedCDATAs () { final Document doc = XMLFactory.newDocument (); // Containing the forbidden CDATA end marker Element e = doc.createElement ("a"); e.appendChild (doc.createCDATASection ("a]]>b")); assertEquals ("<a><![CDATA[a]]]]><![CDATA[>b]]></a>" + CRLF, XMLWriter.getXMLString (e)); // Containing more than one forbidden CDATA end marker e = doc.createElement ("a"); e.appendChild (doc.createCDATASection ("a]]>b]]>c")); assertEquals ("<a><![CDATA[a]]]]><![CDATA[>b]]]]><![CDATA[>c]]></a>" + CRLF, XMLWriter.getXMLString (e)); // Containing a complete CDATA section e = doc.createElement ("a"); e.appendChild (doc.createCDATASection ("a<![CDATA[x]]>b")); assertEquals ("<a><![CDATA[a<![CDATA[x]]]]><![CDATA[>b]]></a>" + CRLF, XMLWriter.getXMLString (e)); } @Test public void testWithNamespaceContext () { final Document aDoc = XMLFactory.newDocument (); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElementNS ("ns1url", "root")); eRoot.appendChild (aDoc.createElementNS ("ns2url", "child1")); eRoot.appendChild (aDoc.createElementNS ("ns2url", "child2")); final XMLWriterSettings aSettings = new XMLWriterSettings ().setCharset (CCharset.CHARSET_ISO_8859_1_OBJ) .setIndent (EXMLSerializeIndent.NONE); String s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<root xmlns=\"ns1url\">" + "<ns0:child1 xmlns:ns0=\"ns2url\" />" + "<ns0:child2 xmlns:ns0=\"ns2url\" />" + "</root>", s); final MapBasedNamespaceContext aCtx = new MapBasedNamespaceContext (); aCtx.addMapping ("a", "ns1url"); aSettings.setNamespaceContext (aCtx); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<a:root xmlns:a=\"ns1url\">" + "<ns0:child1 xmlns:ns0=\"ns2url\" />" + "<ns0:child2 xmlns:ns0=\"ns2url\" />" + "</a:root>", s); aCtx.addMapping ("xy", "ns2url"); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<a:root xmlns:a=\"ns1url\">" + "<xy:child1 xmlns:xy=\"ns2url\" />" + "<xy:child2 xmlns:xy=\"ns2url\" />" + "</a:root>", s); aSettings.setUseDoubleQuotesForAttributes (false); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='yes'?>" + "<a:root xmlns:a='ns1url'>" + "<xy:child1 xmlns:xy='ns2url' />" + "<xy:child2 xmlns:xy='ns2url' />" + "</a:root>", s); aSettings.setSpaceOnSelfClosedElement (false); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='yes'?>" + "<a:root xmlns:a='ns1url'>" + "<xy:child1 xmlns:xy='ns2url'/>" + "<xy:child2 xmlns:xy='ns2url'/>" + "</a:root>", s); aSettings.setPutNamespaceContextPrefixesInRoot (true); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='yes'?>" + "<a:root xmlns:a='ns1url' xmlns:xy='ns2url'>" + "<xy:child1/>" + "<xy:child2/>" + "</a:root>", s); eRoot.appendChild (aDoc.createElementNS ("ns3url", "zz")); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='yes'?>" + "<a:root xmlns:a='ns1url' xmlns:xy='ns2url'>" + "<xy:child1/>" + "<xy:child2/>" + "<ns0:zz xmlns:ns0='ns3url'/>" + "</a:root>", s); } @Test public void testWithoutEmitNamespaces () { final Document aDoc = XMLFactory.newDocument (); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElementNS ("ns1url", "root")); eRoot.appendChild (aDoc.createElementNS ("ns2url", "child1")); eRoot.appendChild (aDoc.createElementNS ("ns2url", "child2")); final XMLWriterSettings aSettings = new XMLWriterSettings ().setCharset (CCharset.CHARSET_ISO_8859_1_OBJ) .setIndent (EXMLSerializeIndent.NONE); String s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<root xmlns=\"ns1url\">" + "<ns0:child1 xmlns:ns0=\"ns2url\" />" + "<ns0:child2 xmlns:ns0=\"ns2url\" />" + "</root>", s); aSettings.setEmitNamespaces (false); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<root>" + "<child1 />" + "<child2 />" + "</root>", s); aSettings.setPutNamespaceContextPrefixesInRoot (true); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<root>" + "<child1 />" + "<child2 />" + "</root>", s); } @Test public void testXMLVersionNumber () { Document aDoc = XMLFactory.newDocument (EXMLVersion.XML_10); aDoc.appendChild (aDoc.createElement ("any")); String sXML = XMLWriter.getXMLString (aDoc); assertEquals ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + CRLF + "<any />" + CRLF, sXML); aDoc = XMLFactory.newDocument (EXMLVersion.XML_11); aDoc.appendChild (aDoc.createElement ("any")); sXML = XMLWriter.getXMLString (aDoc); assertEquals ("<?xml version=\"1.1\" encoding=\"UTF-8\" standalone=\"yes\"?>" + CRLF + "<any />" + CRLF, sXML); } @Test public void testNumericReferencesXML10 () throws SAXException, TransformerException { for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; ++i) if (!XMLCharHelper.isInvalidXMLTextChar (EXMLSerializeVersion.XML_10, (char) i)) { final String sText = "abc" + (char) i + "def"; final Document aDoc = XMLFactory.newDocument (EXMLVersion.XML_10); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElement ("root")); eRoot.appendChild (aDoc.createTextNode (sText)); // Use regular transformer final Transformer aTransformer = XMLTransformerFactory.newTransformer (); aTransformer.setOutputProperty (OutputKeys.ENCODING, CCharset.CHARSET_UTF_8); aTransformer.setOutputProperty (OutputKeys.INDENT, "yes"); aTransformer.setOutputProperty (OutputKeys.VERSION, EXMLVersion.XML_10.getVersion ()); final StringStreamResult aRes = new StringStreamResult (); aTransformer.transform (new DOMSource (aDoc), aRes); final String sXML = aRes.getAsString (); final Document aDoc2 = DOMReader.readXMLDOM (sXML); assertNotNull (aDoc2); } } @Test public void testNumericReferencesXML11 () throws SAXException, TransformerException { for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; ++i) if (!XMLCharHelper.isInvalidXMLTextChar (EXMLSerializeVersion.XML_11, (char) i)) { final String sText = "abc" + (char) i + "def"; final Document aDoc = XMLFactory.newDocument (EXMLVersion.XML_11); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElement ("root")); eRoot.appendChild (aDoc.createTextNode (sText)); final Transformer aTransformer = XMLTransformerFactory.newTransformer (); aTransformer.setOutputProperty (OutputKeys.ENCODING, CCharset.CHARSET_UTF_8); aTransformer.setOutputProperty (OutputKeys.INDENT, "no"); aTransformer.setOutputProperty (OutputKeys.VERSION, EXMLVersion.XML_11.getVersion ()); final StringStreamResult aRes = new StringStreamResult (); aTransformer.transform (new DOMSource (aDoc), aRes); final String sXML = aRes.getAsString (); final Document aDoc2 = DOMReader.readXMLDOM (sXML); assertNotNull (aDoc2); } } @Test public void testAttributesWithNamespaces () throws SAXException { final XMLWriterSettings aSettings = new XMLWriterSettings ().setIndent (EXMLSerializeIndent.NONE) .setCharset (CCharset.CHARSET_ISO_8859_1_OBJ); final Document aDoc = XMLFactory.newDocument (); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElementNS ("ns1url", "root")); final Element e1 = (Element) eRoot.appendChild (aDoc.createElementNS ("ns2url", "child1")); e1.setAttributeNS ("ns2url", "attr1", "value1"); final Element e2 = (Element) eRoot.appendChild (aDoc.createElementNS ("ns2url", "child2")); e2.setAttributeNS ("ns3url", "attr2", "value2"); String s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<root xmlns=\"ns1url\">" + "<ns0:child1 xmlns:ns0=\"ns2url\" ns0:attr1=\"value1\" />" + "<ns0:child2 xmlns:ns0=\"ns2url\" xmlns:ns1=\"ns3url\" ns1:attr2=\"value2\" />" + "</root>", s); assertEquals (s, XMLWriter.getNodeAsString (DOMReader.readXMLDOM (s), aSettings)); aSettings.setEmitNamespaces (false); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>" + "<root>" + "<child1 attr1=\"value1\" />" + "<child2 attr2=\"value2\" />" + "</root>", s); } }
Added test for bracket mode handler
src/test/java/com/helger/commons/xml/serialize/write/XMLWriterTest.java
Added test for bracket mode handler
<ide><path>rc/test/java/com/helger/commons/xml/serialize/write/XMLWriterTest.java <ide> import com.helger.commons.xml.transform.StringStreamResult; <ide> import com.helger.commons.xml.transform.XMLTransformerFactory; <ide> <del>import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; <del> <ide> /** <ide> * Test class for {@link XMLWriter} <ide> * <ide> private static final String DOCTYPE_XHTML10_URI = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"; <ide> private static final String CRLF = ENewLineMode.DEFAULT.getText (); <ide> <del> /** <del> * Test the method getXHTMLString <del> */ <del> @SuppressFBWarnings ("NP_NONNULL_PARAM_VIOLATION") <ide> @Test <ide> public void testGetXHTMLString () <ide> { <ide> + "<child2 attr2=\"value2\" />" <ide> + "</root>", s); <ide> } <add> <add> @Test <add> public void testHTML4BracketMode () <add> { <add> final String sINDENT = XMLWriterSettings.DEFAULT_INDENTATION_STRING; <add> <add> final Document doc = XMLFactory.newDocument ("html", DOCTYPE_XHTML10_QNAME, DOCTYPE_XHTML10_URI); <add> final Element aHead = (Element) doc.getDocumentElement ().appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, <add> "head")); <add> aHead.appendChild (doc.createTextNode ("Hallo")); <add> final Element aNoText = (Element) doc.getDocumentElement ().appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, <add> "body")); <add> aNoText.appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, "img")); <add> <add> // test including doc type <add> final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ()); <add> assertEquals ("<!DOCTYPE html PUBLIC \"" + <add> DOCTYPE_XHTML10_QNAME + <add> "\" \"" + <add> DOCTYPE_XHTML10_URI + <add> "\">" + <add> CRLF + <add> "<html xmlns=\"" + <add> DOCTYPE_XHTML10_URI + <add> "\">" + <add> CRLF + <add> sINDENT + <add> "<head>Hallo</head>" + <add> CRLF + <add> sINDENT + <add> "<body>" + <add> CRLF + <add> sINDENT + <add> sINDENT + <add> // Unclosed img :) <add> "<img>" + <add> CRLF + <add> sINDENT + <add> "</body>" + <add> CRLF + <add> "</html>" + <add> CRLF, sResult); <add> } <ide> }
Java
bsd-3-clause
2fbc95fa8da1868a8b5c3fa548e0bb0855b51d66
0
UNFPAInnovation/GetIn_Mobile,UNFPAInnovation/GetIn_Mobile
package org.sana.android.procedure; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.Animatable; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.animation.Animation; import android.widget.Button; import android.widget.Gallery; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import org.sana.R; import org.sana.android.media.AudioPlayer; import org.sana.android.media.EducationResource; import org.sana.android.util.SanaUtil; import org.w3c.dom.Node; import org.w3c.dom.Text; import java.net.URISyntaxException; /** * A ProcedureElement is an item that can be placed on a page in a Sana * procedure. Typically there will only be one ProcedureElement per page, but * this style suggestion is not enforced, and users can make XML procedure * definitions that contain several ProcedureElements per page. * <p/> * A ProcedureElement, generally speaking, asks a question and may allow for an * answer. For example, a RadioElement poses a question and allows a user to * choose among response buttons. * * ProcedureElements are defined in XML and dynamically created from the XML in * Sana. * <p/> * <ul type="none"> * <li><b>Clinical Use </b> Defined by subclasses.</li> * <li><b>Collects </b> Defined by subclasses.</li> * </ul> * The <em>Collects</em> documentation should declare the format of any returned * answer strings * * @author Sana Development Team */ public abstract class ProcedureElement { public static String TAG = ProcedureElement.class.getSimpleName(); /** * An enumeration of the valid ProcedureElement types. * * @author Sana Development Team */ public static enum ElementType { /** Provides text display */ TEXT(""), /** Provides text capture. */ ENTRY(""), /** Provides exclusive option selector as a dropdown box. */ SELECT(""), /** An entry element for displaying/entering a patient identifier */ PATIENT_ID(""), /** A non-exclusive option selector as a list of checkboxes. */ MULTI_SELECT(""), /** An exclusive multi-option selector as a list of radio buttons */ RADIO(""), /** Provides capture of one or more images */ PICTURE("image.jpg"), /** Provides capture of a single audio resource. */ SOUND("sound.3gp"), /** Provides attachment of a binary file for upload */ BINARYFILE("binary.bin"), /** A marker for invalid elements */ INVALID(""), /** Provides capture of GPS coordinates */ GPS(""), /** Provides capture of a date */ DATE(""), /** Provides a viewable resource for patient education. */ EDUCATION_RESOURCE(""), /** Provides access to 3rd party tools for data capture where the data * is returned directly. */ PLUGIN(""), /** Provides access to 3rd party tools for data capture where the data * is not returned directly and must be manually entered by the user. */ ENTRY_PLUGIN(""), HIDDEN(""), AGE(""), TRUTH; private String filename; private ElementType(){ this(""); } private ElementType(String filename) { this.filename = filename; } /** * Returns the default filename for a given ElementType * @return */ public String getFilename() { return filename; } } protected String id; protected String question; protected String answer; protected String concept; protected String action = null; // Resource of a corresponding figure for this element. protected String figure; // Resource of a corresponding audio prompt for this element. protected String audioPrompt; // Whether a null answer is allowed private boolean bRequired = false; // Optional attributes - specific element types must implement as necessary protected String defaultValue = null; protected String defaultPrompt = null; private Procedure procedure; private Context cachedContext; private View cachedView; private AudioPlayer mAudioPlayer; private String helpText; /** * Constructs the view of this ProcedureElement * * @param c the current Context */ protected abstract View createView(Context c); void clearCachedView() { cachedView = null; } /** * Constructs a new Instance. * * @param id The unique identifier of this element within its procedure. * @param question The text that will be displayed to the user as a question * @param answer The result of data capture. * @param concept A required categorization of the type of data captured. * @param figure An optional figure to display to the user. * @param audioPrompt An optional audio prompt to play for the user. */ protected ProcedureElement(String id, String question, String answer, String concept, String figure, String audioPrompt) { this.id = id; this.question = question; this.answer = answer; this.concept = concept; this.figure = figure; this.audioPrompt = audioPrompt; } /** * A reference to the enclosing Procedure * @return A Procedure instance. */ protected Procedure getProcedure() { // set the ImageView bounds to match the Drawable's dimensions return procedure; } /** * Sets the enclosing procedure * @param procedure the new enclosing procedure. */ public void setProcedure(Procedure procedure) { this.procedure = procedure; } /** * Whether this element is considered active. * @return */ protected boolean isViewActive() { return !(cachedView == null); } /** * A cached Context. * @return The Context this element holds a reference to. */ protected Context getContext() { return cachedContext; } /** * A visible representation of this object. * @param c The Context which will be used in the View constructors for this * object's representation. * @return A new view of this object or cached view if it exists. */ public View toView(Context c) { if(cachedView == null || cachedContext != c) { cachedView = createView(c); cachedContext = c; } return cachedView; } /** * Returns the ElementType of this element as defined in the * ProcedureElement ElementType enum. */ public abstract ElementType getType(); /** * Gets the value of the answer attribute. * * @return A String representation of collected data. */ public String getAnswer(){ return answer; } /** * Set the value of the answer attribute as a String representation of * collected data. * * @param answer the new answer */ public void setAnswer(String answer){ this.answer = answer; } /** * Whether this element is considered required * @return */ public boolean isRequired() { return bRequired; } /** * Sets the required state of this element. * @param required The new required state. */ public void setRequired(boolean required) { this.bRequired = required; } /** * Help text associated with this element * @return An informative string. */ public String getHelpText() { return helpText; } /** * Sets the help text for this instance. * @param helpText the new help string. */ public void setHelpText(String helpText) { this.helpText = helpText; } public String getAction(){ return action; } /** * Whether this element is valid. * @return true if not required or required and answer is not empty * @throws ValidationError */ public boolean validate() throws ValidationError { if (bRequired && "".equals(getAnswer().trim())) { String msg = TextUtils.isEmpty(helpText)? getString(R.string.general_input_required): helpText; throw new ValidationError(msg); } return true; } /** * Tell the element's widget to refresh itself. */ public void refreshWidget() { } /** * Writes a string representation of this object to a StringBuilder. * Extending classes should override appendOptionalAttributes if they * require attributes beyond those defined in this class. * * @param sb the builder to write to. */ public void buildXML(StringBuilder sb){ sb.append("<Element "); sb.append("type=\"" + getType().name() + "\" "); sb.append("id=\"" + getId()+ "\" "); sb.append("question=\"" + getQuestion()+ "\" "); sb.append("answer=\"" + getAnswer()+ "\" "); sb.append("figure=\"" + getFigure()+ "\" "); sb.append("concept=\"" + getConcept()+ "\" "); sb.append("audio=\"" + getAudioPrompt()+ "\" "); sb.append("required=\"" + isRequired()+ "\" "); appendOptionalAttributes(sb); sb.append("/>\n"); } protected void appendOptionalAttributes(StringBuilder sb){ if(!TextUtils.isEmpty(action)) sb.append("action=\"" + action+ "\" "); if(hasDefault()) sb.append("default=\"" + getDefault()+ "\" "); return; } /** * Build the XML representation of this ProcedureElement. Should only use * this if you intend to use only the XML for this element. If you are * building the XML for this Procedure, then prefer buildXML with a * StringBuilder since String operations are slow. */ public String toXML() { StringBuilder sb = new StringBuilder(); buildXML(sb); return sb.toString(); } /** * Create an element from an XML element node of a procedure definition. * @param node a Node object containing a ProcedureElement representation */ public static ProcedureElement createElementfromXML(Node node) throws ProcedureParseException { //Log.i(TAG, "fromXML(" + node.getNodeName() + ")"); if(!node.getNodeName().equals("Element")) { throw new ProcedureParseException("Element got NodeName " + node.getNodeName()); } String questionStr = SanaUtil.getNodeAttributeOrDefault(node, "question", ""); String answerStr = SanaUtil.getNodeAttributeOrDefault(node, "answer", null); String typeStr = SanaUtil.getNodeAttributeOrDefault(node, "type", "INVALID"); String conceptStr = SanaUtil.getNodeAttributeOrDefault(node, "concept", ""); String idStr = SanaUtil.getNodeAttributeOrFail(node, "id", new ProcedureParseException("Element doesn't have id number")); String figureStr = SanaUtil.getNodeAttributeOrDefault(node, "figure", ""); String audioStr = SanaUtil.getNodeAttributeOrDefault(node, "audio", ""); ElementType etype = ElementType.valueOf(typeStr); ProcedureElement el = null; switch(etype) { case TEXT: el = TextElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case ENTRY: el = TextEntryElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case SELECT: el = SelectElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case MULTI_SELECT: el = MultiSelectElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case RADIO: el = RadioElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case PICTURE: el = PictureElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case SOUND: el = SoundElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case GPS: el = GpsElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case BINARYFILE: el = BinaryUploadElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case PATIENT_ID: el = PatientIdElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case DATE: el = DateElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case EDUCATION_RESOURCE: el = EducationResourceElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case PLUGIN: el = PluginElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case ENTRY_PLUGIN: el = PluginEntryElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case HIDDEN: el = HiddenElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case AGE: el = AgeElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case TRUTH: el = TruthElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case INVALID: default: throw new ProcedureParseException("Got invalid node type : " + etype); } if (el == null) { throw new ProcedureParseException("Failed to parse node with id " + idStr); } String helpStr = SanaUtil.getNodeAttributeOrDefault(node, "helpText", ""); el.setHelpText(helpStr); String requiredStr = SanaUtil.getNodeAttributeOrDefault(node, "required", "false"); if ("true".equals(requiredStr)) { el.setRequired(true); } else if ("false".equals(requiredStr)) { el.setRequired(false); } else { throw new ProcedureParseException("Argument to \'required\' "+ "attribute invalid for id " + idStr + ". Must be \'true\' or \'false\'"); } return el; } public static void parseOptionalAttributes(Node node, ProcedureElement el) throws ProcedureParseException { Log.i(TAG, "parseOptionalAttributes(Node,ProcedureElement)"); String attr = null; // action attr = SanaUtil.getNodeAttributeOrDefault(node, "action", ""); if(!TextUtils.isEmpty(attr)) el.action = new String(attr); // default attr = SanaUtil.getNodeAttributeOrDefault(node, "default", ""); el.setDefault(new String(attr)); // helpText attr = SanaUtil.getNodeAttributeOrDefault(node, "helpText", ""); el.setHelpText(new String(attr)); // required attr = SanaUtil.getNodeAttributeOrDefault(node, "required", "false"); if ("true".equals(attr)) { el.setRequired(true); } else if ("false".equals(attr)) { el.setRequired(false); } else { throw new ProcedureParseException("Argument to \'required\' " + "attribute invalid for id " + el.getId()+ ". Must be \'true\' or \'false\'"); } } /** @return The value of the id attribute */ public String getId() { return id; } /** @return Gets the identifier for any associated education resources */ public String mediaId(){ return EducationResource.toId(concept+question); } /** * @return the question string originally defined in the XML procedure * definition. */ public String getQuestion() { return question; } /** * @return the medical concept associated with this ProcedureElement */ public String getConcept() { return concept; } /** * @return the figure URL associated with this ProcedureElement */ public String getFigure() { return figure; } /** @return true if this instance has an audio prompt */ boolean hasAudioPrompt() { return !"".equals(audioPrompt); } /** plays this instance's audio prompt */ void playAudioPrompt() { if (mAudioPlayer != null) mAudioPlayer.play(); } /** @return the audioPrompt string */ public String getAudioPrompt() { return audioPrompt; } /** * Returns a localized String from the application package's default string * table. * * @param resId Resource Id for the string * @return */ public String getString(int resId){ return getContext().getString(resId); } /** * Appends another View object a view of this object to a new View . * @param c A valid Context. * @param v The view to append first. * @return A new View containing the parameter View and a View of this * object. */ public View encapsulateQuestion(Context c, View v) { // Add question view TextView textView = new TextView(c); textView.setSingleLine(false); textView.setGravity(Gravity.LEFT); String q = question.replace("\\n", "\n"); Log.d(TAG, "...show question id = " + getProcedure().idsShown()); if(getProcedure().idsShown() && !getType().equals(ElementType.TEXT)){ textView.setText(String.format("%s: %s", getId(), q)); }else{ textView.setText(q); } //textView.setGravity(Gravity.CENTER_HORIZONTAL); textView.setTextAppearance(c, android.R.style.TextAppearance_Large); View questionView = textView; questionView.setPadding(10,5,10,5); // Add image if provided ImageView imageView = null; //Set accompanying figure if(!TextUtils.isEmpty(figure)) { try{ String imagePath = c.getPackageName() + ":" + figure; Log.d(TAG, "Using figure: " + figure); int resID = c.getResources().getIdentifier(figure, null, null); Log.d(TAG, "Using figure id: " + resID); imageView = new ImageView(c); imageView.setImageResource(resID); imageView.setAdjustViewBounds(true); // set the ImageView bounds to match the Drawable's dimensions imageView.setLayoutParams(new Gallery.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); imageView.setPadding(10,10,10,10); } catch(Exception e){ Log.e(TAG, "Couldn't find resource figure " + e.toString()); } } // Add audio prompt if provided if (hasAudioPrompt()) { try { String resourcePath = c.getPackageName() + ":" + audioPrompt; int resID = c.getResources().getIdentifier(resourcePath, null, null); Log.i(TAG, "Looking up ID for resource: " + resourcePath + ", " + "got " + resID); if (resID != 0) { mAudioPlayer = new AudioPlayer(resID); View playerView = mAudioPlayer.createView(c); playerView.setLayoutParams(new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); LinearLayout audioPromptView = new LinearLayout(c); audioPromptView.setOrientation(LinearLayout.HORIZONTAL); audioPromptView.setLayoutParams(new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); audioPromptView.setGravity(Gravity.CENTER); // Insert the play button to the left of the current // question view. audioPromptView.addView(playerView); audioPromptView.addView(questionView); questionView = audioPromptView; } } catch (Exception e) { Log.e(TAG, "Couldn't find resource for audio prompt: " + e.toString()); } } //Log.d(TAG, "Loaded: " +this.toString()); LinearLayout ll = new LinearLayout(c); ll.setOrientation(LinearLayout.VERTICAL); //Add to layout ll.addView(questionView); if (imageView != null) ll.addView(imageView); // Add Buttons if provided if(!TextUtils.isEmpty(action)){ View actionView = getActions(c); actionView.setPadding(5,5,5,5); ll.addView(actionView); } else { //Log.w(TAG, "Empty action string!"); } if(v != null){ LinearLayout viewHolder = new LinearLayout(c); viewHolder.addView(v); viewHolder.setGravity(Gravity.CENTER_HORIZONTAL); ll.addView(viewHolder, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); } ll.setGravity(Gravity.CENTER); ll.setPadding(5, 0, 5, 0); ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); return ll; } @Override public String toString(){ /* Gson gson = new Gson(); return gson.toJson(this); */ return String.format("ProcedureElement: type=%s, concept=%s, " +"required=%s, id=%s, question=%s, figure=%s, audio=%s, answer=%s," +"action=%s", getType(), concept, bRequired, id, question, figure, audioPrompt, answer,action); } /** * Returns a View containing a set of buttons, each of which can be * used as a launch point for another activity. * * @see {@link #getAction()} for more on action String format * @return a View containing a list of action buttons */ public View getActions(Context c){ Log.d(TAG, "action=" + action); LinearLayout ll = new LinearLayout(c); ll.setOrientation(LinearLayout.VERTICAL); ll.setGravity(Gravity.CENTER); ll.setBackgroundColor(Color.CYAN); ll.setPadding(5, 0, 5, 0); ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); // Get the intent for(String intentStr: action.split(",")){ Log.d(TAG, intentStr); Button button = new Button(c); button.setTextColor(Color.BLUE); button.setHint("TOUCH TO CALL"); button.setHintTextColor(Color.CYAN); button.setText("Call Anbulance"); try { Intent buttonAction = Intent.parseUri(intentStr, Intent.URI_INTENT_SCHEME); button.setTag(buttonAction); button.setText(buttonAction.getStringExtra(Intent.EXTRA_TITLE)); button.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { Intent intent = (Intent) v.getTag(); startActivity(intent); }}); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } ll.addView(button, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); } return ll; } protected final Activity getActivity(){ return (Activity) getContext(); } protected final void startActivity(Intent intent){ Activity activity = getActivity(); Intent launcher = new Intent(getContext(), activity.getClass()); launcher.putExtra(Intent.EXTRA_INTENT, intent); launcher.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); getContext().startActivity(launcher); } public String getDefault(){ Log.i(TAG, "getDefault()"); return defaultValue; } public void setDefault(String defaultValue){ Log.i(TAG, "setDefault(String)"); this.defaultValue = defaultValue; } public boolean hasDefault(){ Log.i(TAG, "hasDefault()"); return !TextUtils.isEmpty(defaultValue); } /** * Creates the element from an XML procedure definition. * * @param id The unique identifier of this element within its procedure. * @param question The text that will be displayed to the user as a question * @param answer The result of data capture. * @param concept A required categorization of the type of data captured. * @param figure An optional figure to display to the user. * @param audio An optional audio prompt to play for the user. * @param node The source xml node. * @return A new element. * @throws ProcedureParseException if an error occurred while parsing * additional information from the Node */ public static ProcedureElement fromXML(String id, String question, String answer, String concept, String figure, String audio, Node node) throws ProcedureParseException { throw new UnsupportedOperationException(); } }
app/src/main/java/org/sana/android/procedure/ProcedureElement.java
package org.sana.android.procedure; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.Gallery; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import org.sana.R; import org.sana.android.media.AudioPlayer; import org.sana.android.media.EducationResource; import org.sana.android.util.SanaUtil; import org.w3c.dom.Node; import java.net.URISyntaxException; /** * A ProcedureElement is an item that can be placed on a page in a Sana * procedure. Typically there will only be one ProcedureElement per page, but * this style suggestion is not enforced, and users can make XML procedure * definitions that contain several ProcedureElements per page. * <p/> * A ProcedureElement, generally speaking, asks a question and may allow for an * answer. For example, a RadioElement poses a question and allows a user to * choose among response buttons. * * ProcedureElements are defined in XML and dynamically created from the XML in * Sana. * <p/> * <ul type="none"> * <li><b>Clinical Use </b> Defined by subclasses.</li> * <li><b>Collects </b> Defined by subclasses.</li> * </ul> * The <em>Collects</em> documentation should declare the format of any returned * answer strings * * @author Sana Development Team */ public abstract class ProcedureElement { public static String TAG = ProcedureElement.class.getSimpleName(); /** * An enumeration of the valid ProcedureElement types. * * @author Sana Development Team */ public static enum ElementType { /** Provides text display */ TEXT(""), /** Provides text capture. */ ENTRY(""), /** Provides exclusive option selector as a dropdown box. */ SELECT(""), /** An entry element for displaying/entering a patient identifier */ PATIENT_ID(""), /** A non-exclusive option selector as a list of checkboxes. */ MULTI_SELECT(""), /** An exclusive multi-option selector as a list of radio buttons */ RADIO(""), /** Provides capture of one or more images */ PICTURE("image.jpg"), /** Provides capture of a single audio resource. */ SOUND("sound.3gp"), /** Provides attachment of a binary file for upload */ BINARYFILE("binary.bin"), /** A marker for invalid elements */ INVALID(""), /** Provides capture of GPS coordinates */ GPS(""), /** Provides capture of a date */ DATE(""), /** Provides a viewable resource for patient education. */ EDUCATION_RESOURCE(""), /** Provides access to 3rd party tools for data capture where the data * is returned directly. */ PLUGIN(""), /** Provides access to 3rd party tools for data capture where the data * is not returned directly and must be manually entered by the user. */ ENTRY_PLUGIN(""), HIDDEN(""), AGE(""), TRUTH; private String filename; private ElementType(){ this(""); } private ElementType(String filename) { this.filename = filename; } /** * Returns the default filename for a given ElementType * @return */ public String getFilename() { return filename; } } protected String id; protected String question; protected String answer; protected String concept; protected String action = null; // Resource of a corresponding figure for this element. protected String figure; // Resource of a corresponding audio prompt for this element. protected String audioPrompt; // Whether a null answer is allowed private boolean bRequired = false; // Optional attributes - specific element types must implement as necessary protected String defaultValue = null; protected String defaultPrompt = null; private Procedure procedure; private Context cachedContext; private View cachedView; private AudioPlayer mAudioPlayer; private String helpText; /** * Constructs the view of this ProcedureElement * * @param c the current Context */ protected abstract View createView(Context c); void clearCachedView() { cachedView = null; } /** * Constructs a new Instance. * * @param id The unique identifier of this element within its procedure. * @param question The text that will be displayed to the user as a question * @param answer The result of data capture. * @param concept A required categorization of the type of data captured. * @param figure An optional figure to display to the user. * @param audioPrompt An optional audio prompt to play for the user. */ protected ProcedureElement(String id, String question, String answer, String concept, String figure, String audioPrompt) { this.id = id; this.question = question; this.answer = answer; this.concept = concept; this.figure = figure; this.audioPrompt = audioPrompt; } /** * A reference to the enclosing Procedure * @return A Procedure instance. */ protected Procedure getProcedure() { // set the ImageView bounds to match the Drawable's dimensions return procedure; } /** * Sets the enclosing procedure * @param procedure the new enclosing procedure. */ public void setProcedure(Procedure procedure) { this.procedure = procedure; } /** * Whether this element is considered active. * @return */ protected boolean isViewActive() { return !(cachedView == null); } /** * A cached Context. * @return The Context this element holds a reference to. */ protected Context getContext() { return cachedContext; } /** * A visible representation of this object. * @param c The Context which will be used in the View constructors for this * object's representation. * @return A new view of this object or cached view if it exists. */ public View toView(Context c) { if(cachedView == null || cachedContext != c) { cachedView = createView(c); cachedContext = c; } return cachedView; } /** * Returns the ElementType of this element as defined in the * ProcedureElement ElementType enum. */ public abstract ElementType getType(); /** * Gets the value of the answer attribute. * * @return A String representation of collected data. */ public String getAnswer(){ return answer; } /** * Set the value of the answer attribute as a String representation of * collected data. * * @param answer the new answer */ public void setAnswer(String answer){ this.answer = answer; } /** * Whether this element is considered required * @return */ public boolean isRequired() { return bRequired; } /** * Sets the required state of this element. * @param required The new required state. */ public void setRequired(boolean required) { this.bRequired = required; } /** * Help text associated with this element * @return An informative string. */ public String getHelpText() { return helpText; } /** * Sets the help text for this instance. * @param helpText the new help string. */ public void setHelpText(String helpText) { this.helpText = helpText; } public String getAction(){ return action; } /** * Whether this element is valid. * @return true if not required or required and answer is not empty * @throws ValidationError */ public boolean validate() throws ValidationError { if (bRequired && "".equals(getAnswer().trim())) { String msg = TextUtils.isEmpty(helpText)? getString(R.string.general_input_required): helpText; throw new ValidationError(msg); } return true; } /** * Tell the element's widget to refresh itself. */ public void refreshWidget() { } /** * Writes a string representation of this object to a StringBuilder. * Extending classes should override appendOptionalAttributes if they * require attributes beyond those defined in this class. * * @param sb the builder to write to. */ public void buildXML(StringBuilder sb){ sb.append("<Element "); sb.append("type=\"" + getType().name() + "\" "); sb.append("id=\"" + getId()+ "\" "); sb.append("question=\"" + getQuestion()+ "\" "); sb.append("answer=\"" + getAnswer()+ "\" "); sb.append("figure=\"" + getFigure()+ "\" "); sb.append("concept=\"" + getConcept()+ "\" "); sb.append("audio=\"" + getAudioPrompt()+ "\" "); sb.append("required=\"" + isRequired()+ "\" "); appendOptionalAttributes(sb); sb.append("/>\n"); } protected void appendOptionalAttributes(StringBuilder sb){ if(!TextUtils.isEmpty(action)) sb.append("action=\"" + action+ "\" "); if(hasDefault()) sb.append("default=\"" + getDefault()+ "\" "); return; } /** * Build the XML representation of this ProcedureElement. Should only use * this if you intend to use only the XML for this element. If you are * building the XML for this Procedure, then prefer buildXML with a * StringBuilder since String operations are slow. */ public String toXML() { StringBuilder sb = new StringBuilder(); buildXML(sb); return sb.toString(); } /** * Create an element from an XML element node of a procedure definition. * @param node a Node object containing a ProcedureElement representation */ public static ProcedureElement createElementfromXML(Node node) throws ProcedureParseException { //Log.i(TAG, "fromXML(" + node.getNodeName() + ")"); if(!node.getNodeName().equals("Element")) { throw new ProcedureParseException("Element got NodeName " + node.getNodeName()); } String questionStr = SanaUtil.getNodeAttributeOrDefault(node, "question", ""); String answerStr = SanaUtil.getNodeAttributeOrDefault(node, "answer", null); String typeStr = SanaUtil.getNodeAttributeOrDefault(node, "type", "INVALID"); String conceptStr = SanaUtil.getNodeAttributeOrDefault(node, "concept", ""); String idStr = SanaUtil.getNodeAttributeOrFail(node, "id", new ProcedureParseException("Element doesn't have id number")); String figureStr = SanaUtil.getNodeAttributeOrDefault(node, "figure", ""); String audioStr = SanaUtil.getNodeAttributeOrDefault(node, "audio", ""); ElementType etype = ElementType.valueOf(typeStr); ProcedureElement el = null; switch(etype) { case TEXT: el = TextElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case ENTRY: el = TextEntryElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case SELECT: el = SelectElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case MULTI_SELECT: el = MultiSelectElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case RADIO: el = RadioElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case PICTURE: el = PictureElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case SOUND: el = SoundElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case GPS: el = GpsElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case BINARYFILE: el = BinaryUploadElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case PATIENT_ID: el = PatientIdElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case DATE: el = DateElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case EDUCATION_RESOURCE: el = EducationResourceElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case PLUGIN: el = PluginElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case ENTRY_PLUGIN: el = PluginEntryElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case HIDDEN: el = HiddenElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case AGE: el = AgeElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case TRUTH: el = TruthElement.fromXML(idStr, questionStr, answerStr, conceptStr, figureStr, audioStr, node); break; case INVALID: default: throw new ProcedureParseException("Got invalid node type : " + etype); } if (el == null) { throw new ProcedureParseException("Failed to parse node with id " + idStr); } String helpStr = SanaUtil.getNodeAttributeOrDefault(node, "helpText", ""); el.setHelpText(helpStr); String requiredStr = SanaUtil.getNodeAttributeOrDefault(node, "required", "false"); if ("true".equals(requiredStr)) { el.setRequired(true); } else if ("false".equals(requiredStr)) { el.setRequired(false); } else { throw new ProcedureParseException("Argument to \'required\' "+ "attribute invalid for id " + idStr + ". Must be \'true\' or \'false\'"); } return el; } public static void parseOptionalAttributes(Node node, ProcedureElement el) throws ProcedureParseException { Log.i(TAG, "parseOptionalAttributes(Node,ProcedureElement)"); String attr = null; // action attr = SanaUtil.getNodeAttributeOrDefault(node, "action", ""); if(!TextUtils.isEmpty(attr)) el.action = new String(attr); // default attr = SanaUtil.getNodeAttributeOrDefault(node, "default", ""); el.setDefault(new String(attr)); // helpText attr = SanaUtil.getNodeAttributeOrDefault(node, "helpText", ""); el.setHelpText(new String(attr)); // required attr = SanaUtil.getNodeAttributeOrDefault(node, "required", "false"); if ("true".equals(attr)) { el.setRequired(true); } else if ("false".equals(attr)) { el.setRequired(false); } else { throw new ProcedureParseException("Argument to \'required\' " + "attribute invalid for id " + el.getId()+ ". Must be \'true\' or \'false\'"); } } /** @return The value of the id attribute */ public String getId() { return id; } /** @return Gets the identifier for any associated education resources */ public String mediaId(){ return EducationResource.toId(concept+question); } /** * @return the question string originally defined in the XML procedure * definition. */ public String getQuestion() { return question; } /** * @return the medical concept associated with this ProcedureElement */ public String getConcept() { return concept; } /** * @return the figure URL associated with this ProcedureElement */ public String getFigure() { return figure; } /** @return true if this instance has an audio prompt */ boolean hasAudioPrompt() { return !"".equals(audioPrompt); } /** plays this instance's audio prompt */ void playAudioPrompt() { if (mAudioPlayer != null) mAudioPlayer.play(); } /** @return the audioPrompt string */ public String getAudioPrompt() { return audioPrompt; } /** * Returns a localized String from the application package's default string * table. * * @param resId Resource Id for the string * @return */ public String getString(int resId){ return getContext().getString(resId); } /** * Appends another View object a view of this object to a new View . * @param c A valid Context. * @param v The view to append first. * @return A new View containing the parameter View and a View of this * object. */ public View encapsulateQuestion(Context c, View v) { // Add question view TextView textView = new TextView(c); textView.setSingleLine(false); textView.setGravity(Gravity.LEFT); String q = question.replace("\\n", "\n"); Log.d(TAG, "...show question id = " + getProcedure().idsShown()); if(getProcedure().idsShown() && !getType().equals(ElementType.TEXT)){ textView.setText(String.format("%s: %s", getId(), q)); }else{ textView.setText(q); } //textView.setGravity(Gravity.CENTER_HORIZONTAL); textView.setTextAppearance(c, android.R.style.TextAppearance_Large); View questionView = textView; questionView.setPadding(10,5,10,5); // Add image if provided ImageView imageView = null; //Set accompanying figure if(!TextUtils.isEmpty(figure)) { try{ String imagePath = c.getPackageName() + ":" + figure; Log.d(TAG, "Using figure: " + figure); int resID = c.getResources().getIdentifier(figure, null, null); Log.d(TAG, "Using figure id: " + resID); imageView = new ImageView(c); imageView.setImageResource(resID); imageView.setAdjustViewBounds(true); // set the ImageView bounds to match the Drawable's dimensions imageView.setLayoutParams(new Gallery.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); imageView.setPadding(10,10,10,10); } catch(Exception e){ Log.e(TAG, "Couldn't find resource figure " + e.toString()); } } // Add audio prompt if provided if (hasAudioPrompt()) { try { String resourcePath = c.getPackageName() + ":" + audioPrompt; int resID = c.getResources().getIdentifier(resourcePath, null, null); Log.i(TAG, "Looking up ID for resource: " + resourcePath + ", " + "got " + resID); if (resID != 0) { mAudioPlayer = new AudioPlayer(resID); View playerView = mAudioPlayer.createView(c); playerView.setLayoutParams(new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); LinearLayout audioPromptView = new LinearLayout(c); audioPromptView.setOrientation(LinearLayout.HORIZONTAL); audioPromptView.setLayoutParams(new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); audioPromptView.setGravity(Gravity.CENTER); // Insert the play button to the left of the current // question view. audioPromptView.addView(playerView); audioPromptView.addView(questionView); questionView = audioPromptView; } } catch (Exception e) { Log.e(TAG, "Couldn't find resource for audio prompt: " + e.toString()); } } //Log.d(TAG, "Loaded: " +this.toString()); LinearLayout ll = new LinearLayout(c); ll.setOrientation(LinearLayout.VERTICAL); //Add to layout ll.addView(questionView); if (imageView != null) ll.addView(imageView); // Add Buttons if provided if(!TextUtils.isEmpty(action)){ View actionView = getActions(c); actionView.setPadding(5,5,5,5); ll.addView(actionView); } else { //Log.w(TAG, "Empty action string!"); } if(v != null){ LinearLayout viewHolder = new LinearLayout(c); viewHolder.addView(v); viewHolder.setGravity(Gravity.CENTER_HORIZONTAL); ll.addView(viewHolder, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); } ll.setGravity(Gravity.CENTER); ll.setPadding(5, 0, 5, 0); ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); return ll; } @Override public String toString(){ /* Gson gson = new Gson(); return gson.toJson(this); */ return String.format("ProcedureElement: type=%s, concept=%s, " +"required=%s, id=%s, question=%s, figure=%s, audio=%s, answer=%s," +"action=%s", getType(), concept, bRequired, id, question, figure, audioPrompt, answer,action); } /** * Returns a View containing a set of buttons, each of which can be * used as a launch point for another activity. * * @see {@link #getAction()} for more on action String format * @return a View containing a list of action buttons */ public View getActions(Context c){ Log.d(TAG, "action=" + action); LinearLayout ll = new LinearLayout(c); ll.setOrientation(LinearLayout.VERTICAL); ll.setGravity(Gravity.CENTER); ll.setPadding(5, 0, 5, 0); ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); // Get the intent for(String intentStr: action.split(",")){ Log.d(TAG, intentStr); Button button = new Button(c); button.setText("????"); try { Intent buttonAction = Intent.parseUri(intentStr, Intent.URI_INTENT_SCHEME); button.setTag(buttonAction); button.setText(buttonAction.getStringExtra(Intent.EXTRA_TITLE)); button.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { Intent intent = (Intent) v.getTag(); startActivity(intent); }}); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } ll.addView(button, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); } return ll; } protected final Activity getActivity(){ return (Activity) getContext(); } protected final void startActivity(Intent intent){ Activity activity = getActivity(); Intent launcher = new Intent(getContext(), activity.getClass()); launcher.putExtra(Intent.EXTRA_INTENT, intent); launcher.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); getContext().startActivity(launcher); } public String getDefault(){ Log.i(TAG, "getDefault()"); return defaultValue; } public void setDefault(String defaultValue){ Log.i(TAG, "setDefault(String)"); this.defaultValue = defaultValue; } public boolean hasDefault(){ Log.i(TAG, "hasDefault()"); return !TextUtils.isEmpty(defaultValue); } /** * Creates the element from an XML procedure definition. * * @param id The unique identifier of this element within its procedure. * @param question The text that will be displayed to the user as a question * @param answer The result of data capture. * @param concept A required categorization of the type of data captured. * @param figure An optional figure to display to the user. * @param audio An optional audio prompt to play for the user. * @param node The source xml node. * @return A new element. * @throws ProcedureParseException if an error occurred while parsing * additional information from the Node */ public static ProcedureElement fromXML(String id, String question, String answer, String concept, String figure, String audio, Node node) throws ProcedureParseException { throw new UnsupportedOperationException(); } }
UI styling for Call button
app/src/main/java/org/sana/android/procedure/ProcedureElement.java
UI styling for Call button
<ide><path>pp/src/main/java/org/sana/android/procedure/ProcedureElement.java <ide> import android.content.Context; <ide> import android.content.Intent; <ide> import android.graphics.Color; <add>import android.graphics.drawable.Animatable; <ide> import android.text.TextUtils; <ide> import android.util.Log; <ide> import android.view.Gravity; <ide> import android.view.View; <ide> import android.view.ViewGroup.LayoutParams; <add>import android.view.animation.Animation; <ide> import android.widget.Button; <ide> import android.widget.Gallery; <ide> import android.widget.ImageView; <ide> import org.sana.android.media.EducationResource; <ide> import org.sana.android.util.SanaUtil; <ide> import org.w3c.dom.Node; <add>import org.w3c.dom.Text; <ide> <ide> import java.net.URISyntaxException; <ide> <ide> LinearLayout ll = new LinearLayout(c); <ide> ll.setOrientation(LinearLayout.VERTICAL); <ide> ll.setGravity(Gravity.CENTER); <add> ll.setBackgroundColor(Color.CYAN); <ide> ll.setPadding(5, 0, 5, 0); <ide> ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, <ide> LayoutParams.WRAP_CONTENT)); <ide> for(String intentStr: action.split(",")){ <ide> Log.d(TAG, intentStr); <ide> Button button = new Button(c); <del> button.setText("????"); <add> button.setTextColor(Color.BLUE); <add> button.setHint("TOUCH TO CALL"); <add> button.setHintTextColor(Color.CYAN); <add> button.setText("Call Anbulance"); <ide> try { <ide> Intent buttonAction = Intent.parseUri(intentStr, Intent.URI_INTENT_SCHEME); <ide> button.setTag(buttonAction);
Java
apache-2.0
72759cc75e1342fc3d836bd79f6c699fd8c330f1
0
kalaspuffar/pdfbox,apache/pdfbox,kalaspuffar/pdfbox,apache/pdfbox
/* * 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.pdfbox.cos; import static org.junit.Assert.fail; import java.util.Calendar; import org.apache.pdfbox.pdmodel.font.encoding.Encoding; import org.junit.Test; public class UnmodifiableCOSDictionaryTest { @Test public void testUnmodifiableCOSDictionary() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.clear(); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.removeItem(COSName.A); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.addAll(new COSDictionary()); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setFlag(COSName.A, 0, true); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setNeedToBeUpdated(true); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setNeedToBeUpdated(true); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetItem() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setItem(COSName.A, COSName.A); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setItem(COSName.A, Encoding.getInstance(COSName.STANDARD_ENCODING)); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setItem("A", COSName.A); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setItem("A", Encoding.getInstance(COSName.STANDARD_ENCODING)); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetBoolean() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setBoolean(COSName.A, true); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setBoolean("A", true); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetName() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setName(COSName.A, "A"); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setName("A", "A"); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetDate() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setDate(COSName.A, Calendar.getInstance()); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setDate("A", Calendar.getInstance()); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetEmbeddedDate() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setEmbeddedDate("Embedded", COSName.A, Calendar.getInstance()); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setEmbeddedDate("Embedded", "A", Calendar.getInstance()); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetString() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setString(COSName.A, "A"); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setString("A", "A"); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetEmbeddedString() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setEmbeddedString("Embedded", COSName.A, "A"); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setEmbeddedString("Embedded", "A", "A"); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetInt() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setInt(COSName.A, 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setInt("A", 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetEmbeddedInt() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setEmbeddedInt("Embedded", COSName.A, 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setEmbeddedInt("Embedded", "A", 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetLong() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setLong(COSName.A, 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setLong("A", 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetFloat() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setFloat(COSName.A, 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setFloat("A", 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } }
pdfbox/src/test/java/org/apache/pdfbox/cos/UnmodifiableCOSDictionaryTest.java
/* * 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.pdfbox.cos; import static org.junit.Assert.fail; import java.util.Calendar; import java.util.function.BiConsumer; import org.apache.pdfbox.pdmodel.common.COSObjectable; import org.apache.pdfbox.pdmodel.font.encoding.Encoding; import org.junit.Test; public class UnmodifiableCOSDictionaryTest { @Test public void testUnmodifiableCOSDictionary() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.clear(); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.removeItem(COSName.A); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.addAll(new COSDictionary()); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setFlag(COSName.A, 0, true); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setNeedToBeUpdated(true); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setNeedToBeUpdated(true); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetItem() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setItem(COSName.A, COSName.A); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setItem(COSName.A, Encoding.getInstance(COSName.STANDARD_ENCODING)); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setItem("A", COSName.A); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setItem("A", Encoding.getInstance(COSName.STANDARD_ENCODING)); fail("An UnsupportedOperationException should have been thrown"); } catch(UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetBoolean() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setBoolean(COSName.A, true); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setBoolean("A", true); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetName() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setName(COSName.A, "A"); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setName("A", "A"); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetDate() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setDate(COSName.A, Calendar.getInstance()); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setDate("A", Calendar.getInstance()); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetEmbeddedDate() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setEmbeddedDate("Embedded", COSName.A, Calendar.getInstance()); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setEmbeddedDate("Embedded", "A", Calendar.getInstance()); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetString() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setString(COSName.A, "A"); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setString("A", "A"); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetEmbeddedString() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setEmbeddedString("Embedded", COSName.A, "A"); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setEmbeddedString("Embedded", "A", "A"); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetInt() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setInt(COSName.A, 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setInt("A", 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetEmbeddedInt() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setEmbeddedInt("Embedded", COSName.A, 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setEmbeddedInt("Embedded", "A", 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetLong() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setLong(COSName.A, 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setLong("A", 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } @Test public void testSetFloat() { COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary(); try { unmodifiableCOSDictionary.setFloat(COSName.A, 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } try { unmodifiableCOSDictionary.setFloat("A", 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException exception) { // nothing to do } } }
PDFBOX-4892: remove unused imports git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1882837 13f79535-47bb-0310-9956-ffa450edef68
pdfbox/src/test/java/org/apache/pdfbox/cos/UnmodifiableCOSDictionaryTest.java
PDFBOX-4892: remove unused imports
<ide><path>dfbox/src/test/java/org/apache/pdfbox/cos/UnmodifiableCOSDictionaryTest.java <ide> import static org.junit.Assert.fail; <ide> <ide> import java.util.Calendar; <del>import java.util.function.BiConsumer; <del> <del>import org.apache.pdfbox.pdmodel.common.COSObjectable; <add> <ide> import org.apache.pdfbox.pdmodel.font.encoding.Encoding; <ide> import org.junit.Test; <ide>
Java
mit
02cd39ae4e52d530e2ccb9883bb5b85053b62126
0
YiiGuxing/TranslationPlugin,YiiGuxing/TranslationPlugin
package cn.yiiguxing.plugin.translate.action; import cn.yiiguxing.plugin.translate.TranslationUiManager; import cn.yiiguxing.plugin.translate.Utils; import com.intellij.codeInsight.documentation.DocumentationManager; import com.intellij.codeInsight.hint.HintManagerImpl; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopup; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.text.JTextComponent; /** * 文本组件(如快速文档、提示气泡、输入框……)翻译动作 */ public class TranslateTextComponentAction extends AnAction implements DumbAware, HintManagerImpl.ActionToIgnore { public TranslateTextComponentAction() { setEnabledInModalContext(true); } @Nullable public static String getSelectedText(@NotNull AnActionEvent event) { final DataContext dataContext = event.getDataContext(); String selectedQuickDocText = DocumentationManager.SELECTED_QUICK_DOC_TEXT.getData(dataContext); if (selectedQuickDocText != null) { return selectedQuickDocText; } final Editor editor = CommonDataKeys.EDITOR.getData(dataContext); if (editor != null) { return editor.getSelectionModel().getSelectedText(); } final Object data = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext); if (data instanceof JTextComponent) { return ((JTextComponent) data).getSelectedText(); } return null; } @Override public void update(AnActionEvent e) { final String selected = getSelectedText(e); e.getPresentation().setEnabledAndVisible(!Utils.isEmptyOrBlankString(Utils.splitWord(selected))); } @Override public void actionPerformed(AnActionEvent e) { if (ApplicationManager.getApplication().isHeadlessEnvironment()) { return; } final String selected = Utils.splitWord(getSelectedText(e)); if (Utils.isEmptyOrBlankString(selected)) { return; } final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext()); final JBPopup docInfoHint = project == null ? null : DocumentationManager.getInstance(project).getDocInfoHint(); if (docInfoHint != null) { docInfoHint.cancel(); } TranslationUiManager.getInstance().showTranslationDialog(e.getProject()).query(selected); } }
src/cn/yiiguxing/plugin/translate/action/TranslateTextComponentAction.java
package cn.yiiguxing.plugin.translate.action; import cn.yiiguxing.plugin.translate.TranslationUiManager; import cn.yiiguxing.plugin.translate.Utils; import com.intellij.codeInsight.documentation.DocumentationManager; import com.intellij.codeInsight.hint.HintManagerImpl; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.textarea.TextComponentEditorImpl; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopup; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.text.JTextComponent; /** * 文本组件(如快速文档、提示气泡、输入框……)翻译动作 */ public class TranslateTextComponentAction extends AnAction implements DumbAware, HintManagerImpl.ActionToIgnore { public TranslateTextComponentAction() { setEnabledInModalContext(true); } @Nullable public static Editor getEditorFromContext(@NotNull DataContext dataContext) { final Editor editor = CommonDataKeys.EDITOR.getData(dataContext); if (editor != null) return editor; final Object data = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext); if (data instanceof JTextComponent) { return new TextComponentEditorImpl(CommonDataKeys.PROJECT.getData(dataContext), (JTextComponent) data); } return null; } @Override public void update(AnActionEvent e) { final String selected = getSelectedText(e); e.getPresentation().setEnabledAndVisible(!Utils.isEmptyOrBlankString(Utils.splitWord(selected))); } @Nullable private String getSelectedText(AnActionEvent e) { String selected = e.getData(DocumentationManager.SELECTED_QUICK_DOC_TEXT); if (selected == null) { final Editor editor = getEditorFromContext(e.getDataContext()); if (editor != null) { selected = editor.getSelectionModel().getSelectedText(); } } return selected; } @Override public void actionPerformed(AnActionEvent e) { if (ApplicationManager.getApplication().isHeadlessEnvironment()) { return; } final String selected = Utils.splitWord(getSelectedText(e)); if (Utils.isEmptyOrBlankString(selected)) { return; } final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext()); final JBPopup docInfoHint = project == null ? null : DocumentationManager.getInstance(project).getDocInfoHint(); if (docInfoHint != null) { docInfoHint.cancel(); } TranslationUiManager.getInstance().showTranslationDialog(e.getProject()).query(selected); } }
:ambulance: 低版本兼容
src/cn/yiiguxing/plugin/translate/action/TranslateTextComponentAction.java
:ambulance: 低版本兼容
<ide><path>rc/cn/yiiguxing/plugin/translate/action/TranslateTextComponentAction.java <ide> import com.intellij.openapi.actionSystem.*; <ide> import com.intellij.openapi.application.ApplicationManager; <ide> import com.intellij.openapi.editor.Editor; <del>import com.intellij.openapi.editor.textarea.TextComponentEditorImpl; <ide> import com.intellij.openapi.project.DumbAware; <ide> import com.intellij.openapi.project.Project; <ide> import com.intellij.openapi.ui.popup.JBPopup; <ide> } <ide> <ide> @Nullable <del> public static Editor getEditorFromContext(@NotNull DataContext dataContext) { <add> public static String getSelectedText(@NotNull AnActionEvent event) { <add> final DataContext dataContext = event.getDataContext(); <add> <add> String selectedQuickDocText = DocumentationManager.SELECTED_QUICK_DOC_TEXT.getData(dataContext); <add> if (selectedQuickDocText != null) { <add> return selectedQuickDocText; <add> } <add> <ide> final Editor editor = CommonDataKeys.EDITOR.getData(dataContext); <del> if (editor != null) return editor; <add> if (editor != null) { <add> return editor.getSelectionModel().getSelectedText(); <add> } <ide> <ide> final Object data = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext); <ide> if (data instanceof JTextComponent) { <del> return new TextComponentEditorImpl(CommonDataKeys.PROJECT.getData(dataContext), (JTextComponent) data); <add> return ((JTextComponent) data).getSelectedText(); <ide> } <ide> <ide> return null; <ide> public void update(AnActionEvent e) { <ide> final String selected = getSelectedText(e); <ide> e.getPresentation().setEnabledAndVisible(!Utils.isEmptyOrBlankString(Utils.splitWord(selected))); <del> } <del> <del> @Nullable <del> private String getSelectedText(AnActionEvent e) { <del> String selected = e.getData(DocumentationManager.SELECTED_QUICK_DOC_TEXT); <del> if (selected == null) { <del> final Editor editor = getEditorFromContext(e.getDataContext()); <del> if (editor != null) { <del> selected = editor.getSelectionModel().getSelectedText(); <del> } <del> } <del> <del> return selected; <ide> } <ide> <ide> @Override
Java
mit
0ff586badf276c575e5215d0020e37aff9b1bc78
0
ronnyfriedland/Knowledgebase-2.0,ronnyfriedland/Knowledgebase-2.0,ronnyfriedland/Knowledgebase-2.0,ronnyfriedland/Knowledgebase-2.0
package de.ronnyfriedland.knowledgebase.entity; import java.util.Collections; import org.junit.Assert; import org.junit.Test; import de.ronnyfriedland.knowledgebase.repository.jcr.JCRTextDocument; /** * @author ronnyfriedland */ public class DocumentTest { @Test public void testConstructor() throws Exception { Document<String> subject = new Document<>("key", "header", "message", false, "tag1", "tag2"); Assert.assertNotNull(subject); Assert.assertEquals("key", subject.getKey()); Assert.assertEquals("header", subject.getHeader()); Assert.assertEquals("message", subject.getMessage()); Assert.assertArrayEquals(new String[] { "tag1", "tag2" }, subject.getTags()); subject = new Document<>("key", "header", "message", false); Assert.assertArrayEquals(new String[0], subject.getTags()); } @Test public void testFromJcrDocument() throws Exception { Document<String> subject = new JCRTextDocument("path", "header", "message", false, Collections.singletonList(" tag1 withwithspaces ")).toDocument(); Assert.assertNotNull(subject); Assert.assertNotNull(subject.getKey()); Assert.assertEquals("path", subject.getKey()); Assert.assertNotNull(subject.getHeader()); Assert.assertEquals("header", subject.getHeader()); Assert.assertNotNull(subject.getMessage()); Assert.assertEquals("message", subject.getMessage()); Assert.assertNotNull(subject.getTags()); Assert.assertArrayEquals(new String[] { "tag1 withwithspaces" }, subject.getTags()); // trimmed tags } }
src/test/java/de/ronnyfriedland/knowledgebase/entity/DocumentTest.java
package de.ronnyfriedland.knowledgebase.entity; import java.util.Collections; import org.junit.Assert; import org.junit.Test; import de.ronnyfriedland.knowledgebase.repository.jcr.JCRTextDocument; /** * @author ronnyfriedland */ public class DocumentTest { @Test public void testConstructor() throws Exception { Document<String> subject = new Document<>("key", "header", "message", false, "tag1", "tag2"); Assert.assertNotNull(subject); Assert.assertEquals("key", subject.getKey()); Assert.assertEquals("header", subject.getHeader()); Assert.assertEquals("message", subject.getMessage()); Assert.assertArrayEquals(new String[] { "tag1", "tag2" }, subject.getTags()); subject = new Document<>("key", "header", "message", false); Assert.assertArrayEquals(new String[0], subject.getTags()); } @Test public void testFromJcrDocument() throws Exception { Document<String> subject = new JCRTextDocument("path", "header", "message", false, Collections.singletonList(" tag1 withwithspaces ")).toDocument(); Assert.assertNotNull(subject); Assert.assertNotNull(subject.getKey()); Assert.assertEquals("/path", subject.getKey()); Assert.assertNotNull(subject.getHeader()); Assert.assertEquals("header", subject.getHeader()); Assert.assertNotNull(subject.getMessage()); Assert.assertEquals("message", subject.getMessage()); Assert.assertNotNull(subject.getTags()); Assert.assertArrayEquals(new String[] { "tag1 withwithspaces" }, subject.getTags()); // trimmed tags } }
fix test
src/test/java/de/ronnyfriedland/knowledgebase/entity/DocumentTest.java
fix test
<ide><path>rc/test/java/de/ronnyfriedland/knowledgebase/entity/DocumentTest.java <ide> Collections.singletonList(" tag1 withwithspaces ")).toDocument(); <ide> Assert.assertNotNull(subject); <ide> Assert.assertNotNull(subject.getKey()); <del> Assert.assertEquals("/path", subject.getKey()); <add> Assert.assertEquals("path", subject.getKey()); <ide> Assert.assertNotNull(subject.getHeader()); <ide> Assert.assertEquals("header", subject.getHeader()); <ide> Assert.assertNotNull(subject.getMessage());
Java
apache-2.0
f4db45f608adcfca25aa678f5fb643a8e72e5fcb
0
antonio-fasolato/jfmigrate
package net.fasolato.jfmigrate.internal; import net.fasolato.jfmigrate.JFMigrationClass; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class ReflectionHelper { private static Logger log = LogManager.getLogger(ReflectionHelper.class); public static List<JFMigrationClass> getAllMigrations(String pkg) throws Exception { if (pkg == null || pkg.trim().length() == 0) { throw new Exception("Null or empty package passed"); } List<String> classNames = listClassesInPackage(pkg); List<JFMigrationClass> migrations = new ArrayList<JFMigrationClass>(); for (String n : classNames) { Class<?> c = Class.forName((pkg + "." + n).replaceAll("/", "")); if (!JFMigrationClass.class.isAssignableFrom(c)) { log.debug("class {} does not implement IMigration. Class is ignored", c.getSimpleName()); } else { log.debug("class {} implements IMigration. Class is added as a migration", c.getSimpleName()); migrations.add((JFMigrationClass) c.newInstance()); } } return migrations; } // Inspiration and code taken from https://stackoverflow.com/a/7461653 public static List<String> listClassesInPackage(String packageName) throws IOException, URISyntaxException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL url; List<String> toReturn = new ArrayList<String>(); packageName = packageName.replaceAll("\\.", "/"); url = cl.getResource(packageName); if (url.getProtocol().equals("jar")) { //Jar files String jarFile = URLDecoder.decode(url.getFile(), "UTF-8"); String fileName = jarFile.substring(5, jarFile.indexOf("!")); JarFile jf = new JarFile(fileName); Enumeration<JarEntry> entries = jf.entries(); while (entries.hasMoreElements()) { JarEntry jar = entries.nextElement(); String entryName = jar.getName(); if (entryName.startsWith(packageName) && entryName.length() > packageName.length() + 5) { entryName = entryName.substring(packageName.length(), entryName.lastIndexOf('.')); toReturn.add(entryName); } } } else { //class files File dir = new File(new URI(url.toString()).getPath()); for (File f : dir.listFiles()) { if (f.isFile()) { toReturn.add(f.getName().substring(0, f.getName().lastIndexOf('.'))); } } } return toReturn; } }
JFMigrate/src/main/java/net/fasolato/jfmigrate/internal/ReflectionHelper.java
package net.fasolato.jfmigrate.internal; import net.fasolato.jfmigrate.JFMigrationClass; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class ReflectionHelper { private static Logger log = LogManager.getLogger(ReflectionHelper.class); public static List<JFMigrationClass> getAllMigrations(String pkg) throws Exception { if (pkg == null || pkg.trim().length() == 0) { throw new Exception("Null or empty package passed"); } List<String> classNames = listClassesInPackage(pkg); List<JFMigrationClass> migrations = new ArrayList<JFMigrationClass>(); for (String n : classNames) { Class<?> c = Class.forName(pkg + "." + n); if (!JFMigrationClass.class.isAssignableFrom(c)) { log.debug("class {} does not implement IMigration. Class is ignored", c.getSimpleName()); } else { log.debug("class {} implements IMigration. Class is added as a migration", c.getSimpleName()); migrations.add((JFMigrationClass) c.newInstance()); } } return migrations; } // Inspiration and code taken from https://stackoverflow.com/a/7461653 public static List<String> listClassesInPackage(String packageName) throws IOException, URISyntaxException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL url; List<String> toReturn = new ArrayList<String>(); packageName = packageName.replaceAll("\\.", "/"); url = cl.getResource(packageName); if (url.getProtocol().equals("jar")) { //Jar files String jarFile = URLDecoder.decode(url.getFile(), "UTF-8"); String fileName = jarFile.substring(5, jarFile.indexOf("!")); JarFile jf = new JarFile(fileName); Enumeration<JarEntry> entries = jf.entries(); while (entries.hasMoreElements()) { JarEntry jar = entries.nextElement(); String entryName = jar.getName(); if (entryName.startsWith(packageName) && entryName.length() > packageName.length() + 5) { entryName = entryName.substring(packageName.length(), entryName.lastIndexOf('.')); toReturn.add(entryName); } } } else { //class files File dir = new File(new URI(url.toString()).getPath()); for (File f : dir.listFiles()) { if (f.isFile()) { toReturn.add(f.getName().substring(0, f.getName().lastIndexOf('.'))); } } } return toReturn; } }
Fixed an error reading classes names
JFMigrate/src/main/java/net/fasolato/jfmigrate/internal/ReflectionHelper.java
Fixed an error reading classes names
<ide><path>FMigrate/src/main/java/net/fasolato/jfmigrate/internal/ReflectionHelper.java <ide> <ide> List<JFMigrationClass> migrations = new ArrayList<JFMigrationClass>(); <ide> for (String n : classNames) { <del> Class<?> c = Class.forName(pkg + "." + n); <add> Class<?> c = Class.forName((pkg + "." + n).replaceAll("/", "")); <ide> if (!JFMigrationClass.class.isAssignableFrom(c)) { <ide> log.debug("class {} does not implement IMigration. Class is ignored", c.getSimpleName()); <ide> } else {
JavaScript
mit
4c56fce5c4c953d54ce621fb8b0382baa224e422
0
vladikoff/p,rkatic/p,vladikoff/p,rkatic/p
(function(){ "use strict"; var opt_tracing = typeof TRACE_FUNCTIONS !== "undefined"; if ( typeof P === "undefined" ) { global.P = require(opt_tracing ? "./p" : "../p"); global.expect = require("expect.js"); //require("mocha"); } if ( opt_tracing ) { TRACE_FUNCTIONS.stopAdding(); beforeEach(function() { TRACE_FUNCTIONS.optimize(); }); afterEach(function() { TRACE_FUNCTIONS.optimize(); }); } var isNodeJS = typeof process === "object" && process && ({}).toString.call(process) === "[object process]"; function fail() { expect(true).to.be(false); } function thenableSyncFulfillment( value ) { return { then: function( cb, eb ) { cb( value ); } }; } function thenableSyncRejection( reason ) { return { then: function( cb, eb ) { eb( reason ); } }; } function thenableFulfillment( value ) { return { then: function( cb, eb ) { setTimeout(function() { cb( value ); }, 0) } }; } function thenableRejection( reason ) { return { then: function( cb, eb ) { setTimeout(function() { eb( reason ); }, 0) } }; } var VALUES = ["", true, false, 0, 1, 2, -1, -2, {}, [], {x: 1}, [1,2,3], null, void 0, new Error()]; var FULLFILMENTS = VALUES.concat( VALUES.map( P ), VALUES.map( thenableFulfillment ), VALUES.map( thenableSyncFulfillment ) ); var REJECTIONS = [].concat( VALUES.map( P.reject ), VALUES.map( thenableRejection ), VALUES.map( thenableSyncRejection ) ); var FULLFILMENTS_AND_REJECTIONS = FULLFILMENTS.concat( REJECTIONS ); function map( array, f ) { var array2 = new Array(array.length|0); for ( var i = 0, l = array.length; i < l; ++i ) { if ( i in array ) { array2[i] = f( array[i], i, array ); } } return array2; } function allValues( func ) { return P.all( map(VALUES, func) ); } describe("P function", function() { it("should return a promise", function() { var Promise = P().constructor; expect( Promise.constructor.name === "Promise" || Promise.toString().lastIndexOf("function Promise", 0) === 0 ).to.be(true); map(FULLFILMENTS_AND_REJECTIONS, function( value ) { expect( P(value) instanceof Promise ).to.be(true); }); }); it("should return input itself if it is a promise", function() { var p = P(); expect( P(p) ).to.be( p ); }); it("should fulfill with input if not a promise", function() { return allValues(function( value ) { return P( value ).then(function( fulfilledValue ) { expect( fulfilledValue ).to.be( value ); }); }); }); }); describe("inspect", function() { it("on fulfillment", function() { return allValues(function( value ) { var p = P( value ); return p.then(function() { expect( p.inspect() ).to.be.eql( {state: "fulfilled", value: value} ); }); }); }); it("on rejection", function() { return allValues(function( reason ) { var d = P.defer(); var p = d.promise; expect( p.inspect() ).to.be.eql( {state: "pending"} ); d.reject( reason ); return p.then( fail, function() { expect( p.inspect() ).to.be.eql( {state: "rejected", reason: reason} ); }); }); }); }); describe("reject", function() { it("returns a rejected promise", function() { return allValues(function( reason ) { return P.reject( reason ).then( fail, function( rejectedReason ) { expect( rejectedReason ).to.be( reason ); }); }); }); }); function deep( func ) { var d = P.defer(); var p = d.promise; var n = 10000; while ( n-- ) { p = func([ p ]); } d.promise = p; return d; } describe("all", function() { it("resolves when passed an empty array", function() { return P.all([]); }); it("resolves when passed an array", function() { var toResolve = P.defer(); var array = VALUES.concat( toResolve.promise ); var array2 = array.slice(); array2[ array2.length - 1 ] = 12; var promise = P.all( array ); toResolve.resolve(12); return promise.then(function( values ) { expect( values ).to.be.eql( array2 ); }); }); it("rejects if any consituent promise is rejectd", function() { var toReject = P.defer(); var theReason = new Error(); toReject.reject( theReason ); var array = FULLFILMENTS.concat( toReject.promise ) return P.all( array ) .then( fail, function( reason ) { expect( reason ).to.be( theReason ); }) .then(function() { var toRejectLater = P.defer(); var array = FULLFILMENTS.concat( toRejectLater.promise ); var promise = P.all( array ); toRejectLater.reject( theReason ); return promise; }) .then( fail, function( reason ) { expect( reason ).to.be( theReason ); }); }); it("should resolve on deep resolved promise", function() { var d = deep( P.all ); d.resolve( 1 ); return d.promise; }); it("should reject on deep rejected promise", function() { var d = deep( P.all ); d.reject( 7 ); return d.promise.then(fail, function( reason ) { expect( reason ).to.be( 7 ); }); }); }); describe("allSettled", function() { it("resolves when passed an empty array", function() { return P.allSettled([]); }); it("resolves when passed an array", function() { var array = FULLFILMENTS_AND_REJECTIONS; var promise = P.allSettled( array ); return promise.then(function( settled ) { for ( var i = 0; i < settled.length; ++i ) { var expectedValue = VALUES[ i % VALUES.length ]; if ( i < FULLFILMENTS.length ) { expect( settled[i] ).to.be.eql( {state: "fulfilled", value: expectedValue} ); } else { expect( settled[i] ).to.be.eql( {state: "rejected", reason: expectedValue} ); } } }); }); it("should resolve on deep resolved promise", function() { var d = deep( P.allSettled ); d.resolve( 1 ); return d.promise; }); it("should resolve on deep rejected promise", function() { var d = deep( P.allSettled ); d.reject( new Error("foo") ); return d.promise; }); }); describe("spread", function() { it("spreads values across arguments", function() { return P([1, P(2), 3]).spread(function( one, two, three ) { expect( one ).to.be( 1 ); expect( two ).to.be( 2 ); expect( three ).to.be( 3 ); }); }); it("should call the errback in case of a rejected promise", function() { var toReject = P.defer(); var theReason = new Error(); toReject.reject( theReason ); return P([ 1, P(2), toReject.promise]).spread( fail, function( reason ) { expect( reason ).to.be( theReason ); } ); }); }); describe("done", function() { afterEach(function() { P.onerror = null; }); // TODO: cover other cases too! describe("when the promise is rejected", function() { describe("and there is no errback", function() { it("should throw the reason in a next turn", function( done ) { var turn = 0; var toReject = P.defer(); toReject.reject("foo"); var promise = toReject.promise; expect( promise.done() ).to.be( undefined ); P.onerror = function( error ) { expect( turn ).to.be( 1 ); expect( error ).to.be("foo"); done(); }; ++turn; }); }); }); }); describe("fin", function() { describe("when the promise is fulfilled", function() { it("should call the callback and fulfill with the original value", function() { var called = false; return P("foo") .fin(function() { called = true; return "boo"; }) .then(function( value ) { expect( called ).to.be( true ); expect( value ).to.be("foo"); }); }); describe("when the callback returns a promise", function() { describe("that is fulfilled", function() { it("should fulfill with the original value after the promise is settled", function() { var delayed = P("boo").delay(50); return P("foo") .fin(function() { return delayed; }) .then(function( value ) { expect( delayed.inspect() ).to.be.eql({ state: "fulfilled", value: "boo" }); expect( value ).to.be("foo"); }); }) }); describe("that is rejected", function() { it("should reject with this new reason", function() { var theError = new Error("boo"); return P("foo") .fin(function() { return P.reject( theError ); }) .then(fail, function( reason ) { expect( reason ).to.be( theError ); }); }); }); }); describe("when the callback throws an exception", function() { it("should reject with this new exception", function() { var theError = new Error("boo"); return P("foo") .fin(function() { throw theError; }) .then(fail, function( reason ) { expect( reason ).to.be( theError ); }); }); }); }); describe("when the promise is rejected", function () { var theError = new Error("nooo"); it("should call the callback and reject with the original reason", function() { var called = false; return P.reject( theError ) .fin(function() { called = true; return "boo"; }) .then(fail, function( reason ) { expect( called ).to.be( true ); expect( reason ).to.be( theError ); }); }); describe("when the callback returns a promise", function() { describe("that is fulfilled", function() { it("should reject with the original reason after the promise is settled", function() { var delayed = P("boo").delay(50); return P.reject( theError ) .fin(function() { return delayed; }) .then(fail, function( reason ) { expect( delayed.inspect() ).to.be.eql({ state: "fulfilled", value: "boo" }); expect( reason ).to.be( theError ); }); }) }); describe("that is rejected", function() { it("should reject with this new reason", function() { return P.reject( new Error("boo") ) .fin(function() { return P.reject( theError ); }) .then(fail, function( reason ) { expect( reason ).to.be( theError ); }); }); }); }); describe("when the callback throws an exception", function() { it("should reject with this new exception", function() { var theError = new Error("boo"); return P.reject( new Error("boo") ) .fin(function() { throw theError; }) .then(fail, function( reason ) { expect( reason ).to.be( theError ); }); }); }); }); }); describe("timeout", function() { // This part is based on the respective part of the Q spec. it("should do nothing if the promise fulfills quickly", function() { return P().delay( 10 ).timeout( 100 ); }); it("should do nothing if the promise rejects quickly", function() { var error = new Error(); return P().delay( 10 ) .then(function() { throw error; }) .timeout( 100 ) .then( fail, function( reason ) { expect( reason ).to.be( error ); }); }); it("should reject within a timeout error if the promise is too slow", function() { return P().delay( 100 ) .timeout( 10 ) .then( fail, function( reason ) { expect( reason.message ).to.match(/time/i); }); }); it("should reject with a custom timeout message if the promise is too slow", function() { return P().delay( 100 ) .timeout(10, "custom") .then( fail, function( reason ) { expect( reason.message ).to.match(/custom/i); }); }); }); describe("delay", function() { // This part is based on the respective part of the Q spec. it("should dealy fulfillment", function() { var promise = P(1).delay( 50 ); setTimeout(function() { expect( promise.inspect().state ).to.be("pending"); }, 30); return promise; }); it("should not dealy rejection", function() { var d = P.defer(); d.reject(1); var promise = d.promise.delay( 50 ); setTimeout(function() { expect( promise.inspect().state ).to.be("rejected"); }, 30); return promise.then( fail, function(){} ); }); it("should delay after fulfillment", function() { var p1 = P("foo").delay( 30 ); var p2 = p1.delay( 30 ); setTimeout(function() { expect( p1.inspect().state ).to.be("fulfilled"); expect( p2.inspect().state ).to.be("pending"); }, 45); return p2.then(function( value ) { expect( value ).to.be("foo"); }); }); }); describe("nodeify", function() { it("calls back with a resolution", function( done ) { P( 7 ).nodeify(function( error, value ) { expect( error ).to.be( null ); expect( value ).to.be( 7 ); done(); }); }); it("calls back with an error", function( done ) { P.reject( 13 ).nodeify(function( error, value ) { expect( error ).to.be( 13 ); expect( value ).to.be( void 0 ); done(); }); }); it("forwards a fullfilment", function() { return P( 5 ).nodeify( void 0 ).then(function( value ) { expect( value ).to.be( 5 ); }); }); it("forwards a rejection", function() { return P.reject( 3 ).nodeify( void 0 ).then(fail, function( reason ) { expect( reason ).to.be( 3 ); }); }); }); describe("promised", function() { var sum = P.promised(function( a, b ) { return a + b; }); var inc = P.promised(function( n ) { return this + n; }); it("resolves promised arguments", function() { return sum( P(1), 2 ).then(function( res ) { expect( res ).to.be( 3 ); }); }); it("resolves promised `this`", function() { return inc.call( P(4), 1 ).then(function( res ) { expect( res ).to.be( 5 ); }); }); it("is rejected if an argument is rejected", function() { return sum( P.reject(1), 2 ).then(fail, function( e ) { expect( e ).to.be( 1 ); }); }); it("is rejected if `this` is rejected", function() { return inc.call( P.reject(1), P(2) ).then(fail, function( e ) { expect( e ).to.be( 1 ); }); }); }); describe("denodeify", function() { it("should fulfill if no error", function() { var f = P.denodeify(function( a, b, c, d, callback ) { callback( null, a + b + c + d ); }); return f( 1, 2, 3, 4 ).then(function( value ) { expect( value ).to.be( 10 ); }); }); it("should reject on error", function() { var theError = new Error(); var f = P.denodeify(function( a, b, c, d, callback ) { callback( theError ); }); return f( 1, 2, 3, 4 ).then(fail, function( reason ) { expect( reason ).to.be( theError ); }); }); it("should reject on thrown error", function() { var theError = new Error(); var f = P.denodeify(function( a, b, c, d, callback ) { throw theError; }); return f( 1, 2, 3, 4 ).then(fail, function( reason ) { expect( reason ).to.be( theError ); }); }); }); !opt_tracing && describe("longStackSupport", function() { Error.stackTraceLimit = Infinity; beforeEach(function() { P.longStackSupport = true; }); afterEach(function() { P.longStackSupport = false; }); function createError( msg ) { try { throw new Error( msg ); } catch ( e ) { return e; } } function checkError( error, expectedNamesStr ) { expect( error instanceof Error ).to.be( true ); var stacks = error.stack .split("_it_")[0] .split("\nFrom previous event:\n"); var str = map(stacks, function( stack ) { return ( stack.match(/_(\w+)_/g) || [] ) .join("") .split("__").join("-") .slice(1, -1); }) .join(" ") .replace(/^\s+|\s+$/g, "") .replace(/\s+/g, " "); expect( str ).to.be( expectedNamesStr ); } it("should make trace long on sync rejected thenable", function _it_() { return P().then(function _5_() { return P().then(function _4_() { return P().then(function _3_() { return {then: function _2_( cb, eb ) { cb({then: function _1_( cb, eb ) { eb( createError() ); }}); }}; }); }) }) .then(fail, function( error ) { checkError(error, "1-2 4 5"); }); }); it("should make trace long on async rejected thenable", function _it_() { return P().then(function _5_() { return P().then(function _4_() { return P().then(function _3_() { return {then: function _2_( cb, eb ) { setTimeout(function _b_() { cb({then: function _1_( cb, eb ) { cb({then: function( cb, eb ) { setTimeout(function _a_() { eb( new Error() ); }, 0); }}); }}); P().then(function _c_() { throw new Error(); }) .done(null, function( error ) { checkError(error, "c b"); }); }, 0); }}; }); }) }) .then(fail, function( error ) { checkError(error, "a 1-b 4 5"); }); }); it("should make trace long if denodeifed function rejects", function _it_() { var rejection = P.denodeify(function( nodeback ) { setTimeout(function _0_() { nodeback( new Error() ); }, 0); }); return P().then(function _2_() { return P().then(function _1_() { return rejection(); }); }) .then(fail, function( error ) { checkError(error, "0 1 2"); }); }); it("should make trace long on timeouted promise", function _it_() { return P().then(function _2_() { return P().then(function _1_() { return P.defer().promise.timeout(1); }); }) .then(fail, function( error ) { checkError(error, "1 2"); }); }); }); if ( isNodeJS ) describe("domain", function() { var domain = require("domain"); it("should work with domains", function() { var d = P.defer(); var theValue = 0; var theError = new Error(); P(47).then(function( value ) { theValue = value; }); var theDomain = domain.create(); theDomain.on("error", function( error ) { expect( theValue ).to.be( 47 ); expect( error ).to.be( theError ); P().then( d.resolve ); }) .run(function() { P().then(function() { expect( domain.active ).to.be( theDomain ); }).done(); P.reject( theError ).done(); }); return d.promise.then(function() { expect( domain.active ).to.be( theDomain ); }, fail); }); it("should not evaluate promises in disposed domains", function() { var theDomain = domain.create(); var called = false; theDomain.on("error", function( e ) { P().then(function() { called = true; }); theDomain.dispose(); }) .run(function() { P.reject( new Error() ).done(); }); return P().delay(10).then(function() { expect( called ).to.be( false ); }); }); }); })();
test/test.js
(function(){ "use strict"; var opt_tracing = typeof TRACE_FUNCTIONS !== "undefined"; if ( typeof P === "undefined" ) { global.P = require(opt_tracing ? "./p" : "../p"); global.expect = require("expect.js"); //require("mocha"); } if ( opt_tracing ) { TRACE_FUNCTIONS.stopAdding(); beforeEach(function() { TRACE_FUNCTIONS.optimize(); }); afterEach(function() { TRACE_FUNCTIONS.optimize(); }); } var isNodeJS = typeof process === "object" && process && ({}).toString.call(process) === "[object process]"; function fail() { expect(true).to.be(false); } function thenableSyncFulfillment( value ) { return { then: function( cb, eb ) { cb( value ); } }; } function thenableSyncRejection( reason ) { return { then: function( cb, eb ) { eb( reason ); } }; } function thenableFulfillment( value ) { return { then: function( cb, eb ) { setTimeout(function() { cb( value ); }, 0) } }; } function thenableRejection( reason ) { return { then: function( cb, eb ) { setTimeout(function() { eb( reason ); }, 0) } }; } var VALUES = ["", true, false, 0, 1, 2, -1, -2, {}, [], {x: 1}, [1,2,3], null, void 0, new Error()]; var FULLFILMENTS = VALUES.concat( VALUES.map( P ), VALUES.map( thenableFulfillment ), VALUES.map( thenableSyncFulfillment ) ); var REJECTIONS = [].concat( VALUES.map( P.reject ), VALUES.map( thenableRejection ), VALUES.map( thenableSyncRejection ) ); var FULLFILMENTS_AND_REJECTIONS = FULLFILMENTS.concat( REJECTIONS ); function map( array, f ) { var array2 = new Array(array.length|0); for ( var i = 0, l = array.length; i < l; ++i ) { if ( i in array ) { array2[i] = f( array[i], i, array ); } } return array2; } function allValues( func ) { return P.all( map(VALUES, func) ); } describe("P function", function() { it("should return a promise", function() { var Promise = P().constructor; expect( Promise.constructor.name === "Promise" || Promise.toString().lastIndexOf("function Promise", 0) === 0 ).to.be(true); map(FULLFILMENTS_AND_REJECTIONS, function( value ) { expect( P(value) instanceof Promise ).to.be(true); }); }); it("should return input itself if it is a promise", function() { var p = P(); expect( P(p) ).to.be( p ); }); it("should fulfill with input if not a promise", function() { return allValues(function( value ) { return P( value ).then(function( fulfilledValue ) { expect( fulfilledValue ).to.be( value ); }); }); }); }); describe("inspect", function() { it("on fulfillment", function() { return allValues(function( value ) { var p = P( value ); return p.then(function() { expect( p.inspect() ).to.be.eql( {state: "fulfilled", value: value} ); }); }); }); it("on rejection", function() { return allValues(function( reason ) { var d = P.defer(); var p = d.promise; expect( p.inspect() ).to.be.eql( {state: "pending"} ); d.reject( reason ); return p.then( fail, function() { expect( p.inspect() ).to.be.eql( {state: "rejected", reason: reason} ); }); }); }); }); describe("reject", function() { it("returns a rejected promise", function() { return allValues(function( reason ) { return P.reject( reason ).then( fail, function( rejectedReason ) { expect( rejectedReason ).to.be( reason ); }); }); }); }); function deep( func ) { var d = P.defer(); var p = d.promise; var n = 10000; while ( n-- ) { p = func([ p ]); } d.promise = p; return d; } describe("all", function() { it("resolves when passed an empty array", function() { return P.all([]); }); it("resolves when passed an array", function() { var toResolve = P.defer(); var array = VALUES.concat( toResolve.promise ); var array2 = array.slice(); array2[ array2.length - 1 ] = 12; var promise = P.all( array ); toResolve.resolve(12); return promise.then(function( values ) { expect( values ).to.be.eql( array2 ); }); }); it("rejects if any consituent promise is rejectd", function() { var toReject = P.defer(); var theReason = new Error(); toReject.reject( theReason ); var array = FULLFILMENTS.concat( toReject.promise ) return P.all( array ) .then( fail, function( reason ) { expect( reason ).to.be( theReason ); }) .then(function() { var toRejectLater = P.defer(); var array = FULLFILMENTS.concat( toRejectLater.promise ); var promise = P.all( array ); toRejectLater.reject( theReason ); return promise; }) .then( fail, function( reason ) { expect( reason ).to.be( theReason ); }); }); it("should resolve on deep resolved promise", function() { var d = deep( P.all ); d.resolve( 1 ); return d.promise; }); it("should reject on deep rejected promise", function() { var d = deep( P.all ); d.reject( 7 ); return d.promise.then(fail, function( reason ) { expect( reason ).to.be( 7 ); }); }); }); describe("allSettled", function() { it("resolves when passed an empty array", function() { return P.allSettled([]); }); it("resolves when passed an array", function() { var array = FULLFILMENTS_AND_REJECTIONS; var promise = P.allSettled( array ); return promise.then(function( settled ) { for ( var i = 0; i < settled.length; ++i ) { var expectedValue = VALUES[ i % VALUES.length ]; if ( i < FULLFILMENTS.length ) { expect( settled[i] ).to.be.eql( {state: "fulfilled", value: expectedValue} ); } else { expect( settled[i] ).to.be.eql( {state: "rejected", reason: expectedValue} ); } } }); }); it("should resolve on deep resolved promise", function() { var d = deep( P.allSettled ); d.resolve( 1 ); return d.promise; }); it("should resolve on deep rejected promise", function() { var d = deep( P.allSettled ); d.reject( new Error("foo") ); return d.promise; }); }); describe("spread", function() { it("spreads values across arguments", function() { return P([1, P(2), 3]).spread(function( one, two, three ) { expect( one ).to.be( 1 ); expect( two ).to.be( 2 ); expect( three ).to.be( 3 ); }); }); it("should call the errback in case of a rejected promise", function() { var toReject = P.defer(); var theReason = new Error(); toReject.reject( theReason ); return P([ 1, P(2), toReject.promise]).spread( fail, function( reason ) { expect( reason ).to.be( theReason ); } ); }); }); describe("done", function() { afterEach(function() { P.onerror = null; }); // TODO: cover other cases too! describe("when the promise is rejected", function() { describe("and there is no errback", function() { it("should throw the reason in a next turn", function( done ) { var turn = 0; var toReject = P.defer(); toReject.reject("foo"); var promise = toReject.promise; expect( promise.done() ).to.be( undefined ); P.onerror = function( error ) { expect( turn ).to.be( 1 ); expect( error ).to.be("foo"); done(); }; ++turn; }); }); }); }); describe("fin", function() { describe("when the promise is fulfilled", function() { it("should call the callback and fulfill with the original value", function() { var called = false; return P("foo") .fin(function() { called = true; return "boo"; }) .then(function( value ) { expect( called ).to.be( true ); expect( value ).to.be("foo"); }); }); describe("when the callback returns a promise", function() { describe("that is fulfilled", function() { it("should fulfill with the original value after the promise is settled", function() { var delayed = P("boo").delay(50); return P("foo") .fin(function() { return delayed; }) .then(function( value ) { expect( delayed.inspect() ).to.be.eql({ state: "fulfilled", value: "boo" }); expect( value ).to.be("foo"); }); }) }); describe("that is rejected", function() { it("should reject with this new reason", function() { var theError = new Error("boo"); return P("foo") .fin(function() { return P.reject( theError ); }) .then(fail, function( reason ) { expect( reason ).to.be( theError ); }); }); }); }); describe("when the callback throws an exception", function() { it("should reject with this new exception", function() { var theError = new Error("boo"); return P("foo") .fin(function() { throw theError; }) .then(fail, function( reason ) { expect( reason ).to.be( theError ); }); }); }); }); describe("when the promise is rejected", function () { var theError = new Error("nooo"); it("should call the callback and reject with the original reason", function() { var called = false; return P.reject( theError ) .fin(function() { called = true; return "boo"; }) .then(fail, function( reason ) { expect( called ).to.be( true ); expect( reason ).to.be( theError ); }); }); describe("when the callback returns a promise", function() { describe("that is fulfilled", function() { it("should reject with the original reason after the promise is settled", function() { var delayed = P("boo").delay(50); return P.reject( theError ) .fin(function() { return delayed; }) .then(fail, function( reason ) { expect( delayed.inspect() ).to.be.eql({ state: "fulfilled", value: "boo" }); expect( reason ).to.be( theError ); }); }) }); describe("that is rejected", function() { it("should reject with this new reason", function() { return P.reject( new Error("boo") ) .fin(function() { return P.reject( theError ); }) .then(fail, function( reason ) { expect( reason ).to.be( theError ); }); }); }); }); describe("when the callback throws an exception", function() { it("should reject with this new exception", function() { var theError = new Error("boo"); return P.reject( new Error("boo") ) .fin(function() { throw theError; }) .then(fail, function( reason ) { expect( reason ).to.be( theError ); }); }); }); }); }); describe("timeout", function() { // This part is based on the respective part of the Q spec. it("should do nothing if the promise fulfills quickly", function() { return P().delay( 10 ).timeout( 100 ); }); it("should do nothing if the promise rejects quickly", function() { var error = new Error(); return P().delay( 10 ) .then(function() { throw error; }) .timeout( 100 ) .then( fail, function( reason ) { expect( reason ).to.be( error ); }); }); it("should reject within a timeout error if the promise is too slow", function() { return P().delay( 100 ) .timeout( 10 ) .then( fail, function( reason ) { expect( reason.message ).to.match(/time/i); }); }); it("should reject with a custom timeout message if the promise is too slow", function() { return P().delay( 100 ) .timeout(10, "custom") .then( fail, function( reason ) { expect( reason.message ).to.match(/custom/i); }); }); }); describe("delay", function() { // This part is based on the respective part of the Q spec. it("should dealy fulfillment", function() { var promise = P(1).delay( 50 ); setTimeout(function() { expect( promise.inspect().state ).to.be("pending"); }, 30); return promise; }); it("should not dealy rejection", function() { var d = P.defer(); d.reject(1); var promise = d.promise.delay( 50 ); setTimeout(function() { expect( promise.inspect().state ).to.be("rejected"); }, 30); return promise.then( fail, function(){} ); }); it("should delay after fulfillment", function() { var p1 = P("foo").delay( 30 ); var p2 = p1.delay( 30 ); setTimeout(function() { expect( p1.inspect().state ).to.be("fulfilled"); expect( p2.inspect().state ).to.be("pending"); }, 45); return p2.then(function( value ) { expect( value ).to.be("foo"); }); }); }); describe("nodeify", function() { it("calls back with a resolution", function( done ) { P( 7 ).nodeify(function( error, value ) { expect( error ).to.be( null ); expect( value ).to.be( 7 ); done(); }); }); it("calls back with an error", function( done ) { P.reject( 13 ).nodeify(function( error, value ) { expect( error ).to.be( 13 ); expect( value ).to.be( void 0 ); done(); }); }); it("forwards a fullfilment", function() { return P( 5 ).nodeify( void 0 ).then(function( value ) { expect( value ).to.be( 5 ); }); }); it("forwards a rejection", function() { return P.reject( 3 ).nodeify( void 0 ).then(fail, function( reason ) { expect( reason ).to.be( 3 ); }); }); }); describe("promised", function() { var sum = P.promised(function( a, b ) { return a + b; }); var inc = P.promised(function( n ) { return this + n; }); it("resolves promised arguments", function() { return sum( P(1), 2 ).then(function( res ) { expect( res ).to.be( 3 ); }); }); it("resolves promised `this`", function() { return inc.call( P(4), 1 ).then(function( res ) { expect( res ).to.be( 5 ); }); }); it("is rejected if an argument is rejected", function() { return sum( P.reject(1), 2 ).then(fail, function( e ) { expect( e ).to.be( 1 ); }); }); it("is rejected if `this` is rejected", function() { return inc.call( P.reject(1), P(2) ).then(fail, function( e ) { expect( e ).to.be( 1 ); }); }); }); describe("denodeify", function() { it("should fulfill if no error", function() { var f = P.denodeify(function( a, b, c, d, callback ) { callback( null, a + b + c + d ); }); return f( 1, 2, 3, 4 ).then(function( value ) { expect( value ).to.be( 10 ); }); }); it("should reject on error", function() { var theError = new Error(); var f = P.denodeify(function( a, b, c, d, callback ) { callback( theError ); }); return f( 1, 2, 3, 4 ).then(fail, function( reason ) { expect( reason ).to.be( theError ); }); }); it("should reject on thrown error", function() { var theError = new Error(); var f = P.denodeify(function( a, b, c, d, callback ) { throw theError; }); return f( 1, 2, 3, 4 ).then(fail, function( reason ) { expect( reason ).to.be( theError ); }); }); }); !opt_tracing && describe("longStackSupport", function() { Error.stackTraceLimit = Infinity; beforeEach(function() { P.longStackSupport = true; }); afterEach(function() { P.longStackSupport = false; }); function createError( msg ) { try { throw new Error( msg ); } catch ( e ) { return e; } } function checkError( error, expectedNamesStr ) { expect( error instanceof Error ).to.be( true ); var stacks = error.stack .split("_it_")[0] .split("\nFrom previous event:\n"); var str = map(stacks, function( stack ) { return ( stack.match(/_(\w+)_/g) || [] ) .join("") .split("__").join("-") .slice(1, -1); }) .join(" ") .replace(/^\s+|\s+$/g, "") .replace(/\s+/g, " "); expect( str ).to.be( expectedNamesStr ); } it("should make trace long on sync rejected thenable", function _it_() { return P().then(function _5_() { return P().then(function _4_() { return P().then(function _3_() { return {then: function _2_( cb, eb ) { cb({then: function _1_( cb, eb ) { eb( createError() ); }}); }}; }); }) }) .then(fail, function( error ) { checkError(error, "1-2 4 5"); }); }); it("should make trace long on async rejected thenable", function _it_() { return P().then(function _5_() { return P().then(function _4_() { return P().then(function _3_() { return {then: function _2_( cb, eb ) { setTimeout(function _b_() { cb({then: function _1_( cb, eb ) { cb({then: function( cb, eb ) { setTimeout(function _a_() { eb( new Error() ); }, 0); }}); }}); P().then(function _c_() { throw new Error(); }) .done(null, function( error ) { checkError(error, "c b"); }); }, 0); }}; }); }) }) .then(fail, function( error ) { checkError(error, "a 1-b 4 5"); }); }); it("should make trace long if denodeifed function rejects", function _it_() { var rejection = P.denodeify(function( nodeback ) { setTimeout(function _0_() { nodeback( new Error() ); }, 0); }); return P().then(function _2_() { return P().then(function _1_() { return rejection(); }); }) .then(fail, function( error ) { checkError(error, "0 1 2"); }); }); it("should make trace long on timeouted promise", function _it_() { return P().then(function _2_() { return P().then(function _1_() { return P.defer().promise.timeout(1); }); }) .then(fail, function( error ) { checkError(error, "1 2"); }); }); }); if ( isNodeJS ) describe("domain", function() { var domain = require("domain"); it("should work with domains", function() { var d = P.defer(); var theValue = 0; var theError = new Error(); P(47).then(function( value ) { theValue = value; }); var theDomain = domain.create(); theDomain.on("error", function( error ) { expect( theValue ).to.be( 47 ); expect( error ).to.be( theError ); P().then( d.resolve ); }) .run(function() { P().then(function() { expect( domain.active ).to.be( theDomain ); }).done(); P.reject( theError ).done(); }); return d.promise.then(function() { expect( domain.active ).not.to.be( theDomain ); }, fail); }); it("should not evaluate promises in disposed domains", function() { var theDomain = domain.create(); var called = false; theDomain.on("error", function( e ) { P().then(function() { called = true; }); theDomain.dispose(); }) .run(function() { P.reject( new Error() ).done(); }); return P().delay(10).then(function() { expect( called ).to.be( false ); }); }); }); })();
Fix domain test
test/test.js
Fix domain test
<ide><path>est/test.js <ide> }); <ide> <ide> return d.promise.then(function() { <del> expect( domain.active ).not.to.be( theDomain ); <add> expect( domain.active ).to.be( theDomain ); <ide> }, fail); <ide> }); <ide>
Java
apache-2.0
fe43a364c84d92209af2c1e60a6af80870009213
0
tylerrinnan-wf/java-nats,cloudfoundry-community/java-nats
/* * Copyright (c) 2012 Mike Heath. All rights reserved. * * 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 nats.codec; import nats.NatsException; import org.codehaus.jackson.annotate.JsonCreator; import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; /** * @author Mike Heath <[email protected]> */ public class ConnectBody { private final String user; private final String password; private final boolean pedantic; private final boolean verbose; @JsonCreator public ConnectBody( @JsonProperty("user") String user, @JsonProperty("pass") String password, @JsonProperty("pedantic") boolean pedantic, @JsonProperty("verbose") boolean verbose) { this.user = user; this.password = password; this.pedantic = pedantic; this.verbose = verbose; } @JsonProperty("pass") public String getPassword() { return password; } public boolean isPedantic() { return pedantic; } public String getUser() { return user; } public boolean isVerbose() { return verbose; } public static ConnectBody parse(String body) { final ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); try { return mapper.readValue(body, ConnectBody.class); } catch (IOException e) { throw new NatsException(e); } } }
client/src/main/java/nats/codec/ConnectBody.java
/* * Copyright (c) 2012 Mike Heath. All rights reserved. * * 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 nats.codec; import nats.NatsException; import org.codehaus.jackson.annotate.JsonCreator; import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; /** * @author Mike Heath <[email protected]> */ public class ConnectBody { private final String user; private final String password; private final boolean pedantic; private final boolean verbose; @JsonCreator public ConnectBody( @JsonProperty("user") String user, @JsonProperty("password") String password, @JsonProperty("pedantic") boolean pedantic, @JsonProperty("verbose") boolean verbose) { this.user = user; this.password = password; this.pedantic = pedantic; this.verbose = verbose; } public String getPassword() { return password; } public boolean isPedantic() { return pedantic; } public String getUser() { return user; } public boolean isVerbose() { return verbose; } public static ConnectBody parse(String body) { final ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); try { return mapper.readValue(body, ConnectBody.class); } catch (IOException e) { throw new NatsException(e); } } }
Fixed #19 - Body of connect message isn't JSON encoded properly for authentication.
client/src/main/java/nats/codec/ConnectBody.java
Fixed #19 - Body of connect message isn't JSON encoded properly for authentication.
<ide><path>lient/src/main/java/nats/codec/ConnectBody.java <ide> public ConnectBody( <ide> @JsonProperty("user") <ide> String user, <del> @JsonProperty("password") <add> @JsonProperty("pass") <ide> String password, <ide> @JsonProperty("pedantic") <ide> boolean pedantic, <ide> this.verbose = verbose; <ide> } <ide> <add> @JsonProperty("pass") <ide> public String getPassword() { <ide> return password; <ide> }
Java
agpl-3.0
0d4722c5f2379da05a6041d2834e1098db852d6b
0
fqqb/yamcs,fqqb/yamcs,yamcs/yamcs,fqqb/yamcs,yamcs/yamcs,fqqb/yamcs,yamcs/yamcs,fqqb/yamcs,yamcs/yamcs,fqqb/yamcs,yamcs/yamcs,yamcs/yamcs
package org.yamcs.yarch.rocksdb; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.rocksdb.ReadOptions; import org.rocksdb.RocksDBException; import org.rocksdb.RocksIterator; import org.rocksdb.Snapshot; import org.rocksdb.WriteBatch; import org.rocksdb.WriteOptions; import org.yamcs.utils.StringConverter; import org.yamcs.yarch.AbstractTableWalker; import org.yamcs.yarch.DbRange; import org.yamcs.yarch.Partition; import org.yamcs.yarch.PartitionManager; import org.yamcs.yarch.RawTuple; import org.yamcs.yarch.TableDefinition; import org.yamcs.yarch.TableVisitor; import org.yamcs.yarch.YarchDatabaseInstance; import org.yamcs.yarch.YarchException; import org.yamcs.yarch.streamsql.StreamSqlException; import org.yamcs.yarch.streamsql.StreamSqlException.ErrCode; public class RdbTableWalker extends AbstractTableWalker { private final Tablespace tablespace; static AtomicInteger count = new AtomicInteger(0); boolean batchUpdates = false; Snapshot snapshot = null; protected TableVisitor visitor; protected RdbTableWalker(Tablespace tablespace, YarchDatabaseInstance ydb, TableDefinition tableDefinition, boolean ascending, boolean follow) { super(ydb, tableDefinition, ascending, follow); this.tablespace = tablespace; } /** * * Iterate data through the given interval taking into account also the tableRange. * <p> * tableRange has to be non-null but can be unbounded at one or both ends. * <p * Return true if the tableRange is bounded and the end has been reached. * * @throws StreamSqlException */ @Override protected boolean walkInterval(PartitionManager.Interval interval, DbRange tableRange, TableVisitor visitor) throws YarchException, StreamSqlException { this.visitor = visitor; running = true; try { return doWalkInterval(interval, tableRange); } catch (RocksDBException e) { throw new YarchException(e); } } /** * runs value based partitions: the partition value is encoded as the first bytes of the key, so we have to make * multiple parallel iterators * * @return true if the end condition has been reached * @throws RocksDBException * @throws StreamSqlException */ private boolean doWalkInterval(PartitionManager.Interval interval, DbRange tableRange) throws RocksDBException, StreamSqlException { DbIterator iterator = null; RdbPartition p1 = (RdbPartition) interval.iterator().next(); final YRDB rdb; if (p1.dir != null) { log.debug("opening database {}", p1.dir); rdb = tablespace.getRdb(p1.dir, false); } else { rdb = tablespace.getRdb(); } ReadOptions readOptions = new ReadOptions(); readOptions.setTailing(follow); if (!follow) { if (snapshot == null) { snapshot = rdb.getDb().getSnapshot(); } readOptions.setSnapshot(snapshot); } WriteBatch writeBatch = batchUpdates ? new WriteBatch() : null; try { List<DbIterator> itList = new ArrayList<>(interval.size()); // create an iterator for each partitions for (Partition p : interval) { p1 = (RdbPartition) p; if (!ascending) { readOptions.setTotalOrderSeek(true); } RocksIterator rocksIt = rdb.getDb().newIterator(readOptions); DbIterator it = getPartitionIterator(rocksIt, p1.tbsIndex, ascending, tableRange); if (it.isValid()) { itList.add(it); } else { it.close(); } } if (itList.size() == 0) { return false; } else if (itList.size() == 1) { iterator = itList.get(0); } else { iterator = new MergingIterator(itList, ascending ? new SuffixAscendingComparator(4) : new SuffixDescendingComparator(4)); } boolean endReached; if (ascending) { endReached = runAscending(rdb, iterator, writeBatch, tableRange.rangeEnd); } else { endReached = runDescending(rdb, iterator, writeBatch, tableRange.rangeStart); } if (writeBatch != null) { WriteOptions wo = new WriteOptions(); rdb.getDb().write(wo, writeBatch); wo.close(); } return endReached; } finally { if (iterator != null) { iterator.close(); } if (snapshot != null) { rdb.getDb().releaseSnapshot(snapshot); snapshot.close(); snapshot = null; } readOptions.close(); tablespace.dispose(rdb); if (writeBatch != null) { writeBatch.close(); } } } /** * If set, the snapshot will be used to iterate the database but only if the follow = false * <p> * The snapshot will be release at the end * * @param snapshot */ public void setSnapshot(Snapshot snapshot) { this.snapshot = snapshot; } // return true if the end condition has been reached boolean runAscending(YRDB rdb, DbIterator iterator, WriteBatch writeBatch, byte[] rangeEnd) throws RocksDBException, StreamSqlException { while (isRunning() && iterator.isValid()) { byte[] dbKey = iterator.key(); byte[] key = Arrays.copyOfRange(dbKey, 4, dbKey.length); byte[] value = iterator.value(); numRecordsRead++; if (iAscendingFinished(key, value, rangeEnd)) { return true; } TableVisitor.Action action = visitor.visit(key, iterator.value()); if (writeBatch == null) { executeAction(rdb, action, dbKey); } else { executeAction(rdb, writeBatch, action, dbKey); } if (action.stop()) { close(); return false; } iterator.next(); } return false; } boolean runDescending(YRDB rdb, DbIterator iterator, WriteBatch writeBatch, byte[] rangeStart) throws RocksDBException, StreamSqlException { while (isRunning() && iterator.isValid()) { byte[] dbKey = iterator.key(); byte[] key = Arrays.copyOfRange(dbKey, 4, dbKey.length); numRecordsRead++; if (isDescendingFinished(key, iterator.value(), rangeStart)) { return true; } TableVisitor.Action action = visitor.visit(key, iterator.value()); if (writeBatch == null) { executeAction(rdb, action, dbKey); } else { executeAction(rdb, writeBatch, action, dbKey); } if (action.stop()) { close(); return false; } iterator.prev(); } return false; } static void executeAction(YRDB rdb, WriteBatch writeBatch, TableVisitor.Action action, byte[] dbKey) throws RocksDBException, StreamSqlException { if (action.action() == TableVisitor.ActionType.DELETE) { writeBatch.delete(dbKey); } else if (action.action() == TableVisitor.ActionType.UPDATE_VAL) { writeBatch.put(dbKey, action.getUpdatedValue()); } else if (action.action() == TableVisitor.ActionType.UPDATE_ROW) { // we only support updates on non partition tables int tbsIndex = RdbStorageEngine.tbsIndex(dbKey); byte[] updatedDbKey = RdbStorageEngine.dbKey(tbsIndex, action.getUpdatedKey()); if (rdb.get(updatedDbKey) != null) { throw new StreamSqlException(ErrCode.DUPLICATE_KEY, "duplicate key in update: " + StringConverter.arrayToHexString(updatedDbKey)); } writeBatch.delete(dbKey); writeBatch.put(updatedDbKey, action.getUpdatedValue()); } } static void executeAction(YRDB rdb, TableVisitor.Action action, byte[] dbKey) throws RocksDBException, StreamSqlException { if (action.action() == TableVisitor.ActionType.DELETE) { rdb.delete(dbKey); } else if (action.action() == TableVisitor.ActionType.UPDATE_VAL) { rdb.put(dbKey, action.getUpdatedValue()); } else if (action.action() == TableVisitor.ActionType.UPDATE_ROW) { // we only support updates on non partition tables int tbsIndex = RdbStorageEngine.tbsIndex(dbKey); byte[] updatedDbKey = RdbStorageEngine.dbKey(tbsIndex, action.getUpdatedKey()); if (rdb.get(updatedDbKey) != null) { throw new StreamSqlException(ErrCode.DUPLICATE_KEY, "duplicate key in update: " + StringConverter.arrayToHexString(updatedDbKey)); } rdb.delete(dbKey); rdb.put(updatedDbKey, action.getUpdatedValue()); } } /* * create a ranging iterator for the given partition * TODO: check usage of RocksDB prefix iterators * */ private DbIterator getPartitionIterator(RocksIterator it, int tbsIndex, boolean ascending, DbRange tableRange) { DbRange dbRange = getDbRange(tbsIndex, tableRange); if (ascending) { return new AscendingRangeIterator(it, dbRange); } else { return new DescendingRangeIterator(it, dbRange); } } public long getNumRecordsRead() { return numRecordsRead; } public boolean isBatchUpdates() { return batchUpdates; } public void setBatchUpdates(boolean batchUpdates) { this.batchUpdates = batchUpdates; } class RdbRawTuple extends RawTuple { RocksIterator iterator; byte[] partition; byte[] key; byte[] value; public RdbRawTuple(byte[] partition, byte[] key, byte[] value, RocksIterator iterator, int index) { super(index); this.partition = partition; this.key = key; this.value = value; this.iterator = iterator; } @Override protected byte[] getKey() { return key; } @Override protected byte[] getValue() { return value; } } static DbRange getDbRange(int tbsIndex, DbRange tableRange) { DbRange dbr = new DbRange(); if (tableRange != null && tableRange.rangeStart != null) { dbr.rangeStart = RdbStorageEngine.dbKey(tbsIndex, tableRange.rangeStart); } else { dbr.rangeStart = RdbStorageEngine.dbKey(tbsIndex); } if (tableRange != null && tableRange.rangeEnd != null) { dbr.rangeEnd = RdbStorageEngine.dbKey(tbsIndex, tableRange.rangeEnd); } else { dbr.rangeEnd = RdbStorageEngine.dbKey(tbsIndex); } return dbr; } static class SuffixAscendingComparator implements Comparator<byte[]> { int prefixSize; public SuffixAscendingComparator(int prefixSize) { this.prefixSize = prefixSize; } @Override public int compare(byte[] b1, byte[] b2) { int minLength = Math.min(b1.length, b2.length); for (int i = prefixSize; i < minLength; i++) { int d = (b1[i] & 0xFF) - (b2[i] & 0xFF); if (d != 0) { return d; } } for (int i = 0; i < prefixSize; i++) { int d = (b1[i] & 0xFF) - (b2[i] & 0xFF); if (d != 0) { return d; } } return b1.length - b2.length; } } static class SuffixDescendingComparator implements Comparator<byte[]> { int prefixSize; public SuffixDescendingComparator(int prefixSize) { this.prefixSize = prefixSize; } @Override public int compare(byte[] b1, byte[] b2) { int minLength = Math.min(b1.length, b2.length); for (int i = prefixSize; i < minLength; i++) { int d = (b2[i] & 0xFF) - (b1[i] & 0xFF); if (d != 0) { return d; } } for (int i = 0; i < prefixSize; i++) { int d = (b2[i] & 0xFF) - (b1[i] & 0xFF); if (d != 0) { return d; } } return b2.length - b1.length; } } }
yamcs-core/src/main/java/org/yamcs/yarch/rocksdb/RdbTableWalker.java
package org.yamcs.yarch.rocksdb; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.rocksdb.ReadOptions; import org.rocksdb.RocksDBException; import org.rocksdb.RocksIterator; import org.rocksdb.Snapshot; import org.rocksdb.WriteBatch; import org.rocksdb.WriteOptions; import org.yamcs.utils.StringConverter; import org.yamcs.yarch.AbstractTableWalker; import org.yamcs.yarch.DbRange; import org.yamcs.yarch.Partition; import org.yamcs.yarch.PartitionManager; import org.yamcs.yarch.RawTuple; import org.yamcs.yarch.TableDefinition; import org.yamcs.yarch.TableVisitor; import org.yamcs.yarch.YarchDatabaseInstance; import org.yamcs.yarch.YarchException; import org.yamcs.yarch.streamsql.StreamSqlException; import org.yamcs.yarch.streamsql.StreamSqlException.ErrCode; public class RdbTableWalker extends AbstractTableWalker { private final Tablespace tablespace; static AtomicInteger count = new AtomicInteger(0); boolean batchUpdates = false; Snapshot snapshot = null; protected TableVisitor visitor; protected RdbTableWalker(Tablespace tablespace, YarchDatabaseInstance ydb, TableDefinition tableDefinition, boolean ascending, boolean follow) { super(ydb, tableDefinition, ascending, follow); this.tablespace = tablespace; } /** * * Iterate data through the given interval taking into account also the tableRange. * <p> * tableRange has to be non-null but can be unbounded at one or both ends. * <p * Return true if the tableRange is bounded and the end has been reached. * * @throws StreamSqlException */ @Override protected boolean walkInterval(PartitionManager.Interval interval, DbRange tableRange, TableVisitor visitor) throws YarchException, StreamSqlException { this.visitor = visitor; running = true; try { return doWalkInterval(interval, tableRange); } catch (RocksDBException e) { throw new YarchException(e); } } /** * runs value based partitions: the partition value is encoded as the first bytes of the key, so we have to make * multiple parallel iterators * * @return true if the end condition has been reached * @throws RocksDBException * @throws StreamSqlException */ private boolean doWalkInterval(PartitionManager.Interval interval, DbRange tableRange) throws RocksDBException, StreamSqlException { DbIterator iterator = null; RdbPartition p1 = (RdbPartition) interval.iterator().next(); final YRDB rdb; if (p1.dir != null) { log.debug("opening database {}", p1.dir); rdb = tablespace.getRdb(p1.dir, false); } else { rdb = tablespace.getRdb(); } ReadOptions readOptions = new ReadOptions(); readOptions.setTailing(follow); if (!follow) { if (snapshot == null) { snapshot = rdb.getDb().getSnapshot(); } readOptions.setSnapshot(snapshot); } WriteBatch writeBatch = batchUpdates ? new WriteBatch() : null; try { List<DbIterator> itList = new ArrayList<>(interval.size()); // create an iterator for each partitions for (Partition p : interval) { p1 = (RdbPartition) p; if (!ascending) { readOptions.setTotalOrderSeek(true); } RocksIterator rocksIt = rdb.getDb().newIterator(readOptions); DbIterator it = getPartitionIterator(rocksIt, p1.tbsIndex, ascending, tableRange); if (it.isValid()) { itList.add(it); } else { it.close(); } } if (itList.size() == 0) { return false; } else if (itList.size() == 1) { iterator = itList.get(0); } else { iterator = new MergingIterator(itList, ascending ? new SuffixAscendingComparator(4) : new SuffixDescendingComparator(4)); } boolean endReached; if (ascending) { endReached = runAscending(rdb, iterator, writeBatch, tableRange.rangeEnd); } else { endReached = runDescending(rdb, iterator, writeBatch, tableRange.rangeStart); } if (writeBatch != null) { WriteOptions wo = new WriteOptions(); rdb.getDb().write(wo, writeBatch); wo.close(); } return endReached; } finally { if (iterator != null) { iterator.close(); } if (snapshot != null) { snapshot.close(); rdb.getDb().releaseSnapshot(snapshot); snapshot = null; } readOptions.close(); tablespace.dispose(rdb); if (writeBatch != null) { writeBatch.close(); } } } /** * If set, the snapshot will be used to iterate the database but only if the follow = false * <p> * The snapshot will be release at the end * * @param snapshot */ public void setSnapshot(Snapshot snapshot) { this.snapshot = snapshot; } // return true if the end condition has been reached boolean runAscending(YRDB rdb, DbIterator iterator, WriteBatch writeBatch, byte[] rangeEnd) throws RocksDBException, StreamSqlException { while (isRunning() && iterator.isValid()) { byte[] dbKey = iterator.key(); byte[] key = Arrays.copyOfRange(dbKey, 4, dbKey.length); byte[] value = iterator.value(); numRecordsRead++; if (iAscendingFinished(key, value, rangeEnd)) { return true; } TableVisitor.Action action = visitor.visit(key, iterator.value()); if (writeBatch == null) { executeAction(rdb, action, dbKey); } else { executeAction(rdb, writeBatch, action, dbKey); } if (action.stop()) { close(); return false; } iterator.next(); } return false; } boolean runDescending(YRDB rdb, DbIterator iterator, WriteBatch writeBatch, byte[] rangeStart) throws RocksDBException, StreamSqlException { while (isRunning() && iterator.isValid()) { byte[] dbKey = iterator.key(); byte[] key = Arrays.copyOfRange(dbKey, 4, dbKey.length); numRecordsRead++; if (isDescendingFinished(key, iterator.value(), rangeStart)) { return true; } TableVisitor.Action action = visitor.visit(key, iterator.value()); if (writeBatch == null) { executeAction(rdb, action, dbKey); } else { executeAction(rdb, writeBatch, action, dbKey); } if (action.stop()) { close(); return false; } iterator.prev(); } return false; } static void executeAction(YRDB rdb, WriteBatch writeBatch, TableVisitor.Action action, byte[] dbKey) throws RocksDBException, StreamSqlException { if (action.action() == TableVisitor.ActionType.DELETE) { writeBatch.delete(dbKey); } else if (action.action() == TableVisitor.ActionType.UPDATE_VAL) { writeBatch.put(dbKey, action.getUpdatedValue()); } else if (action.action() == TableVisitor.ActionType.UPDATE_ROW) { // we only support updates on non partition tables int tbsIndex = RdbStorageEngine.tbsIndex(dbKey); byte[] updatedDbKey = RdbStorageEngine.dbKey(tbsIndex, action.getUpdatedKey()); if (rdb.get(updatedDbKey) != null) { throw new StreamSqlException(ErrCode.DUPLICATE_KEY, "duplicate key in update: " + StringConverter.arrayToHexString(updatedDbKey)); } writeBatch.delete(dbKey); writeBatch.put(updatedDbKey, action.getUpdatedValue()); } } static void executeAction(YRDB rdb, TableVisitor.Action action, byte[] dbKey) throws RocksDBException, StreamSqlException { if (action.action() == TableVisitor.ActionType.DELETE) { rdb.delete(dbKey); } else if (action.action() == TableVisitor.ActionType.UPDATE_VAL) { rdb.put(dbKey, action.getUpdatedValue()); } else if (action.action() == TableVisitor.ActionType.UPDATE_ROW) { // we only support updates on non partition tables int tbsIndex = RdbStorageEngine.tbsIndex(dbKey); byte[] updatedDbKey = RdbStorageEngine.dbKey(tbsIndex, action.getUpdatedKey()); if (rdb.get(updatedDbKey) != null) { throw new StreamSqlException(ErrCode.DUPLICATE_KEY, "duplicate key in update: " + StringConverter.arrayToHexString(updatedDbKey)); } rdb.delete(dbKey); rdb.put(updatedDbKey, action.getUpdatedValue()); } } /* * create a ranging iterator for the given partition * TODO: check usage of RocksDB prefix iterators * */ private DbIterator getPartitionIterator(RocksIterator it, int tbsIndex, boolean ascending, DbRange tableRange) { DbRange dbRange = getDbRange(tbsIndex, tableRange); if (ascending) { return new AscendingRangeIterator(it, dbRange); } else { return new DescendingRangeIterator(it, dbRange); } } public long getNumRecordsRead() { return numRecordsRead; } public boolean isBatchUpdates() { return batchUpdates; } public void setBatchUpdates(boolean batchUpdates) { this.batchUpdates = batchUpdates; } class RdbRawTuple extends RawTuple { RocksIterator iterator; byte[] partition; byte[] key; byte[] value; public RdbRawTuple(byte[] partition, byte[] key, byte[] value, RocksIterator iterator, int index) { super(index); this.partition = partition; this.key = key; this.value = value; this.iterator = iterator; } @Override protected byte[] getKey() { return key; } @Override protected byte[] getValue() { return value; } } static DbRange getDbRange(int tbsIndex, DbRange tableRange) { DbRange dbr = new DbRange(); if (tableRange != null && tableRange.rangeStart != null) { dbr.rangeStart = RdbStorageEngine.dbKey(tbsIndex, tableRange.rangeStart); } else { dbr.rangeStart = RdbStorageEngine.dbKey(tbsIndex); } if (tableRange != null && tableRange.rangeEnd != null) { dbr.rangeEnd = RdbStorageEngine.dbKey(tbsIndex, tableRange.rangeEnd); } else { dbr.rangeEnd = RdbStorageEngine.dbKey(tbsIndex); } return dbr; } static class SuffixAscendingComparator implements Comparator<byte[]> { int prefixSize; public SuffixAscendingComparator(int prefixSize) { this.prefixSize = prefixSize; } @Override public int compare(byte[] b1, byte[] b2) { int minLength = Math.min(b1.length, b2.length); for (int i = prefixSize; i < minLength; i++) { int d = (b1[i] & 0xFF) - (b2[i] & 0xFF); if (d != 0) { return d; } } for (int i = 0; i < prefixSize; i++) { int d = (b1[i] & 0xFF) - (b2[i] & 0xFF); if (d != 0) { return d; } } return b1.length - b2.length; } } static class SuffixDescendingComparator implements Comparator<byte[]> { int prefixSize; public SuffixDescendingComparator(int prefixSize) { this.prefixSize = prefixSize; } @Override public int compare(byte[] b1, byte[] b2) { int minLength = Math.min(b1.length, b2.length); for (int i = prefixSize; i < minLength; i++) { int d = (b2[i] & 0xFF) - (b1[i] & 0xFF); if (d != 0) { return d; } } for (int i = 0; i < prefixSize; i++) { int d = (b2[i] & 0xFF) - (b1[i] & 0xFF); if (d != 0) { return d; } } return b2.length - b1.length; } } }
fix crash with snapshot releaseSnapshot has to be called before snapshot.close
yamcs-core/src/main/java/org/yamcs/yarch/rocksdb/RdbTableWalker.java
fix crash with snapshot
<ide><path>amcs-core/src/main/java/org/yamcs/yarch/rocksdb/RdbTableWalker.java <ide> iterator.close(); <ide> } <ide> if (snapshot != null) { <add> rdb.getDb().releaseSnapshot(snapshot); <ide> snapshot.close(); <del> rdb.getDb().releaseSnapshot(snapshot); <ide> snapshot = null; <ide> } <ide> readOptions.close();
Java
apache-2.0
error: pathspec 'src/com/opengamma/id/UniqueIdentifierFudgeType.java' did not match any file(s) known to git
4d5602f87edb7e38444fe670c999532f099c45b6
1
nssales/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,jeorme/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling
/** * Copyright (C) 2009 - 2010 by OpenGamma Inc. * * Please see distribution for license. */ package com.opengamma.id; import org.fudgemsg.types.SecondaryFieldType; import org.fudgemsg.types.StringFieldType; /** * Defines a UniqueIdentifier as a Fudge type, based on String. The UniqueIdentifier is typically encoded as a * submessage using its toFudgeMsg and fromFudgeMsg methods, but there may be cases where a string is required. */ public final class UniqueIdentifierFudgeType extends SecondaryFieldType<UniqueIdentifier, String> { /** * Singleton instance of the type. */ public static final UniqueIdentifierFudgeType INSTANCE = new UniqueIdentifierFudgeType(); private UniqueIdentifierFudgeType() { super(StringFieldType.INSTANCE, UniqueIdentifier.class); } @Override public String secondaryToPrimary(final UniqueIdentifier identifier) { return identifier.toString(); } @Override public UniqueIdentifier primaryToSecondary(final String string) { return UniqueIdentifier.parse(string); } }
src/com/opengamma/id/UniqueIdentifierFudgeType.java
Secondary Fudge type for UniqueIdentifiers that are encoded as strings.
src/com/opengamma/id/UniqueIdentifierFudgeType.java
Secondary Fudge type for UniqueIdentifiers that are encoded as strings.
<ide><path>rc/com/opengamma/id/UniqueIdentifierFudgeType.java <add>/** <add> * Copyright (C) 2009 - 2010 by OpenGamma Inc. <add> * <add> * Please see distribution for license. <add> */ <add>package com.opengamma.id; <add> <add>import org.fudgemsg.types.SecondaryFieldType; <add>import org.fudgemsg.types.StringFieldType; <add> <add>/** <add> * Defines a UniqueIdentifier as a Fudge type, based on String. The UniqueIdentifier is typically encoded as a <add> * submessage using its toFudgeMsg and fromFudgeMsg methods, but there may be cases where a string is required. <add> */ <add>public final class UniqueIdentifierFudgeType extends SecondaryFieldType<UniqueIdentifier, String> { <add> <add> /** <add> * Singleton instance of the type. <add> */ <add> public static final UniqueIdentifierFudgeType INSTANCE = new UniqueIdentifierFudgeType(); <add> <add> private UniqueIdentifierFudgeType() { <add> super(StringFieldType.INSTANCE, UniqueIdentifier.class); <add> } <add> <add> @Override <add> public String secondaryToPrimary(final UniqueIdentifier identifier) { <add> return identifier.toString(); <add> } <add> <add> @Override <add> public UniqueIdentifier primaryToSecondary(final String string) { <add> return UniqueIdentifier.parse(string); <add> } <add> <add>}
JavaScript
mit
7a83bd3496e1d98ca493169576948ae02d574372
0
linkedgeodesy/opossum,linkedgeodesy/opossum
import "./style/style.css"; import * as $ from "jquery"; import * as L from "leaflet"; import * as wellknown from "wellknown"; import * as turf from "@turf/turf"; import "materialize-css"; let ors_key = "58d904a497c67e00015b45fcd2e10661dfa14f2d46c679d259b00197"; let lat = 39.4699075; let lon = -0.3762881000000107; let radius = 10000; let lat_mz = 50.0; let lon_mz = 8.271111; let radius_mz = 10; let lgdtype = "PlaceOfWorship"; //Museum School PlaceOfWorship Restaurant let lgdtype2 = "Restaurant"; //Museum School PlaceOfWorship Restaurant let range_mz_min = 25; let range_mz = range_mz_min*60; // set tile layer let hotMap = L.tileLayer("http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", { maxZoom: 19, attribution: "&copy; <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a>, Tiles courtesy of <a href='http://hot.openstreetmap.org/' target='_blank'>Humanitarian OpenStreetMap Team</a>" }); let osmMap = L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { maxZoom: 19, attribution: "&copy; <a href='http://openstreetmap.org'>OpenStreetMap</a> Contributors" }); // add circle let buffer = L.circle([lat, lon], { color: "#000", fillOpacity: 0.0, radius: radius }); let buffer2 = L.circle([lat_mz, lon_mz], { color: "#000", fillOpacity: 0.0, radius: radius }); let wikipedia = L.layerGroup(); let PlaceOfWorship = L.layerGroup(); let Restaurant = L.layerGroup(); let walkingArea = L.layerGroup(); let getTypesFromDBpedia = (json) => { let types = "<br><br><b>types</b><br>"; $.ajax({ type: "GET", url: "http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=SELECT+*+WHERE+%7B+%3Fs+%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2FwikiPageID%3E+%22"+json.pageid+"%22%5E%5Exsd%3Ainteger+.+%3Fs+%3Fp+%3Fo+.%0D%0A%7D&format=application%2Fsparql-results%2Bjson&CXML_redir_for_subjs=121&CXML_redir_for_hrefs=&timeout=30000&run=+Run+Query+", async: false, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); }, success: function (data) { let bindings = data.results.bindings; for (var item in bindings) { if (bindings[item].p.value.includes("#type")) { if (bindings[item].o.value.includes("http://dbpedia.org/ontology/")) { let split = bindings[item].o.value.split("/"); types += split[split.length-1]+"<br>"; } } } } }); return types; }; var styleValencia = { "color": "#0000FF", "weight": 5, "opacity": 1.0, "fillOpacity": 0.8 }; // read valencia data from wikipedia api $.ajax({ type: "GET", url: "https://en.wikipedia.org/w/api.php?action=query&gsmaxdim=10000&list=geosearch&gslimit=1000&gsradius="+radius+"&gscoord="+lat+"|"+lon+"&continue&format=json&origin=*", async: false, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); }, success: function (data) { let geosearch = data.query.geosearch; for (var item in geosearch) { let point = turf.point([geosearch[item].lon, geosearch[item].lat]); let buffer = turf.buffer(point, 20, "meters"); let envelope = turf.envelope(buffer); let marker = L.geoJson(envelope, {style: styleValencia}); marker.properties = {}; marker.properties.wiki1 = geosearch[item]; marker.bindPopup("<a href='https://en.wikipedia.org/wiki/"+marker.properties.wiki1.title+"' target='_blank'>"+marker.properties.wiki1.title+"</a>"+getTypesFromDBpedia(geosearch[item])); wikipedia.addLayer(marker); } } }); var stylePlaceOfWorship = { "color": "#ff7800", "weight": 5, "opacity": 1.0, "fillOpacity": 0.8 }; // load place of worships via linkedgeodata.org $.ajax({ type: "GET", url: "http://linkedgeodata.org/sparql?default-graph-uri=http%3A%2F%2Flinkedgeodata.org&query=Prefix+rdfs%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23%3E%0D%0APrefix+ogc%3A+%3Chttp%3A%2F%2Fwww.opengis.net%2Font%2Fgeosparql%23%3E%0D%0APrefix+geom%3A+%3Chttp%3A%2F%2Fgeovocab.org%2Fgeometry%23%3E%0D%0APrefix+lgdo%3A+%3Chttp%3A%2F%2Flinkedgeodata.org%2Fontology%2F%3E%0D%0A%0D%0ASelect+%3Fitem+%3Flabel+%3Fgeo%0D%0AFrom+%3Chttp%3A%2F%2Flinkedgeodata.org%3E+%7B%0D%0A++%3Fitem%0D%0A++++a+lgdo%3A"+lgdtype+"+%3B%0D%0A++++rdfs%3Alabel+%3Flabel+%3B%0D%0A++++geom%3Ageometry+%5B%0D%0A++++++ogc%3AasWKT+%3Fgeo%0D%0A++++%5D+.%0D%0A+++%0D%0A++Filter+%28%0D%0A++++bif%3Ast_intersects+%28%3Fgeo%2C+bif%3Ast_point+%28"+lon_mz+"%2C+"+lat_mz+"%29%2C+"+radius_mz+"%29%0D%0A++%29+.%0D%0A%7D&format=application%2Fsparql-results%2Bjson&timeout=0&debug=on", async: false, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); }, success: function (data) { let bindings = data.results.bindings; for (var item in bindings) { // WKT TO GEOJSON via let geojson = wellknown.parse(bindings[item].geo.value); // LINESTRING TO POLYGON VIA turf if (bindings[item].geo.value.includes("LINESTRING")) { var coord = turf.getCoords(geojson); var line = turf.lineString(coord); var polygon = turf.lineStringToPolygon(line); geojson = polygon; } else if (bindings[item].geo.value.includes("POINT")) { let coord = turf.getCoords(geojson); let point = turf.point(coord); let buffer = turf.buffer(point, 10, "meters"); let envelope = turf.envelope(buffer); geojson = envelope; } let marker = L.geoJson(geojson, {style: stylePlaceOfWorship}); marker.properties = {}; marker.properties.item = bindings[item].item.value; marker.properties.label = bindings[item].label.value; marker.bindPopup("<i class='fa fa-bell' aria-hidden='true'></i><br><br>"+marker.properties.label); PlaceOfWorship.addLayer(marker); } } }); var styleRestaurant = { "color": "#447550", "weight": 5, "opacity": 1.0, "fillOpacity": 0.8 }; // load restaurants via linkedgeodata.org $.ajax({ type: "GET", url: "http://linkedgeodata.org/sparql?default-graph-uri=http%3A%2F%2Flinkedgeodata.org&query=Prefix+rdfs%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23%3E%0D%0APrefix+ogc%3A+%3Chttp%3A%2F%2Fwww.opengis.net%2Font%2Fgeosparql%23%3E%0D%0APrefix+geom%3A+%3Chttp%3A%2F%2Fgeovocab.org%2Fgeometry%23%3E%0D%0APrefix+lgdo%3A+%3Chttp%3A%2F%2Flinkedgeodata.org%2Fontology%2F%3E%0D%0A%0D%0ASelect+%3Fitem+%3Flabel+%3Fgeo%0D%0AFrom+%3Chttp%3A%2F%2Flinkedgeodata.org%3E+%7B%0D%0A++%3Fitem%0D%0A++++a+lgdo%3A"+lgdtype2+"+%3B%0D%0A++++rdfs%3Alabel+%3Flabel+%3B%0D%0A++++geom%3Ageometry+%5B%0D%0A++++++ogc%3AasWKT+%3Fgeo%0D%0A++++%5D+.%0D%0A+++%0D%0A++Filter+%28%0D%0A++++bif%3Ast_intersects+%28%3Fgeo%2C+bif%3Ast_point+%28"+lon_mz+"%2C+"+lat_mz+"%29%2C+"+radius_mz+"%29%0D%0A++%29+.%0D%0A%7D&format=application%2Fsparql-results%2Bjson&timeout=0&debug=on", async: false, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); }, success: function (data) { let bindings = data.results.bindings; for (var item in bindings) { // WKT TO GEOJSON via let geojson = wellknown.parse(bindings[item].geo.value); // LINESTRING TO POLYGON VIA turf if (bindings[item].geo.value.includes("LINESTRING")) { let coord = turf.getCoords(geojson); let line = turf.lineString(coord); let polygon = turf.lineStringToPolygon(line); geojson = polygon; } else if (bindings[item].geo.value.includes("POINT")) { let coord = turf.getCoords(geojson); let point = turf.point(coord); let buffer = turf.buffer(point, 10, "meters"); let envelope = turf.envelope(buffer); geojson = envelope; } let marker = L.geoJson(geojson, {style: styleRestaurant}); marker.properties = {}; marker.properties.item = bindings[item].item.value; marker.properties.label = bindings[item].label.value; marker.bindPopup("<i class='fa fa-glass' aria-hidden='true'></i><br><br>"+marker.properties.label); Restaurant.addLayer(marker); } } }); var styleWalkingArea = { "color": "grey", "weight": 5, "opacity": 1.0, "fillOpacity": 0.8 }; // load waking area via openrouteservice.org $.ajax({ type: "GET", url: "https://api.openrouteservice.org/isochrones?locations="+lon_mz+"%2C"+lat_mz+"&profile=foot-walking&range_type=time&range="+range_mz+"&location_type=start&api_key="+ors_key, async: false, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); }, success: function (data) { let marker = L.geoJson(data, {style: styleWalkingArea}); marker.bindPopup(); walkingArea.addLayer(marker); } }); // init map let mymap = L.map("mapid", { center: [45.5, 4.8], zoom: 6, layers: [osmMap, buffer, wikipedia, buffer2, walkingArea, PlaceOfWorship, Restaurant] }); let baseMaps = { "Hot": hotMap, "OSM Mapnik": osmMap }; let overlays ={ "Buffer Wikipedia": buffer, "wikipedia": wikipedia, "Buffer LGD": buffer2, "LGD PlaceOfWorship": PlaceOfWorship, "LGD Restaurant": Restaurant, "ORS WalkingArea 25min": walkingArea }; L.control.layers(baseMaps, overlays).addTo(mymap);
src/app.js
import "./style/style.css"; import * as $ from "jquery"; import * as L from "leaflet"; import * as wellknown from "wellknown"; import * as turf from "@turf/turf"; import "materialize-css"; let lat = 39.4699075; let lon = -0.3762881000000107; let radius = 10000; let lat_mz = 50.0; let lon_mz = 8.271111; let radius_mz = 10; let lgdtype = "PlaceOfWorship"; //Museum School PlaceOfWorship Restaurant let lgdtype2 = "Restaurant"; //Museum School PlaceOfWorship Restaurant // set tile layer let hotMap = L.tileLayer("http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", { maxZoom: 19, attribution: "&copy; <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a>, Tiles courtesy of <a href='http://hot.openstreetmap.org/' target='_blank'>Humanitarian OpenStreetMap Team</a>" }); let osmMap = L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { maxZoom: 19, attribution: "&copy; <a href='http://openstreetmap.org'>OpenStreetMap</a> Contributors" }); // add circle let buffer = L.circle([lat, lon], { color: "#000", fillOpacity: 0.0, radius: radius }); let buffer2 = L.circle([lat_mz, lon_mz], { color: "#000", fillOpacity: 0.0, radius: radius }); let wikipedia = L.layerGroup(); let PlaceOfWorship = L.layerGroup(); let Restaurant = L.layerGroup(); let getTypesFromDBpedia = (json) => { let types = "<br><br><b>types</b><br>"; $.ajax({ type: "GET", url: "http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=SELECT+*+WHERE+%7B+%3Fs+%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2FwikiPageID%3E+%22"+json.pageid+"%22%5E%5Exsd%3Ainteger+.+%3Fs+%3Fp+%3Fo+.%0D%0A%7D&format=application%2Fsparql-results%2Bjson&CXML_redir_for_subjs=121&CXML_redir_for_hrefs=&timeout=30000&run=+Run+Query+", async: false, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); }, success: function (data) { let bindings = data.results.bindings; for (var item in bindings) { if (bindings[item].p.value.includes("#type")) { if (bindings[item].o.value.includes("http://dbpedia.org/ontology/")) { let split = bindings[item].o.value.split("/"); types += split[split.length-1]+"<br>"; } } } } }); return types; }; var styleValencia = { "color": "#0000FF", "weight": 5, "opacity": 1.0, "fillOpacity": 0.8 }; // read valencia data from wikipedia api $.ajax({ type: "GET", url: "https://en.wikipedia.org/w/api.php?action=query&gsmaxdim=10000&list=geosearch&gslimit=1000&gsradius="+radius+"&gscoord="+lat+"|"+lon+"&continue&format=json&origin=*", async: false, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); }, success: function (data) { let geosearch = data.query.geosearch; for (var item in geosearch) { let point = turf.point([geosearch[item].lon, geosearch[item].lat]); let buffer = turf.buffer(point, 20, "meters"); let envelope = turf.envelope(buffer); let marker = L.geoJson(envelope, {style: styleValencia}); marker.properties = {}; marker.properties.wiki1 = geosearch[item]; marker.bindPopup("<a href='https://en.wikipedia.org/wiki/"+marker.properties.wiki1.title+"' target='_blank'>"+marker.properties.wiki1.title+"</a>"+getTypesFromDBpedia(geosearch[item])); wikipedia.addLayer(marker); } } }); var stylePlaceOfWorship = { "color": "#ff7800", "weight": 5, "opacity": 1.0, "fillOpacity": 0.8 }; // load place of worships via linkedgeodata.org $.ajax({ type: "GET", url: "http://linkedgeodata.org/sparql?default-graph-uri=http%3A%2F%2Flinkedgeodata.org&query=Prefix+rdfs%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23%3E%0D%0APrefix+ogc%3A+%3Chttp%3A%2F%2Fwww.opengis.net%2Font%2Fgeosparql%23%3E%0D%0APrefix+geom%3A+%3Chttp%3A%2F%2Fgeovocab.org%2Fgeometry%23%3E%0D%0APrefix+lgdo%3A+%3Chttp%3A%2F%2Flinkedgeodata.org%2Fontology%2F%3E%0D%0A%0D%0ASelect+%3Fitem+%3Flabel+%3Fgeo%0D%0AFrom+%3Chttp%3A%2F%2Flinkedgeodata.org%3E+%7B%0D%0A++%3Fitem%0D%0A++++a+lgdo%3A"+lgdtype+"+%3B%0D%0A++++rdfs%3Alabel+%3Flabel+%3B%0D%0A++++geom%3Ageometry+%5B%0D%0A++++++ogc%3AasWKT+%3Fgeo%0D%0A++++%5D+.%0D%0A+++%0D%0A++Filter+%28%0D%0A++++bif%3Ast_intersects+%28%3Fgeo%2C+bif%3Ast_point+%28"+lon_mz+"%2C+"+lat_mz+"%29%2C+"+radius_mz+"%29%0D%0A++%29+.%0D%0A%7D&format=application%2Fsparql-results%2Bjson&timeout=0&debug=on", async: false, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); }, success: function (data) { let bindings = data.results.bindings; for (var item in bindings) { // WKT TO GEOJSON via let geojson = wellknown.parse(bindings[item].geo.value); // LINESTRING TO POLYGON VIA turf if (bindings[item].geo.value.includes("LINESTRING")) { var coord = turf.getCoords(geojson); var line = turf.lineString(coord); var polygon = turf.lineStringToPolygon(line); geojson = polygon; } else if (bindings[item].geo.value.includes("POINT")) { let coord = turf.getCoords(geojson); let point = turf.point(coord); let buffer = turf.buffer(point, 10, "meters"); let envelope = turf.envelope(buffer); geojson = envelope; } let marker = L.geoJson(geojson, {style: stylePlaceOfWorship}); marker.properties = {}; marker.properties.item = bindings[item].item.value; marker.properties.label = bindings[item].label.value; marker.bindPopup("<i class='fa fa-bell' aria-hidden='true'></i><br><br>"+marker.properties.label); PlaceOfWorship.addLayer(marker); } } }); var styleRestaurant = { "color": "#447550", "weight": 5, "opacity": 1.0, "fillOpacity": 0.8 }; // load restaurants via linkedgeodata.org $.ajax({ type: "GET", url: "http://linkedgeodata.org/sparql?default-graph-uri=http%3A%2F%2Flinkedgeodata.org&query=Prefix+rdfs%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23%3E%0D%0APrefix+ogc%3A+%3Chttp%3A%2F%2Fwww.opengis.net%2Font%2Fgeosparql%23%3E%0D%0APrefix+geom%3A+%3Chttp%3A%2F%2Fgeovocab.org%2Fgeometry%23%3E%0D%0APrefix+lgdo%3A+%3Chttp%3A%2F%2Flinkedgeodata.org%2Fontology%2F%3E%0D%0A%0D%0ASelect+%3Fitem+%3Flabel+%3Fgeo%0D%0AFrom+%3Chttp%3A%2F%2Flinkedgeodata.org%3E+%7B%0D%0A++%3Fitem%0D%0A++++a+lgdo%3A"+lgdtype2+"+%3B%0D%0A++++rdfs%3Alabel+%3Flabel+%3B%0D%0A++++geom%3Ageometry+%5B%0D%0A++++++ogc%3AasWKT+%3Fgeo%0D%0A++++%5D+.%0D%0A+++%0D%0A++Filter+%28%0D%0A++++bif%3Ast_intersects+%28%3Fgeo%2C+bif%3Ast_point+%28"+lon_mz+"%2C+"+lat_mz+"%29%2C+"+radius_mz+"%29%0D%0A++%29+.%0D%0A%7D&format=application%2Fsparql-results%2Bjson&timeout=0&debug=on", async: false, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); }, success: function (data) { let bindings = data.results.bindings; for (var item in bindings) { // WKT TO GEOJSON via let geojson = wellknown.parse(bindings[item].geo.value); // LINESTRING TO POLYGON VIA turf if (bindings[item].geo.value.includes("LINESTRING")) { let coord = turf.getCoords(geojson); let line = turf.lineString(coord); let polygon = turf.lineStringToPolygon(line); geojson = polygon; } else if (bindings[item].geo.value.includes("POINT")) { let coord = turf.getCoords(geojson); let point = turf.point(coord); let buffer = turf.buffer(point, 10, "meters"); let envelope = turf.envelope(buffer); geojson = envelope; } let marker = L.geoJson(geojson, {style: styleRestaurant}); marker.properties = {}; marker.properties.item = bindings[item].item.value; marker.properties.label = bindings[item].label.value; marker.bindPopup("<i class='fa fa-glass' aria-hidden='true'></i><br><br>"+marker.properties.label); Restaurant.addLayer(marker); } } }); // init map let mymap = L.map("mapid", { center: [45.5, 4.8], zoom: 6, layers: [osmMap, buffer, wikipedia, buffer2, PlaceOfWorship, Restaurant] }); let baseMaps = { "Hot": hotMap, "OSM Mapnik": osmMap }; let overlays ={ "Buffer Wikipedia": buffer, "wikipedia": wikipedia, "Buffer LGD": buffer2, "LGD PlaceOfWorship": PlaceOfWorship, "LGD Restaurant": Restaurant }; L.control.layers(baseMaps, overlays).addTo(mymap);
add openroutemap and walking area for mainz
src/app.js
add openroutemap and walking area for mainz
<ide><path>rc/app.js <ide> import * as turf from "@turf/turf"; <ide> import "materialize-css"; <ide> <add>let ors_key = "58d904a497c67e00015b45fcd2e10661dfa14f2d46c679d259b00197"; <add> <ide> let lat = 39.4699075; <ide> let lon = -0.3762881000000107; <ide> let radius = 10000; <ide> let radius_mz = 10; <ide> let lgdtype = "PlaceOfWorship"; //Museum School PlaceOfWorship Restaurant <ide> let lgdtype2 = "Restaurant"; //Museum School PlaceOfWorship Restaurant <add>let range_mz_min = 25; <add>let range_mz = range_mz_min*60; <ide> <ide> // set tile layer <ide> let hotMap = L.tileLayer("http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", { <ide> let wikipedia = L.layerGroup(); <ide> let PlaceOfWorship = L.layerGroup(); <ide> let Restaurant = L.layerGroup(); <add>let walkingArea = L.layerGroup(); <ide> <ide> let getTypesFromDBpedia = (json) => { <ide> let types = "<br><br><b>types</b><br>"; <ide> } <ide> }); <ide> <add>var styleWalkingArea = { <add> "color": "grey", <add> "weight": 5, <add> "opacity": 1.0, <add> "fillOpacity": 0.8 <add>}; <add> <add>// load waking area via openrouteservice.org <add>$.ajax({ <add> type: "GET", <add> url: "https://api.openrouteservice.org/isochrones?locations="+lon_mz+"%2C"+lat_mz+"&profile=foot-walking&range_type=time&range="+range_mz+"&location_type=start&api_key="+ors_key, <add> async: false, <add> error: function (jqXHR, textStatus, errorThrown) { <add> alert(errorThrown); <add> }, <add> success: function (data) { <add> let marker = L.geoJson(data, {style: styleWalkingArea}); <add> marker.bindPopup(); <add> walkingArea.addLayer(marker); <add> } <add>}); <add> <ide> // init map <ide> let mymap = L.map("mapid", { <ide> center: [45.5, 4.8], <ide> zoom: 6, <del> layers: [osmMap, buffer, wikipedia, buffer2, PlaceOfWorship, Restaurant] <add> layers: [osmMap, buffer, wikipedia, buffer2, walkingArea, PlaceOfWorship, Restaurant] <ide> }); <ide> <ide> let baseMaps = { <ide> "wikipedia": wikipedia, <ide> "Buffer LGD": buffer2, <ide> "LGD PlaceOfWorship": PlaceOfWorship, <del> "LGD Restaurant": Restaurant <add> "LGD Restaurant": Restaurant, <add> "ORS WalkingArea 25min": walkingArea <ide> }; <ide> <ide> L.control.layers(baseMaps, overlays).addTo(mymap);
Java
mit
ee1b6d0a29d7c50b56ede85fa9c8d0e502dcc986
0
leomoldo/bunkerwar
package fr.leomoldo.android.bunkerwar; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import fr.leomoldo.android.bunkerwar.game.Bunker; import fr.leomoldo.android.bunkerwar.game.Landscape; /** * Created by leomoldo on 16/05/2016. */ public class GameView extends View { private final static float MAX_HEIGHT_RATIO_FOR_LANDSCAPE = 0.5f; private final static Double BUNKER_CANON_LENGTH = 30.0; public final static Float BUNKER_RADIUS = 17f; private final static Float BUNKER_STROKE_WIDTH = 10f; public final static Float BOMBSHELL_RADIUS = 5f; // Context. private Context mContext; // Model. private Landscape mLandscape; private Bunker mPlayerOneBunker; private Bunker mPlayerTwoBunker; private Float mBunkerPlayerOneX; private Float mBunkerPlayerOneY; private Float mBunkerPlayerTwoX; private Float mBunkerPlayerTwoY; private Float mBombShellX; private Float mBombShellY; // Paints. private Paint mLandscapePaint; private Paint mPlayerOneBunkerPaint; private Paint mPlayerTwoBunkerPaint; private Paint mBombShellPaint; public GameView(Context context) { this(context, null); } public GameView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public GameView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; this.setWillNotDraw(false); initializePaints(); } public void initializeNewGame(Landscape landscape, Bunker playerOneBunker, Bunker playerTwoBunker) { mLandscape = landscape; mPlayerOneBunker = playerOneBunker; mPlayerTwoBunker = playerTwoBunker; } public void showBombShell(float x, float y) { mBombShellX = x; mBombShellY = y; } public void hideBombShell() { mBombShellY = null; mBombShellY = null; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (canvas == null) return; if (mPlayerOneBunker != null) { drawPlayerOneBunker(canvas); } if (mPlayerTwoBunker != null) { drawPlayerTwoBunker(canvas); } if (mLandscape != null) { drawLandscape(canvas); } // TODO Draw BombShell if necessary (after Landscape). if (mBombShellX != null && mBombShellY != null) { drawBombShell(canvas, mBombShellX, mBombShellY); } } private void drawLandscape(Canvas canvas) { for (int i = 0; i < mLandscape.getNumberOfLandscapeSlices(); i++) { canvas.drawRect(i * getWidth() / mLandscape.getNumberOfLandscapeSlices(), getHeight() - getHeight() * MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(i), (i + 1) * getWidth() / mLandscape.getNumberOfLandscapeSlices(), getHeight(), mLandscapePaint); } } private void drawPlayerOneBunker(Canvas canvas) { if (mBunkerPlayerOneX == null) { setBunkerOneX(); } if (mBunkerPlayerOneY == null) { setBunkerOneY(); } drawBunker(canvas, mPlayerOneBunkerPaint, mBunkerPlayerOneX, mBunkerPlayerOneY, mPlayerOneBunker.getCanonAngleRadian(), true); } private void drawPlayerTwoBunker(Canvas canvas) { if (mBunkerPlayerTwoX == null) { setBunkerTwoX(); } if (mBunkerPlayerTwoY == null) { setBunkerTwoY(); } drawBunker(canvas, mPlayerTwoBunkerPaint, mBunkerPlayerTwoX, mBunkerPlayerTwoY, mPlayerTwoBunker.getCanonAngleRadian(), false); } private void drawBunker(Canvas canvas, Paint paint, float x, float y, double canonAngleRadian, boolean isCanonSetLeftToRight) { // Draw a circle and a rectangle for the bunker. canvas.drawCircle(x, y, BUNKER_RADIUS, paint); canvas.drawRect(x - BUNKER_RADIUS, y, x + BUNKER_RADIUS, getHeight(), paint); // Draw the canon of the bunker. float lengthX = (float) (BUNKER_CANON_LENGTH * Math.cos(canonAngleRadian)); float lengthY = (float) (-BUNKER_CANON_LENGTH * Math.sin(canonAngleRadian)); if (!isCanonSetLeftToRight) { lengthX = -lengthX; } canvas.drawLine(x, y, x + lengthX, y + lengthY, paint); } private void drawBombShell(Canvas canvas, float x, float y) { canvas.drawCircle(x, y, BOMBSHELL_RADIUS, mBombShellPaint); } private void initializePaints() { // Landscape. mLandscapePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mLandscapePaint.setColor(mContext.getResources().getColor(R.color.green_land_slice)); // Bunker One. mPlayerOneBunkerPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPlayerOneBunkerPaint.setColor(Color.RED); mPlayerOneBunkerPaint.setStyle(Paint.Style.FILL); mPlayerOneBunkerPaint.setStrokeCap(Paint.Cap.BUTT); mPlayerOneBunkerPaint.setStrokeWidth(BUNKER_STROKE_WIDTH); // Bunker Two. mPlayerTwoBunkerPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPlayerTwoBunkerPaint.setColor(Color.YELLOW); mPlayerTwoBunkerPaint.setStyle(Paint.Style.FILL); mPlayerTwoBunkerPaint.setStrokeCap(Paint.Cap.BUTT); mPlayerTwoBunkerPaint.setStrokeWidth(BUNKER_STROKE_WIDTH); // Bombshell. mBombShellPaint = new Paint(Paint.ANTI_ALIAS_FLAG); /*if (mBunker.isPlayerOne()) { mBombShellPaint.setColor(Color.RED); } else { mBombShellPaint.setColor(Color.YELLOW); }*/ mBombShellPaint.setColor(Color.BLACK); // TODO Debug only. mBombShellPaint.setStyle(Paint.Style.FILL); } private void setBunkerOneX() { float landSliceWidth = getWidth() / mLandscape.getNumberOfLandscapeSlices(); mBunkerPlayerOneX = Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER * landSliceWidth; } private void setBunkerOneY() { mBunkerPlayerOneY = getHeight() - getHeight() * MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER) - BUNKER_RADIUS; } private void setBunkerTwoX() { float landSliceWidth = getWidth() / mLandscape.getNumberOfLandscapeSlices(); mBunkerPlayerTwoX = getWidth() - landSliceWidth * Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER; } private void setBunkerTwoY() { mBunkerPlayerTwoY = getHeight() - getHeight() * MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(mLandscape.getNumberOfLandscapeSlices() - 1 - Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER) - BUNKER_RADIUS; } }
app/src/main/java/fr/leomoldo/android/bunkerwar/GameView.java
package fr.leomoldo.android.bunkerwar; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import fr.leomoldo.android.bunkerwar.game.Bunker; import fr.leomoldo.android.bunkerwar.game.Landscape; /** * Created by leomoldo on 16/05/2016. */ public class GameView extends View { private final static float MAX_HEIGHT_RATIO_FOR_LANDSCAPE = 0.5f; private final static Double BUNKER_CANON_LENGTH = 30.0; public final static Float BUNKER_RADIUS = 17f; private final static Float BUNKER_STROKE_WIDTH = 10f; public final static Float BOMBSHELL_RADIUS = 5f; // Context. private Context mContext; // Model. private Landscape mLandscape; private Bunker mPlayerOneBunker; private Bunker mPlayerTwoBunker; private Float mBunkerPlayerOneX; private Float mBunkerPlayerOneY; private Float mBunkerPlayerTwoX; private Float mBunkerPlayerTwoY; // Paints. private Paint mLandscapePaint; private Paint mPlayerOneBunkerPaint; private Paint mPlayerTwoBunkerPaint; private Paint mBombShellPaint; public GameView(Context context) { this(context, null); } public GameView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public GameView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; this.setWillNotDraw(false); initializePaints(); } public void initializeNewGame(Landscape landscape, Bunker playerOneBunker, Bunker playerTwoBunker) { mLandscape = landscape; mPlayerOneBunker = playerOneBunker; mPlayerTwoBunker = playerTwoBunker; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (canvas == null) return; if (mPlayerOneBunker != null) { drawPlayerOneBunker(canvas); } if (mPlayerTwoBunker != null) { drawPlayerTwoBunker(canvas); } if (mLandscape != null) { drawLandscape(canvas); } // TODO Draw BombShell if necessary (after Landscape). } private void drawLandscape(Canvas canvas) { for (int i = 0; i < mLandscape.getNumberOfLandscapeSlices(); i++) { canvas.drawRect(i * getWidth() / mLandscape.getNumberOfLandscapeSlices(), getHeight() - getHeight() * MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(i), (i + 1) * getWidth() / mLandscape.getNumberOfLandscapeSlices(), getHeight(), mLandscapePaint); } } private void drawPlayerOneBunker(Canvas canvas) { if (mBunkerPlayerOneX == null) { setBunkerOneX(); } if (mBunkerPlayerOneY == null) { setBunkerOneY(); } drawBunker(canvas, mPlayerOneBunkerPaint, mBunkerPlayerOneX, mBunkerPlayerOneY, mPlayerOneBunker.getCanonAngleRadian(), true); } private void drawPlayerTwoBunker(Canvas canvas) { if (mBunkerPlayerTwoX == null) { setBunkerTwoX(); } if (mBunkerPlayerTwoY == null) { setBunkerTwoY(); } drawBunker(canvas, mPlayerTwoBunkerPaint, mBunkerPlayerTwoX, mBunkerPlayerTwoY, mPlayerTwoBunker.getCanonAngleRadian(), false); } private void drawBunker(Canvas canvas, Paint paint, float x, float y, double canonAngleRadian, boolean isCanonSetLeftToRight) { // Draw a circle and a rectangle for the bunker. canvas.drawCircle(x, y, BUNKER_RADIUS, paint); canvas.drawRect(x - BUNKER_RADIUS, y, x + BUNKER_RADIUS, getHeight(), paint); // Draw the canon of the bunker. float lengthX = (float) (BUNKER_CANON_LENGTH * Math.cos(canonAngleRadian)); float lengthY = (float) (-BUNKER_CANON_LENGTH * Math.sin(canonAngleRadian)); if (!isCanonSetLeftToRight) { lengthX = -lengthX; } canvas.drawLine(x, y, x + lengthX, y + lengthY, paint); } private void drawBombShell(Canvas canvas, float x, float y) { canvas.drawCircle(x, y, BOMBSHELL_RADIUS, mBombShellPaint); } private void initializePaints() { // Landscape. mLandscapePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mLandscapePaint.setColor(mContext.getResources().getColor(R.color.green_land_slice)); // Bunker One. mPlayerOneBunkerPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPlayerOneBunkerPaint.setColor(Color.RED); mPlayerOneBunkerPaint.setStyle(Paint.Style.FILL); mPlayerOneBunkerPaint.setStrokeCap(Paint.Cap.BUTT); mPlayerOneBunkerPaint.setStrokeWidth(BUNKER_STROKE_WIDTH); // Bunker Two. mPlayerTwoBunkerPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPlayerTwoBunkerPaint.setColor(Color.YELLOW); mPlayerTwoBunkerPaint.setStyle(Paint.Style.FILL); mPlayerTwoBunkerPaint.setStrokeCap(Paint.Cap.BUTT); mPlayerTwoBunkerPaint.setStrokeWidth(BUNKER_STROKE_WIDTH); // Bombshell. mBombShellPaint = new Paint(Paint.ANTI_ALIAS_FLAG); /*if (mBunker.isPlayerOne()) { mBombShellPaint.setColor(Color.RED); } else { mBombShellPaint.setColor(Color.YELLOW); }*/ mBombShellPaint.setColor(Color.BLACK); // TODO Debug only. mBombShellPaint.setStyle(Paint.Style.FILL); } private void setBunkerOneX() { float landSliceWidth = getWidth() / mLandscape.getNumberOfLandscapeSlices(); mBunkerPlayerOneX = Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER * landSliceWidth; } private void setBunkerOneY() { mBunkerPlayerOneY = getHeight() - getHeight() * MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER) - BUNKER_RADIUS; } private void setBunkerTwoX() { float landSliceWidth = getWidth() / mLandscape.getNumberOfLandscapeSlices(); mBunkerPlayerTwoX = getWidth() - landSliceWidth * Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER; } private void setBunkerTwoY() { mBunkerPlayerTwoY = getHeight() - getHeight() * MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(mLandscape.getNumberOfLandscapeSlices() - 1 - Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER) - BUNKER_RADIUS; } }
Implemented bombshell drawing management interface in GameView.
app/src/main/java/fr/leomoldo/android/bunkerwar/GameView.java
Implemented bombshell drawing management interface in GameView.
<ide><path>pp/src/main/java/fr/leomoldo/android/bunkerwar/GameView.java <ide> private Float mBunkerPlayerTwoX; <ide> private Float mBunkerPlayerTwoY; <ide> <add> private Float mBombShellX; <add> private Float mBombShellY; <add> <ide> // Paints. <ide> private Paint mLandscapePaint; <ide> private Paint mPlayerOneBunkerPaint; <ide> mPlayerTwoBunker = playerTwoBunker; <ide> } <ide> <add> public void showBombShell(float x, float y) { <add> mBombShellX = x; <add> mBombShellY = y; <add> } <add> <add> public void hideBombShell() { <add> mBombShellY = null; <add> mBombShellY = null; <add> } <add> <ide> @Override <ide> protected void onDraw(Canvas canvas) { <ide> <ide> } <ide> <ide> // TODO Draw BombShell if necessary (after Landscape). <add> <add> if (mBombShellX != null && mBombShellY != null) { <add> drawBombShell(canvas, mBombShellX, mBombShellY); <add> } <ide> } <ide> <ide> private void drawLandscape(Canvas canvas) {
JavaScript
mit
d35966755d63d774a2ddbcdabdf76cfa3d23939d
0
mapzen/documentation,mapzen/documentation,mapzen/mapzen-docs-generator,mapzen/documentation,mapzen/mapzen-docs-generator,mapzen/mapzen-docs-generator,mapzen/mapzen-docs-generator,mapzen/documentation
function getSearchTerm() { var sPageURL = window.location.search.substring(1); var sURLVariables = sPageURL.split('&'); for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); if (sParameterName[0] == 'q') { return sParameterName[1]; } } } $(document).ready(function () { var search_term = getSearchTerm() var $search_modal = $('#mkdocs_search_modal') var $docContainer = $('.documentation-container') var $searchResults = $('#mkdocs-search-results') var $searchInput = $('#mkdocs-search-query') var $nav = $('nav') var $toc = $('#toc') var $docContent = $('.documentation-content').parent() var affixState = false if (search_term) { $searchInput.val(search_term) } var selectedPosition $searchInput.on('keyup', function (e) { // Need to wait a bit for search function to finish populating our results setTimeout(function () { // See if anything is inside the search results if ($.trim($searchResults.html()) !== '') { $searchResults.show() $searchResults.css('max-height', window.innerHeight - $searchResults[0].getBoundingClientRect().top - 100) var input = $searchInput.val().trim() var list = $searchResults.find('article') if (list.length > 0) { // var highlight = function (text, focus) { // var r = RegExp('(' + focus + ')', 'gi'); // return text.replace(r, '<strong>$1</strong>'); // } // var html = $searchResults.html() // $searchResults.html(highlight(html, input)) // Now reapply selection if (selectedPosition) { list[selectedPosition].addClass('selected') } } } else { $searchResults.hide() } }, 0) }) /* DISABLED, this doesn't work well because other search JS overwrites selection $searchInput.on('keydown', function (e) { // Ignore key results are not visible if (!$searchResults.is(':visible')) { return; } var selected = $searchResults.find('article.selected')[0] var list = $searchResults.find('article') for (var i = 0; i < list.length; i++) { if (list[i] === selected) { selectedPosition = i; break; } } switch (e.keyCode) { // 13 = enter case 13: e.preventDefault() if (selected) { findAndOpenLink(selected) } break; // 38 = up arrow case 38: e.preventDefault() if (selected) { $(selected).removeClass('selected') } var previousItem = list[selectedPosition - 1]; if (selected && previousItem) { $(previousItem).addClass('selected'); } else { $(list[list.length - 1]).addClass('selected'); } break; // 40 = down arrow case 40: e.preventDefault() if (selected) { $(selected).removeClass('selected'); } var nextItem = list[selectedPosition + 1]; if (selected && nextItem) { $(nextItem).addClass('selected'); } else { $(list[0]).addClass('selected'); } break; // all other keys default: break; } }) */ $search_modal.on('blur', function () { resetSearchResults(); }) $searchResults.on('click', 'article', function (e) { findAndOpenLink(this); // In case it just jumps down the page resetSearchResults(); }) function findAndOpenLink (articleEl) { var link = $(articleEl).find('a').attr('href') window.location.href = link; } function resetSearchResults () { $searchResults.empty(); $searchResults.hide(); } // Highlight.js hljs.initHighlightingOnLoad(); $('table').addClass('table'); // Affix for side nav bar // Don't turn on affix if the TOC height is greater than // document content, to prevent positioning bugs if ($toc.height() < $docContent.height()) { $toc.affix({ offset: { top: function () { return $docContainer.offset().top - $nav.height() }, bottom: function () { return $(document).height() - $docContainer.offset().top - $docContainer.outerHeight(true) } } }) // Record that affix is on affixState = true } $('.toc-subnav-toggle').on('click', function (e) { e.preventDefault() var $el = $(this).next('ul') $el.toggleClass('toc-expand') // Recalc affix position after expand transition finishes if (affixState === true) { $el.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function (e) { $toc.affix('checkPosition') }) } }) // Guarantee only one active thing is up var activeEls = $('.toc li.active') activeEls.each(function (index) { if (index + 1 !== activeEls.length) { $(activeEls[index]).removeClass('active') } }) }); $('body').scrollspy({ target: '.toc', offset: 10 }); /* Prevent disabled links from causing a page reload */ $('li.disabled a').click(function(event) { event.preventDefault(); })
theme/js/base.js
function getSearchTerm() { var sPageURL = window.location.search.substring(1); var sURLVariables = sPageURL.split('&'); for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); if (sParameterName[0] == 'q') { return sParameterName[1]; } } } $(document).ready(function () { var search_term = getSearchTerm() var $search_modal = $('#mkdocs_search_modal') var $docContainer = $('.documentation-container') var $searchResults = $('#mkdocs-search-results') var $searchInput = $('#mkdocs-search-query') var $nav = $('nav') var $toc = $('#toc') var $docContent = $('.documentation-content').parent() var affixState = false if (search_term) { $searchInput.val(search_term) } var selectedPosition $searchInput.on('keyup', function (e) { // Need to wait a bit for search function to finish populating our results setTimeout(function () { // See if anything is inside the search results if ($.trim($searchResults.html()) !== '') { $searchResults.show() $searchResults.css('max-height', window.innerHeight - $searchResults[0].getBoundingClientRect().top - 100) var input = $searchInput.val().trim() var list = $searchResults.find('article') if (list.length > 0) { var highlight = function (text, focus) { var r = RegExp('(' + focus + ')', 'gi'); return text.replace(r, '<strong>$1</strong>'); } var html = $searchResults.html() $searchResults.html(highlight(html, input)) // Now reapply selection if (selectedPosition) { list[selectedPosition].addClass('selected') } } } else { $searchResults.hide() } }, 0) }) /* DISABLED, this doesn't work well because other search JS overwrites selection $searchInput.on('keydown', function (e) { // Ignore key results are not visible if (!$searchResults.is(':visible')) { return; } var selected = $searchResults.find('article.selected')[0] var list = $searchResults.find('article') for (var i = 0; i < list.length; i++) { if (list[i] === selected) { selectedPosition = i; break; } } switch (e.keyCode) { // 13 = enter case 13: e.preventDefault() if (selected) { findAndOpenLink(selected) } break; // 38 = up arrow case 38: e.preventDefault() if (selected) { $(selected).removeClass('selected') } var previousItem = list[selectedPosition - 1]; if (selected && previousItem) { $(previousItem).addClass('selected'); } else { $(list[list.length - 1]).addClass('selected'); } break; // 40 = down arrow case 40: e.preventDefault() if (selected) { $(selected).removeClass('selected'); } var nextItem = list[selectedPosition + 1]; if (selected && nextItem) { $(nextItem).addClass('selected'); } else { $(list[0]).addClass('selected'); } break; // all other keys default: break; } }) */ $search_modal.on('blur', function () { resetSearchResults(); }) $searchResults.on('click', 'article', function (e) { findAndOpenLink(this); // In case it just jumps down the page resetSearchResults(); }) function findAndOpenLink (articleEl) { var link = $(articleEl).find('a').attr('href') window.location.href = link; } function resetSearchResults () { $searchResults.empty(); $searchResults.hide(); } // Highlight.js hljs.initHighlightingOnLoad(); $('table').addClass('table'); // Affix for side nav bar // Don't turn on affix if the TOC height is greater than // document content, to prevent positioning bugs if ($toc.height() < $docContent.height()) { $toc.affix({ offset: { top: function () { return $docContainer.offset().top - $nav.height() }, bottom: function () { return $(document).height() - $docContainer.offset().top - $docContainer.outerHeight(true) } } }) // Record that affix is on affixState = true } $('.toc-subnav-toggle').on('click', function (e) { e.preventDefault() var $el = $(this).next('ul') $el.toggleClass('toc-expand') // Recalc affix position after expand transition finishes if (affixState === true) { $el.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function (e) { $toc.affix('checkPosition') }) } }) // Guarantee only one active thing is up var activeEls = $('.toc li.active') activeEls.each(function (index) { if (index + 1 !== activeEls.length) { $(activeEls[index]).removeClass('active') } }) }); $('body').scrollspy({ target: '.toc', offset: 10 }); /* Prevent disabled links from causing a page reload */ $('li.disabled a').click(function(event) { event.preventDefault(); })
Do not highlight search results because it is buggy. (#62)
theme/js/base.js
Do not highlight search results because it is buggy. (#62)
<ide><path>heme/js/base.js <ide> var list = $searchResults.find('article') <ide> <ide> if (list.length > 0) { <del> var highlight = function (text, focus) { <del> var r = RegExp('(' + focus + ')', 'gi'); <del> return text.replace(r, '<strong>$1</strong>'); <del> } <add> // var highlight = function (text, focus) { <add> // var r = RegExp('(' + focus + ')', 'gi'); <add> // return text.replace(r, '<strong>$1</strong>'); <add> // } <ide> <del> var html = $searchResults.html() <del> $searchResults.html(highlight(html, input)) <add> // var html = $searchResults.html() <add> // $searchResults.html(highlight(html, input)) <ide> <ide> // Now reapply selection <ide> if (selectedPosition) {
Java
epl-1.0
4adf8e3bd55dff49a76c8e010fa6b3798d7f077a
0
Mark-Booth/daq-eclipse,Mark-Booth/daq-eclipse,Mark-Booth/daq-eclipse
package org.eclipse.scanning.example.scannable; import java.text.MessageFormat; import org.eclipse.dawnsci.nexus.INexusDevice; import org.eclipse.dawnsci.nexus.NXobject; import org.eclipse.dawnsci.nexus.NXpositioner; import org.eclipse.dawnsci.nexus.NexusException; import org.eclipse.dawnsci.nexus.NexusNodeFactory; import org.eclipse.dawnsci.nexus.NexusScanInfo; import org.eclipse.dawnsci.nexus.builder.NexusObjectProvider; import org.eclipse.dawnsci.nexus.builder.NexusObjectWrapper; import org.eclipse.january.dataset.Dataset; import org.eclipse.january.dataset.DatasetFactory; import org.eclipse.january.dataset.ILazyWriteableDataset; import org.eclipse.january.dataset.SliceND; import org.eclipse.scanning.api.IScanAttributeContainer; import org.eclipse.scanning.api.points.IPosition; import org.eclipse.scanning.api.points.Scalar; import org.eclipse.scanning.api.scan.rank.IScanRankService; import org.eclipse.scanning.api.scan.rank.IScanSlice; /** * * A class to wrap any IScannable as a positioner and then write to a nexus file * as the positions are set during the scan. * * @author Matthew Gerring * */ public class MockNeXusScannable extends MockScannable implements INexusDevice<NXpositioner> { public static final String FIELD_NAME_DEMAND_VALUE = NXpositioner.NX_VALUE + "_demand"; private ILazyWriteableDataset lzDemand; private ILazyWriteableDataset lzValue; public MockNeXusScannable() { super(); } public MockNeXusScannable(String name, double d, int level) { super(name, d, level); } public MockNeXusScannable(String name, double d, int level, String unit) { super(name, d, level, unit); } public NexusObjectProvider<NXpositioner> getNexusProvider(NexusScanInfo info) throws NexusException { final NXpositioner positioner = NexusNodeFactory.createNXpositioner(); positioner.setNameScalar(getName()); if (info.isMetadataScannable(getName())) { positioner.setField(FIELD_NAME_DEMAND_VALUE, getPosition().doubleValue()); positioner.setValueScalar(getPosition().doubleValue()); } else { this.lzDemand = positioner.initializeLazyDataset(FIELD_NAME_DEMAND_VALUE, 1, Double.class); lzDemand.setChunking(new int[]{1}); this.lzValue = positioner.initializeLazyDataset(NXpositioner.NX_VALUE, info.getRank(), Double.class); lzValue.setChunking(info.createChunk(1)); // TODO Might be slow, need to check this } registerAttributes(positioner, this); NexusObjectWrapper<NXpositioner> nexusDelegate = new NexusObjectWrapper<>( getName(), positioner, NXpositioner.NX_VALUE); nexusDelegate.setDefaultAxisDataFieldName(FIELD_NAME_DEMAND_VALUE); return nexusDelegate; } public void setPosition(Number value, IPosition position) throws Exception { if (value!=null) { int index = position!=null ? position.getIndex(getName()) : -1; if (isRealisticMove()) { value = doRealisticMove(value, index, -1); } this.position = value; delegate.firePositionPerformed(-1, new Scalar(getName(), index, value.doubleValue())); } if (position!=null) write(value, getPosition(), position); } private void write(Number demand, Number actual, IPosition loc) throws Exception { if (lzValue==null) return; if (actual!=null) { // write actual position final Dataset newActualPositionData = DatasetFactory.createFromObject(actual); IScanSlice rslice = IScanRankService.getScanRankService().createScanSlice(loc); SliceND sliceND = new SliceND(lzValue.getShape(), lzValue.getMaxShape(), rslice.getStart(), rslice.getStop(), rslice.getStep()); lzValue.setSlice(null, newActualPositionData, sliceND); } if (lzDemand==null) return; if (demand!=null) { int index = loc.getIndex(getName()); if (index<0) { throw new Exception("Incorrect data index for scan for value of '"+getName()+"'. The index is "+index); } final int[] startPos = new int[] { index }; final int[] stopPos = new int[] { index + 1 }; // write demand position final Dataset newDemandPositionData = DatasetFactory.createFromObject(demand); lzDemand.setSlice(null, newDemandPositionData, startPos, stopPos, null); } } /** * Add the attributes for the given attribute container into the given nexus object. * @param positioner * @param container * @throws NexusException if the attributes could not be added for any reason */ private static void registerAttributes(NXobject nexusObject, IScanAttributeContainer container) throws NexusException { // We create the attributes, if any nexusObject.setField("name", container.getName()); if (container.getScanAttributeNames()!=null) for(String attrName : container.getScanAttributeNames()) { try { nexusObject.setField(attrName, container.getScanAttribute(attrName)); } catch (Exception e) { throw new NexusException(MessageFormat.format( "An exception occurred attempting to get the value of the attribute ''{0}'' for the device ''{1}''", container.getName(), attrName)); } } } }
org.eclipse.scanning.example/src/org/eclipse/scanning/example/scannable/MockNeXusScannable.java
package org.eclipse.scanning.example.scannable; import java.text.MessageFormat; import org.eclipse.dawnsci.nexus.INexusDevice; import org.eclipse.dawnsci.nexus.NXobject; import org.eclipse.dawnsci.nexus.NXpositioner; import org.eclipse.dawnsci.nexus.NexusException; import org.eclipse.dawnsci.nexus.NexusNodeFactory; import org.eclipse.dawnsci.nexus.NexusScanInfo; import org.eclipse.dawnsci.nexus.builder.NexusObjectProvider; import org.eclipse.dawnsci.nexus.builder.NexusObjectWrapper; import org.eclipse.january.dataset.Dataset; import org.eclipse.january.dataset.DatasetFactory; import org.eclipse.january.dataset.ILazyWriteableDataset; import org.eclipse.january.dataset.SliceND; import org.eclipse.scanning.api.IScanAttributeContainer; import org.eclipse.scanning.api.points.IPosition; import org.eclipse.scanning.api.points.Scalar; import org.eclipse.scanning.api.scan.rank.IScanRankService; import org.eclipse.scanning.api.scan.rank.IScanSlice; /** * * A class to wrap any IScannable as a positioner and then write to a nexus file * as the positions are set during the scan. * * @author Matthew Gerring * */ public class MockNeXusScannable extends MockScannable implements INexusDevice<NXpositioner> { private ILazyWriteableDataset lzDemand; private ILazyWriteableDataset lzValue; public MockNeXusScannable() { super(); } public MockNeXusScannable(String name, double d, int level) { super(name, d, level); } public MockNeXusScannable(String name, double d, int level, String unit) { super(name, d, level, unit); } public NexusObjectProvider<NXpositioner> getNexusProvider(NexusScanInfo info) throws NexusException { final NXpositioner positioner = NexusNodeFactory.createNXpositioner(); positioner.setNameScalar(getName()); String fieldNameDemand = getName() + "_demand"; if (info.isMetadataScannable(getName())) { positioner.setField(fieldNameDemand, getPosition().doubleValue()); positioner.setValueScalar(getPosition().doubleValue()); } else { this.lzDemand = positioner.initializeLazyDataset(fieldNameDemand, 1, Double.class); lzDemand.setChunking(new int[]{1}); this.lzValue = positioner.initializeLazyDataset(NXpositioner.NX_VALUE, info.getRank(), Double.class); lzValue.setChunking(info.createChunk(1)); // TODO Might be slow, need to check this } registerAttributes(positioner, this); NexusObjectWrapper<NXpositioner> nexusDelegate = new NexusObjectWrapper<>( getName(), positioner, NXpositioner.NX_VALUE); nexusDelegate.setDefaultAxisDataFieldName(fieldNameDemand); return nexusDelegate; } public void setPosition(Number value, IPosition position) throws Exception { if (value!=null) { int index = position!=null ? position.getIndex(getName()) : -1; if (isRealisticMove()) { value = doRealisticMove(value, index, -1); } this.position = value; delegate.firePositionPerformed(-1, new Scalar(getName(), index, value.doubleValue())); } if (position!=null) write(value, getPosition(), position); } private void write(Number demand, Number actual, IPosition loc) throws Exception { if (lzValue==null) return; if (actual!=null) { // write actual position final Dataset newActualPositionData = DatasetFactory.createFromObject(actual); IScanSlice rslice = IScanRankService.getScanRankService().createScanSlice(loc); SliceND sliceND = new SliceND(lzValue.getShape(), lzValue.getMaxShape(), rslice.getStart(), rslice.getStop(), rslice.getStep()); lzValue.setSlice(null, newActualPositionData, sliceND); } if (lzDemand==null) return; if (demand!=null) { int index = loc.getIndex(getName()); if (index<0) { throw new Exception("Incorrect data index for scan for value of '"+getName()+"'. The index is "+index); } final int[] startPos = new int[] { index }; final int[] stopPos = new int[] { index + 1 }; // write demand position final Dataset newDemandPositionData = DatasetFactory.createFromObject(demand); lzDemand.setSlice(null, newDemandPositionData, startPos, stopPos, null); } } /** * Add the attributes for the given attribute container into the given nexus object. * @param positioner * @param container * @throws NexusException if the attributes could not be added for any reason */ private static void registerAttributes(NXobject nexusObject, IScanAttributeContainer container) throws NexusException { // We create the attributes, if any nexusObject.setField("name", container.getName()); if (container.getScanAttributeNames()!=null) for(String attrName : container.getScanAttributeNames()) { try { nexusObject.setField(attrName, container.getScanAttribute(attrName)); } catch (Exception e) { throw new NexusException(MessageFormat.format( "An exception occurred attempting to get the value of the attribute ''{0}'' for the device ''{1}''", container.getName(), attrName)); } } } }
Reverted scannable value name change http://jira.diamond.ac.uk/browse/DAQ-244
org.eclipse.scanning.example/src/org/eclipse/scanning/example/scannable/MockNeXusScannable.java
Reverted scannable value name change
<ide><path>rg.eclipse.scanning.example/src/org/eclipse/scanning/example/scannable/MockNeXusScannable.java <ide> */ <ide> public class MockNeXusScannable extends MockScannable implements INexusDevice<NXpositioner> { <ide> <add> public static final String FIELD_NAME_DEMAND_VALUE = NXpositioner.NX_VALUE + "_demand"; <add> <ide> private ILazyWriteableDataset lzDemand; <ide> private ILazyWriteableDataset lzValue; <ide> <ide> final NXpositioner positioner = NexusNodeFactory.createNXpositioner(); <ide> positioner.setNameScalar(getName()); <ide> <del> String fieldNameDemand = getName() + "_demand"; <del> <ide> if (info.isMetadataScannable(getName())) { <del> positioner.setField(fieldNameDemand, getPosition().doubleValue()); <add> positioner.setField(FIELD_NAME_DEMAND_VALUE, getPosition().doubleValue()); <ide> positioner.setValueScalar(getPosition().doubleValue()); <ide> } else { <del> this.lzDemand = positioner.initializeLazyDataset(fieldNameDemand, 1, Double.class); <add> this.lzDemand = positioner.initializeLazyDataset(FIELD_NAME_DEMAND_VALUE, 1, Double.class); <ide> lzDemand.setChunking(new int[]{1}); <ide> <ide> this.lzValue = positioner.initializeLazyDataset(NXpositioner.NX_VALUE, info.getRank(), Double.class); <ide> <ide> NexusObjectWrapper<NXpositioner> nexusDelegate = new NexusObjectWrapper<>( <ide> getName(), positioner, NXpositioner.NX_VALUE); <del> nexusDelegate.setDefaultAxisDataFieldName(fieldNameDemand); <add> nexusDelegate.setDefaultAxisDataFieldName(FIELD_NAME_DEMAND_VALUE); <ide> return nexusDelegate; <ide> } <ide>
Java
bsd-3-clause
6c2b5c72040ba8e49bbf907459ef616bc2d4363d
0
lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon
/* * $Id: LockssRepositoryImpl.java,v 1.53 2004-04-27 19:40:12 tlipkis Exp $ */ /* Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University, all rights reserved. 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 STANFORD UNIVERSITY 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. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.repository; import java.io.*; import java.net.*; import java.util.*; import org.lockss.app.*; import org.lockss.daemon.*; import org.lockss.plugin.*; import org.lockss.util.*; import org.apache.commons.collections.LRUMap; import org.apache.commons.collections.ReferenceMap; /** * LockssRepository is used to organize the urls being cached. * It keeps a memory cache of the most recently used nodes as a * least-recently-used map, and also caches weak references to the instances * as they're doled out. This ensures that two instances of the same node are * never created, as the weak references only disappear when the object is * finalized (they go to null when the last hard reference is gone, then are * removed from the cache on finalize()). */ public class LockssRepositoryImpl extends BaseLockssManager implements LockssRepository { /** * Configuration parameter name for Lockss cache location. */ public static final String PARAM_CACHE_LOCATION = Configuration.PREFIX + "cache.location"; /** * Name of top directory in which the urls are cached. */ public static final String CACHE_ROOT_NAME = "cache"; // needed only for unit tests static String cacheLocation = null; // used for name mapping static HashMap nameMap = null; // starts with a '#' so no possibility of clashing with a URL static final String AU_ID_FILE = "#au_id_file"; static final String AU_ID_PROP = "au.id"; static final String PLUGIN_ID_PROP = "plugin.id"; static final char ESCAPE_CHAR = '#'; static final String ESCAPE_STR = "#"; static final char ENCODED_SEPARATOR_CHAR = 's'; static final String INITIAL_PLUGIN_DIR = String.valueOf((char)('a'-1)); static String lastPluginDir = INITIAL_PLUGIN_DIR; /** * Parameter for maximum number of node instances to cache. This can be * fairly small because there typically isn't need for repeated access to * the same nodes over a short time. */ public static final String PARAM_MAX_LRUMAP_SIZE = Configuration.PREFIX + "cache.max.lrumap.size"; private static final int DEFAULT_MAX_LRUMAP_SIZE = 100; // this contains a '#' so that it's not defeatable by strings which // match the prefix in a url (like '../tmp/') private static final String TEST_PREFIX = "/#tmp"; private String rootLocation; private LRUMap nodeCache; private int nodeCacheSize = DEFAULT_MAX_LRUMAP_SIZE; private ReferenceMap refMap; private int cacheHits = 0; private int cacheMisses = 0; private int refHits = 0; private int refMisses = 0; private static Logger logger = Logger.getLogger("LockssRepository"); LockssRepositoryImpl(String rootPath) { rootLocation = rootPath; if (!rootLocation.endsWith(File.separator)) { // this shouldn't happen rootLocation += File.separator; } nodeCache = new LRUMap(nodeCacheSize); refMap = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.WEAK); } public void stopService() { // mainly important in testing to blank this lastPluginDir = INITIAL_PLUGIN_DIR; nameMap = null; super.stopService(); } protected void setConfig(Configuration newConfig, Configuration prevConfig, Set changedKeys) { // at some point we'll have to respond to changes in the available disk // space list nodeCacheSize = newConfig.getInt(PARAM_MAX_LRUMAP_SIZE, DEFAULT_MAX_LRUMAP_SIZE); if (nodeCache.getMaximumSize() != nodeCacheSize) { nodeCache.setMaximumSize(nodeCacheSize); } } /** Called between initService() and startService(), then whenever the * AU's config changes. * @param auConfig the new configuration */ public void setAuConfig(Configuration auConfig) { } public RepositoryNode getNode(String url) throws MalformedURLException { return getNode(url, false); } public RepositoryNode createNewNode(String url) throws MalformedURLException { return getNode(url, true); } public void deleteNode(String url) throws MalformedURLException { RepositoryNode node = getNode(url, false); if (node!=null) { node.markAsDeleted(); } } public void deactivateNode(String url) throws MalformedURLException { RepositoryNode node = getNode(url, false); if (node!=null) { node.deactivateContent(); } } /** * This function returns a RepositoryNode with a canonicalized path. * @param url the url in String form * @param create true iff the node should be created if absent * @return RepositoryNode the node * @throws MalformedURLException */ private synchronized RepositoryNode getNode(String url, boolean create) throws MalformedURLException { String urlKey; boolean isAuUrl = false; if (AuUrl.isAuUrl(url)) { // path information is lost here, but is unimportant if it's an AuUrl urlKey = AuUrl.PROTOCOL; isAuUrl = true; } else { // create a canonical path, handling all illegal path traversal urlKey = canonicalizePath(url); } // check LRUMap cache for node RepositoryNode node = (RepositoryNode)nodeCache.get(urlKey); if (node!=null) { cacheHits++; return node; } else { cacheMisses++; } // check weak reference map for node node = (RepositoryNode)refMap.get(urlKey); if (node!=null) { refHits++; nodeCache.put(urlKey, node); return node; } else { refMisses++; } String nodeLocation; if (isAuUrl) { // base directory of ArchivalUnit nodeLocation = rootLocation; node = new AuNodeImpl(urlKey, nodeLocation, this); } else { // determine proper node location nodeLocation = LockssRepositoryImpl.mapUrlToFileLocation(rootLocation, urlKey); node = new RepositoryNodeImpl(urlKey, nodeLocation, this); } if (!create) { // if not creating, check for existence File nodeDir = new File(nodeLocation); if (!nodeDir.exists()) { // return null if the node doesn't exist and shouldn't be created return null; } if (!nodeDir.isDirectory()) { logger.error("Cache file not a directory: "+nodeLocation); throw new LockssRepository.RepositoryStateException("Invalid cache file."); } } // add to node cache and weak reference cache nodeCache.put(urlKey, node); refMap.put(urlKey, node); return node; } // functions for testing int getCacheHits() { return cacheHits; } int getCacheMisses() { return cacheMisses; } int getRefHits() { return refHits; } int getRefMisses() { return refMisses; } /** * This is called when a node is in an inconsistent state. It simply creates * some necessary directories and deactivates the node. Future polls should * restore it properly. * @param node the inconsistent node */ void deactivateInconsistentNode(RepositoryNodeImpl node) { logger.warning("Inconsistent node state found; node content deactivated."); if (!node.contentDir.exists()) { node.contentDir.mkdirs(); } // manually deactivate node.deactivateContent(); } /** * A method to remove any non-canonical '..' or '.' elements in the path, * as well as protecting against illegal path traversal. * @param url the raw url * @return String the canonicalized url * @throws MalformedURLException */ public static String canonicalizePath(String url) throws MalformedURLException { String canonUrl; try { URL testUrl = new URL(url); String path = testUrl.getPath(); // look for '.' or '..' elements if (path.indexOf("/.")>=0) { // check if path traversal is legal if (FileUtil.isLegalPath(path)) { // canonicalize to remove urls including '..' and '.' path = TEST_PREFIX + path; File testFile = new File(path); String canonPath = testFile.getCanonicalPath(); String sysDepPrefix = FileUtil.sysDepPath(TEST_PREFIX); int pathIndex = canonPath.indexOf(sysDepPrefix) + sysDepPrefix.length(); // reconstruct the url canonUrl = testUrl.getProtocol() + "://" + testUrl.getHost().toLowerCase() + FileUtil.sysIndepPath(canonPath.substring(pathIndex)); // restore the query, if any String query = testUrl.getQuery(); if (query!=null) { canonUrl += "?" + query; } } else { logger.error("Illegal URL detected: "+url); throw new MalformedURLException("Illegal URL detected."); } } else { // clean path, no testing needed canonUrl = url; } } catch (MalformedURLException e) { logger.warning("Can't canonicalize path: " + e); throw e; } catch (IOException e) { logger.warning("Can't canonicalize path: " + e); throw new MalformedURLException(url); } // canonicalize "dir" and "dir/" // XXX if these are ever two separate nodes, this is wrong if (canonUrl.endsWith(UrlUtil.URL_PATH_SEPARATOR)) { canonUrl = canonUrl.substring(0, canonUrl.length()-1); } return canonUrl; } // static calls /** * Factory method to create new LockssRepository instances. * @param au the {@link ArchivalUnit} * @return the new LockssRepository instance */ public static LockssRepository createNewLockssRepository(ArchivalUnit au) { // XXX needs to handle multiple disks/repository locations cacheLocation = Configuration.getParam(PARAM_CACHE_LOCATION); if (cacheLocation == null) { logger.error("Couldn't get " + PARAM_CACHE_LOCATION + " from Configuration"); throw new LockssRepository.RepositoryStateException( "Couldn't load param."); } cacheLocation = extendCacheLocation(cacheLocation); return new LockssRepositoryImpl( LockssRepositoryImpl.mapAuToFileLocation(cacheLocation, au)); } /** * Adds the 'cache' directory to the HD location. * @param cacheDir the root location. * @return String the extended location */ static String extendCacheLocation(String cacheDir) { StringBuffer buffer = new StringBuffer(cacheDir); if (!cacheDir.endsWith(File.separator)) { buffer.append(File.separator); } buffer.append(CACHE_ROOT_NAME); buffer.append(File.separator); return buffer.toString(); } /** * mapAuToFileLocation() is the method used to resolve {@link ArchivalUnit}s * into directory names. This maps a given au to directories, using the * cache root as the base. Given an au with PluginId of 'plugin' and AuId * of 'au', it would return the string '<rootLocation>/plugin/au/'. * @param rootLocation the root for all ArchivalUnits * @param au the ArchivalUnit to resolve * @return the directory location */ public static String mapAuToFileLocation(String rootLocation, ArchivalUnit au) { StringBuffer buffer = new StringBuffer(rootLocation); if (!rootLocation.endsWith(File.separator)) { buffer.append(File.separator); } getAuDir(au, buffer); buffer.append(File.separator); return buffer.toString(); } /** * mapUrlToFileLocation() is the method used to resolve urls into file names. * This maps a given url to a file location, using the au top directory as * the base. It creates directories which mirror the html string, so * 'http://www.journal.org/issue1/index.html' would be cached in the file: * <rootLocation>/www.journal.org/http/issue1/index.html * @param rootLocation the top directory for ArchivalUnit this URL is in * @param urlStr the url to translate * @return the url file location * @throws java.net.MalformedURLException */ public static String mapUrlToFileLocation(String rootLocation, String urlStr) throws MalformedURLException { int totalLength = rootLocation.length() + urlStr.length(); URL url = new URL(urlStr); StringBuffer buffer = new StringBuffer(totalLength); buffer.append(rootLocation); if (!rootLocation.endsWith(File.separator)) { buffer.append(File.separator); } buffer.append(url.getHost().toLowerCase()); buffer.append(File.separator); buffer.append(url.getProtocol()); buffer.append(escapePath(StringUtil.replaceString(url.getPath(), UrlUtil.URL_PATH_SEPARATOR, File.separator))); String query = url.getQuery(); if (query!=null) { buffer.append("?"); buffer.append(escapeQuery(query)); } return buffer.toString(); } // name mapping functions /** * Finds the directory for this AU. If none found in the map, designates * a new dir for it. * @param au the AU * @param buffer a StringBuffer to add the dir name to. */ static void getAuDir(ArchivalUnit au, StringBuffer buffer) { if (nameMap == null) { loadNameMap(buffer.toString()); } String auKey = au.getAuId(); String auDir = (String)nameMap.get(auKey); if (auDir == null) { logger.debug3("Creating new au directory for '" + auKey + "'."); while (true) { // loop through looking for an available dir auDir = getNewPluginDir(); File testDir = new File(buffer.toString() + auDir); if (!testDir.exists()) { break; } else { logger.debug3("Existing directory found at '"+auDir+ "'. Creating another..."); } } logger.debug3("New au directory: "+auDir); nameMap.put(auKey, auDir); String auLocation = buffer.toString() + auDir; // write the new au property file to the new dir // XXX this data should be backed up elsewhere to avoid single-point // corruption Properties idProps = new Properties(); idProps.setProperty(AU_ID_PROP, au.getAuId()); saveAuIdProperties(auLocation, idProps); } buffer.append(auDir); } /** * Loads the name map by recursing through the current dirs and reading * the AU prop file at each location. * @param rootLocation the repository HD root location */ static void loadNameMap(String rootLocation) { logger.debug3("Loading name map for '" + rootLocation + "'."); nameMap = new HashMap(); File rootFile = new File(rootLocation); if (!rootFile.exists()) { rootFile.mkdirs(); logger.debug3("Creating root directory at '" + rootLocation + "'."); return; } File[] pluginAus = rootFile.listFiles(); for (int ii = 0; ii < pluginAus.length; ii++) { // loop through reading each property and storing the id with that dir String dirName = pluginAus[ii].getName(); if (dirName.compareTo(lastPluginDir) == 1) { // adjust the 'lastPluginDir' upwards if necessary lastPluginDir = dirName; } Properties idProps = getAuIdProperties(pluginAus[ii].getAbsolutePath()); if (idProps==null) { // if no properties were found, just continue continue; } // store the id, dirName pair in our map nameMap.put(idProps.getProperty(AU_ID_PROP), dirName); } } /** * Returns the next dir name, from 'a'->'z', then 'aa'->'az', then 'ba'->etc. * @return String the next dir */ static String getNewPluginDir() { String newPluginDir = ""; boolean charChanged = false; // go through and increment the first non-'z' char // counts back from the last char, so 'aa'->'ab', not 'ba' for (int ii=lastPluginDir.length()-1; ii>=0; ii--) { char curChar = lastPluginDir.charAt(ii); if (!charChanged) { if (curChar < 'z') { curChar++; charChanged = true; newPluginDir = curChar + newPluginDir; } else { newPluginDir += 'a'; } } else { newPluginDir = curChar + newPluginDir; } } if (!charChanged) { newPluginDir += 'a'; } lastPluginDir = newPluginDir; return newPluginDir; } static Properties getAuIdProperties(String location) { File propFile = new File(location + File.separator + AU_ID_FILE); try { InputStream is = new BufferedInputStream(new FileInputStream(propFile)); Properties idProps = new Properties(); idProps.load(is); is.close(); return idProps; } catch (Exception e) { logger.warning("Error loading au id from " + propFile.getPath() + "."); return null; } } static void saveAuIdProperties(String location, Properties props) { //XXX these AU_ID_FILE entries need to be backed up elsewhere to avoid // single-point corruption File propDir = new File(location); if (!propDir.exists()) { logger.debug("Creating directory '"+propDir.getAbsolutePath()+"'"); propDir.mkdirs(); } File propFile = new File(propDir, AU_ID_FILE); try { logger.debug3("Saving au id properties at '" + location + "'."); OutputStream os = new BufferedOutputStream(new FileOutputStream(propFile)); props.store(os, "ArchivalUnit id info"); os.close(); propFile.setReadOnly(); } catch (IOException ioe) { logger.error("Couldn't write properties for " + propFile.getPath() + ".", ioe); throw new LockssRepository.RepositoryStateException( "Couldn't write au id properties file."); } } // lockss filename-specific encoding methods /** * Escapes instances of the ESCAPE_CHAR from the path. This avoids name * conflicts with the repository files, such as '#nodestate.xml'. * @param path the path * @return the escaped path */ static String escapePath(String path) { //XXX escaping disabled because of URL encoding if (false && path.indexOf(ESCAPE_CHAR) >= 0) { return StringUtil.replaceString(path, ESCAPE_STR, ESCAPE_STR+ESCAPE_STR); } else { return path; } } /** * Escapes instances of File.separator from the query. These are safe from * filename overlap, but can't convert into extended paths and directories. * @param query the query * @return the escaped query */ static String escapeQuery(String query) { if (query.indexOf(File.separator) >= 0) { return StringUtil.replaceString(query, File.separator, ESCAPE_STR + ENCODED_SEPARATOR_CHAR); } else { return query; } } /** * Extracts '#x' encoding and converts back to 'x'. * @param orig the original * @return the unescaped version. */ static String unescape(String orig) { if (orig.indexOf(ESCAPE_CHAR) < 0) { // fast treatment of non-escaped strings return orig; } int index = -1; StringBuffer buffer = new StringBuffer(orig.length()); String oldStr = orig; while ((index = oldStr.indexOf(ESCAPE_CHAR)) >= 0) { buffer.append(oldStr.substring(0, index)); buffer.append(convertCode(oldStr.substring(index, index+2))); if (oldStr.length() > 2) { oldStr = oldStr.substring(index + 2); } else { oldStr = ""; } } buffer.append(oldStr); return buffer.toString(); } /** * Returns the second char in the escaped segment, unless it is 's', which * is a stand-in for the File.separatorChar. * @param code the code segment (length 2) * @return the encoded char */ static char convertCode(String code) { char encodedChar = code.charAt(1); if (encodedChar == ENCODED_SEPARATOR_CHAR) { return File.separatorChar; } else { return encodedChar; } } public static class Factory implements LockssAuManager.Factory { public LockssAuManager createAuManager(ArchivalUnit au) { return createNewLockssRepository(au); } } }
src/org/lockss/repository/LockssRepositoryImpl.java
/* * $Id: LockssRepositoryImpl.java,v 1.52 2004-04-14 23:46:17 eaalto Exp $ */ /* Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University, all rights reserved. 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 STANFORD UNIVERSITY 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. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.repository; import java.io.*; import java.net.*; import java.util.*; import org.lockss.app.*; import org.lockss.daemon.*; import org.lockss.plugin.*; import org.lockss.util.*; import org.apache.commons.collections.LRUMap; import org.apache.commons.collections.ReferenceMap; /** * LockssRepository is used to organize the urls being cached. * It keeps a memory cache of the most recently used nodes as a * least-recently-used map, and also caches weak references to the instances * as they're doled out. This ensures that two instances of the same node are * never created, as the weak references only disappear when the object is * finalized (they go to null when the last hard reference is gone, then are * removed from the cache on finalize()). */ public class LockssRepositoryImpl extends BaseLockssManager implements LockssRepository { /** * Configuration parameter name for Lockss cache location. */ public static final String PARAM_CACHE_LOCATION = Configuration.PREFIX + "cache.location"; /** * Name of top directory in which the urls are cached. */ public static final String CACHE_ROOT_NAME = "cache"; // needed only for unit tests static String cacheLocation = null; // used for name mapping static HashMap nameMap = null; // starts with a '#' so no possibility of clashing with a URL static final String AU_ID_FILE = "#au_id_file"; static final String AU_ID_PROP = "au.id"; static final String PLUGIN_ID_PROP = "plugin.id"; static final char ESCAPE_CHAR = '#'; static final String ESCAPE_STR = "#"; static final char ENCODED_SEPARATOR_CHAR = 's'; static final String INITIAL_PLUGIN_DIR = String.valueOf((char)('a'-1)); static String lastPluginDir = INITIAL_PLUGIN_DIR; /** * Parameter for maximum number of node instances to cache. This can be * fairly small because there typically isn't need for repeated access to * the same nodes over a short time. */ public static final String PARAM_MAX_LRUMAP_SIZE = Configuration.PREFIX + "cache.max.lrumap.size"; private static final int DEFAULT_MAX_LRUMAP_SIZE = 100; // this contains a '#' so that it's not defeatable by strings which // match the prefix in a url (like '../tmp/') private static final String TEST_PREFIX = "/#tmp"; private String rootLocation; private LRUMap nodeCache; private int nodeCacheSize = DEFAULT_MAX_LRUMAP_SIZE; private ReferenceMap refMap; private int cacheHits = 0; private int cacheMisses = 0; private int refHits = 0; private int refMisses = 0; private static Logger logger = Logger.getLogger("LockssRepository"); LockssRepositoryImpl(String rootPath) { rootLocation = rootPath; if (!rootLocation.endsWith(File.separator)) { // this shouldn't happen rootLocation += File.separator; } nodeCache = new LRUMap(nodeCacheSize); refMap = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.WEAK); } public void stopService() { // mainly important in testing to blank this lastPluginDir = INITIAL_PLUGIN_DIR; nameMap = null; super.stopService(); } protected void setConfig(Configuration newConfig, Configuration prevConfig, Set changedKeys) { // at some point we'll have to respond to changes in the available disk // space list nodeCacheSize = newConfig.getInt(PARAM_MAX_LRUMAP_SIZE, DEFAULT_MAX_LRUMAP_SIZE); if (nodeCache.getMaximumSize() != nodeCacheSize) { nodeCache.setMaximumSize(nodeCacheSize); } } /** Called between initService() and startService(), then whenever the * AU's config changes. * @param auConfig the new configuration */ public void setAuConfig(Configuration auConfig) { } public RepositoryNode getNode(String url) throws MalformedURLException { return getNode(url, false); } public RepositoryNode createNewNode(String url) throws MalformedURLException { return getNode(url, true); } public void deleteNode(String url) throws MalformedURLException { RepositoryNode node = getNode(url, false); if (node!=null) { node.markAsDeleted(); } } public void deactivateNode(String url) throws MalformedURLException { RepositoryNode node = getNode(url, false); if (node!=null) { node.deactivateContent(); } } /** * This function returns a RepositoryNode with a canonicalized path. * @param url the url in String form * @param create true iff the node should be created if absent * @return RepositoryNode the node * @throws MalformedURLException */ private synchronized RepositoryNode getNode(String url, boolean create) throws MalformedURLException { String urlKey; boolean isAuUrl = false; if (AuUrl.isAuUrl(url)) { // path information is lost here, but is unimportant if it's an AuUrl urlKey = AuUrl.PROTOCOL; isAuUrl = true; } else { // create a canonical path, handling all illegal path traversal urlKey = canonicalizePath(url); } // check LRUMap cache for node RepositoryNode node = (RepositoryNode)nodeCache.get(urlKey); if (node!=null) { cacheHits++; return node; } else { cacheMisses++; } // check weak reference map for node node = (RepositoryNode)refMap.get(urlKey); if (node!=null) { refHits++; nodeCache.put(urlKey, node); return node; } else { refMisses++; } String nodeLocation; if (isAuUrl) { // base directory of ArchivalUnit nodeLocation = rootLocation; node = new AuNodeImpl(urlKey, nodeLocation, this); } else { // determine proper node location nodeLocation = LockssRepositoryImpl.mapUrlToFileLocation(rootLocation, urlKey); node = new RepositoryNodeImpl(urlKey, nodeLocation, this); } if (!create) { // if not creating, check for existence File nodeDir = new File(nodeLocation); if (!nodeDir.exists()) { // return null if the node doesn't exist and shouldn't be created return null; } if (!nodeDir.isDirectory()) { logger.error("Cache file not a directory: "+nodeLocation); throw new LockssRepository.RepositoryStateException("Invalid cache file."); } } // add to node cache and weak reference cache nodeCache.put(urlKey, node); refMap.put(urlKey, node); return node; } // functions for testing int getCacheHits() { return cacheHits; } int getCacheMisses() { return cacheMisses; } int getRefHits() { return refHits; } int getRefMisses() { return refMisses; } /** * This is called when a node is in an inconsistent state. It simply creates * some necessary directories and deactivates the node. Future polls should * restore it properly. * @param node the inconsistent node */ void deactivateInconsistentNode(RepositoryNodeImpl node) { logger.warning("Inconsistent node state found; node content deactivated."); if (!node.contentDir.exists()) { node.contentDir.mkdirs(); } // manually deactivate node.deactivateContent(); } /** * A method to remove any non-canonical '..' or '.' elements in the path, * as well as protecting against illegal path traversal. * @param url the raw url * @return String the canonicalized url * @throws MalformedURLException */ public static String canonicalizePath(String url) throws MalformedURLException { String canonUrl; try { URL testUrl = new URL(url); String path = testUrl.getPath(); // look for '.' or '..' elements if (path.indexOf("/.")>=0) { // check if path traversal is legal if (FileUtil.isLegalPath(path)) { // canonicalize to remove urls including '..' and '.' path = TEST_PREFIX + path; File testFile = new File(path); String canonPath = testFile.getCanonicalPath(); String sysDepPrefix = FileUtil.sysDepPath(TEST_PREFIX); int pathIndex = canonPath.indexOf(sysDepPrefix) + sysDepPrefix.length(); // reconstruct the url canonUrl = testUrl.getProtocol() + "://" + testUrl.getHost().toLowerCase() + FileUtil.sysIndepPath(canonPath.substring(pathIndex)); // restore the query, if any String query = testUrl.getQuery(); if (query!=null) { canonUrl += "?" + query; } } else { logger.error("Illegal URL detected: "+url); throw new MalformedURLException("Illegal URL detected."); } } else { // clean path, no testing needed canonUrl = url; } } catch (IOException ie) { logger.error("Error testing URL: "+ie); throw new MalformedURLException ("Error testing URL."); } // canonicalize "dir" and "dir/" // XXX if these are ever two separate nodes, this is wrong if (canonUrl.endsWith(UrlUtil.URL_PATH_SEPARATOR)) { canonUrl = canonUrl.substring(0, canonUrl.length()-1); } return canonUrl; } // static calls /** * Factory method to create new LockssRepository instances. * @param au the {@link ArchivalUnit} * @return the new LockssRepository instance */ public static LockssRepository createNewLockssRepository(ArchivalUnit au) { // XXX needs to handle multiple disks/repository locations cacheLocation = Configuration.getParam(PARAM_CACHE_LOCATION); if (cacheLocation == null) { logger.error("Couldn't get " + PARAM_CACHE_LOCATION + " from Configuration"); throw new LockssRepository.RepositoryStateException( "Couldn't load param."); } cacheLocation = extendCacheLocation(cacheLocation); return new LockssRepositoryImpl( LockssRepositoryImpl.mapAuToFileLocation(cacheLocation, au)); } /** * Adds the 'cache' directory to the HD location. * @param cacheDir the root location. * @return String the extended location */ static String extendCacheLocation(String cacheDir) { StringBuffer buffer = new StringBuffer(cacheDir); if (!cacheDir.endsWith(File.separator)) { buffer.append(File.separator); } buffer.append(CACHE_ROOT_NAME); buffer.append(File.separator); return buffer.toString(); } /** * mapAuToFileLocation() is the method used to resolve {@link ArchivalUnit}s * into directory names. This maps a given au to directories, using the * cache root as the base. Given an au with PluginId of 'plugin' and AuId * of 'au', it would return the string '<rootLocation>/plugin/au/'. * @param rootLocation the root for all ArchivalUnits * @param au the ArchivalUnit to resolve * @return the directory location */ public static String mapAuToFileLocation(String rootLocation, ArchivalUnit au) { StringBuffer buffer = new StringBuffer(rootLocation); if (!rootLocation.endsWith(File.separator)) { buffer.append(File.separator); } getAuDir(au, buffer); buffer.append(File.separator); return buffer.toString(); } /** * mapUrlToFileLocation() is the method used to resolve urls into file names. * This maps a given url to a file location, using the au top directory as * the base. It creates directories which mirror the html string, so * 'http://www.journal.org/issue1/index.html' would be cached in the file: * <rootLocation>/www.journal.org/http/issue1/index.html * @param rootLocation the top directory for ArchivalUnit this URL is in * @param urlStr the url to translate * @return the url file location * @throws java.net.MalformedURLException */ public static String mapUrlToFileLocation(String rootLocation, String urlStr) throws MalformedURLException { int totalLength = rootLocation.length() + urlStr.length(); URL url = new URL(urlStr); StringBuffer buffer = new StringBuffer(totalLength); buffer.append(rootLocation); if (!rootLocation.endsWith(File.separator)) { buffer.append(File.separator); } buffer.append(url.getHost().toLowerCase()); buffer.append(File.separator); buffer.append(url.getProtocol()); buffer.append(escapePath(StringUtil.replaceString(url.getPath(), UrlUtil.URL_PATH_SEPARATOR, File.separator))); String query = url.getQuery(); if (query!=null) { buffer.append("?"); buffer.append(escapeQuery(query)); } return buffer.toString(); } // name mapping functions /** * Finds the directory for this AU. If none found in the map, designates * a new dir for it. * @param au the AU * @param buffer a StringBuffer to add the dir name to. */ static void getAuDir(ArchivalUnit au, StringBuffer buffer) { if (nameMap == null) { loadNameMap(buffer.toString()); } String auKey = au.getAuId(); String auDir = (String)nameMap.get(auKey); if (auDir == null) { logger.debug3("Creating new au directory for '" + auKey + "'."); while (true) { // loop through looking for an available dir auDir = getNewPluginDir(); File testDir = new File(buffer.toString() + auDir); if (!testDir.exists()) { break; } else { logger.debug3("Existing directory found at '"+auDir+ "'. Creating another..."); } } logger.debug3("New au directory: "+auDir); nameMap.put(auKey, auDir); String auLocation = buffer.toString() + auDir; // write the new au property file to the new dir // XXX this data should be backed up elsewhere to avoid single-point // corruption Properties idProps = new Properties(); idProps.setProperty(AU_ID_PROP, au.getAuId()); saveAuIdProperties(auLocation, idProps); } buffer.append(auDir); } /** * Loads the name map by recursing through the current dirs and reading * the AU prop file at each location. * @param rootLocation the repository HD root location */ static void loadNameMap(String rootLocation) { logger.debug3("Loading name map for '" + rootLocation + "'."); nameMap = new HashMap(); File rootFile = new File(rootLocation); if (!rootFile.exists()) { rootFile.mkdirs(); logger.debug3("Creating root directory at '" + rootLocation + "'."); return; } File[] pluginAus = rootFile.listFiles(); for (int ii = 0; ii < pluginAus.length; ii++) { // loop through reading each property and storing the id with that dir String dirName = pluginAus[ii].getName(); if (dirName.compareTo(lastPluginDir) == 1) { // adjust the 'lastPluginDir' upwards if necessary lastPluginDir = dirName; } Properties idProps = getAuIdProperties(pluginAus[ii].getAbsolutePath()); if (idProps==null) { // if no properties were found, just continue continue; } // store the id, dirName pair in our map nameMap.put(idProps.getProperty(AU_ID_PROP), dirName); } } /** * Returns the next dir name, from 'a'->'z', then 'aa'->'az', then 'ba'->etc. * @return String the next dir */ static String getNewPluginDir() { String newPluginDir = ""; boolean charChanged = false; // go through and increment the first non-'z' char // counts back from the last char, so 'aa'->'ab', not 'ba' for (int ii=lastPluginDir.length()-1; ii>=0; ii--) { char curChar = lastPluginDir.charAt(ii); if (!charChanged) { if (curChar < 'z') { curChar++; charChanged = true; newPluginDir = curChar + newPluginDir; } else { newPluginDir += 'a'; } } else { newPluginDir = curChar + newPluginDir; } } if (!charChanged) { newPluginDir += 'a'; } lastPluginDir = newPluginDir; return newPluginDir; } static Properties getAuIdProperties(String location) { File propFile = new File(location + File.separator + AU_ID_FILE); try { InputStream is = new BufferedInputStream(new FileInputStream(propFile)); Properties idProps = new Properties(); idProps.load(is); is.close(); return idProps; } catch (Exception e) { logger.warning("Error loading au id from " + propFile.getPath() + "."); return null; } } static void saveAuIdProperties(String location, Properties props) { //XXX these AU_ID_FILE entries need to be backed up elsewhere to avoid // single-point corruption File propDir = new File(location); if (!propDir.exists()) { logger.debug("Creating directory '"+propDir.getAbsolutePath()+"'"); propDir.mkdirs(); } File propFile = new File(propDir, AU_ID_FILE); try { logger.debug3("Saving au id properties at '" + location + "'."); OutputStream os = new BufferedOutputStream(new FileOutputStream(propFile)); props.store(os, "ArchivalUnit id info"); os.close(); propFile.setReadOnly(); } catch (IOException ioe) { logger.error("Couldn't write properties for " + propFile.getPath() + ".", ioe); throw new LockssRepository.RepositoryStateException( "Couldn't write au id properties file."); } } // lockss filename-specific encoding methods /** * Escapes instances of the ESCAPE_CHAR from the path. This avoids name * conflicts with the repository files, such as '#nodestate.xml'. * @param path the path * @return the escaped path */ static String escapePath(String path) { //XXX escaping disabled because of URL encoding if (false && path.indexOf(ESCAPE_CHAR) >= 0) { return StringUtil.replaceString(path, ESCAPE_STR, ESCAPE_STR+ESCAPE_STR); } else { return path; } } /** * Escapes instances of File.separator from the query. These are safe from * filename overlap, but can't convert into extended paths and directories. * @param query the query * @return the escaped query */ static String escapeQuery(String query) { if (query.indexOf(File.separator) >= 0) { return StringUtil.replaceString(query, File.separator, ESCAPE_STR + ENCODED_SEPARATOR_CHAR); } else { return query; } } /** * Extracts '#x' encoding and converts back to 'x'. * @param orig the original * @return the unescaped version. */ static String unescape(String orig) { if (orig.indexOf(ESCAPE_CHAR) < 0) { // fast treatment of non-escaped strings return orig; } int index = -1; StringBuffer buffer = new StringBuffer(orig.length()); String oldStr = orig; while ((index = oldStr.indexOf(ESCAPE_CHAR)) >= 0) { buffer.append(oldStr.substring(0, index)); buffer.append(convertCode(oldStr.substring(index, index+2))); if (oldStr.length() > 2) { oldStr = oldStr.substring(index + 2); } else { oldStr = ""; } } buffer.append(oldStr); return buffer.toString(); } /** * Returns the second char in the escaped segment, unless it is 's', which * is a stand-in for the File.separatorChar. * @param code the code segment (length 2) * @return the encoded char */ static char convertCode(String code) { char encodedChar = code.charAt(1); if (encodedChar == ENCODED_SEPARATOR_CHAR) { return File.separatorChar; } else { return encodedChar; } } public static class Factory implements LockssAuManager.Factory { public LockssAuManager createAuManager(ArchivalUnit au) { return createNewLockssRepository(au); } } }
Minor error log improvement. git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@2848 4f837ed2-42f5-46e7-a7a5-fa17313484d4
src/org/lockss/repository/LockssRepositoryImpl.java
Minor error log improvement.
<ide><path>rc/org/lockss/repository/LockssRepositoryImpl.java <ide> /* <del> * $Id: LockssRepositoryImpl.java,v 1.52 2004-04-14 23:46:17 eaalto Exp $ <add> * $Id: LockssRepositoryImpl.java,v 1.53 2004-04-27 19:40:12 tlipkis Exp $ <ide> */ <ide> <ide> /* <ide> // clean path, no testing needed <ide> canonUrl = url; <ide> } <del> } catch (IOException ie) { <del> logger.error("Error testing URL: "+ie); <del> throw new MalformedURLException ("Error testing URL."); <add> } catch (MalformedURLException e) { <add> logger.warning("Can't canonicalize path: " + e); <add> throw e; <add> } catch (IOException e) { <add> logger.warning("Can't canonicalize path: " + e); <add> throw new MalformedURLException(url); <ide> } <ide> <ide> // canonicalize "dir" and "dir/"
Java
apache-2.0
c32c3973a508fbbd570a72c8c94b8007c365afa3
0
SirWellington/alchemy-http,SirWellington/alchemy-http
/* * Copyright © 2018. Sir Wellington. * * 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 tech.sirwellington.alchemy.http.exceptions; import tech.sirwellington.alchemy.http.*; /** * Thrown when an error occurs trying to parse JSON, or unwrap JSON into a * {@linkplain AlchemyRequest.Step3#expecting(java.lang.Class) POJO}. * * @author SirWellington */ public class JsonException extends AlchemyHttpException { public JsonException() { } public JsonException(String message) { super(message); } public JsonException(String message, Throwable cause) { super(message, cause); } public JsonException(Throwable cause) { super(cause); } public JsonException(HttpRequest request) { super(request); } public JsonException(HttpRequest request, String message) { super(request, message); } public JsonException(HttpRequest request, String message, Throwable cause) { super(request, message, cause); } public JsonException(HttpRequest request, Throwable cause) { super(request, cause); } public JsonException(HttpResponse response) { super(response); } public JsonException(HttpResponse response, String message) { super(response, message); } public JsonException(HttpResponse response, String message, Throwable cause) { super(response, message, cause); } public JsonException(HttpResponse response, Throwable cause) { super(response, cause); } public JsonException(HttpRequest request, HttpResponse response) { super(request, response); } public JsonException(HttpRequest request, HttpResponse response, String message) { super(request, response, message); } public JsonException(HttpRequest request, HttpResponse response, String message, Throwable cause) { super(request, response, message, cause); } public JsonException(HttpRequest request, HttpResponse response, Throwable cause) { super(request, response, cause); } }
src/main/java/tech/sirwellington/alchemy/http/exceptions/JsonException.java
/* * Copyright © 2018. Sir Wellington. * * 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 tech.sirwellington.alchemy.http.exceptions; import tech.sirwellington.alchemy.http.AlchemyRequest; import tech.sirwellington.alchemy.http.HttpRequest; import tech.sirwellington.alchemy.http.HttpResponse; /** * Thrown when an error occurs trying to parse JSON, or unwrap JSON into a * {@linkplain AlchemyRequest.Step3#expecting(java.lang.Class) POJO}. * * @author SirWellington */ public class JsonException extends AlchemyHttpException { public JsonException() { } public JsonException(String message) { super(message); } public JsonException(String message, Throwable cause) { super(message, cause); } public JsonException(Throwable cause) { super(cause); } public JsonException(HttpRequest request) { super(request); } public JsonException(HttpRequest request, String message) { super(request, message); } public JsonException(HttpRequest request, String message, Throwable cause) { super(request, message, cause); } public JsonException(HttpRequest request, Throwable cause) { super(request, cause); } public JsonException(HttpResponse response) { super(response); } public JsonException(HttpResponse response, String message) { super(response, message); } public JsonException(HttpResponse response, String message, Throwable cause) { super(response, message, cause); } public JsonException(HttpResponse response, Throwable cause) { super(response, cause); } public JsonException(HttpRequest request, HttpResponse response) { super(request, response); } public JsonException(HttpRequest request, HttpResponse response, String message) { super(request, response, message); } public JsonException(HttpRequest request, HttpResponse response, String message, Throwable cause) { super(request, response, message, cause); } public JsonException(HttpRequest request, HttpResponse response, Throwable cause) { super(request, response, cause); } }
Optimizes imports
src/main/java/tech/sirwellington/alchemy/http/exceptions/JsonException.java
Optimizes imports
<ide><path>rc/main/java/tech/sirwellington/alchemy/http/exceptions/JsonException.java <ide> */ <ide> package tech.sirwellington.alchemy.http.exceptions; <ide> <del>import tech.sirwellington.alchemy.http.AlchemyRequest; <del>import tech.sirwellington.alchemy.http.HttpRequest; <del>import tech.sirwellington.alchemy.http.HttpResponse; <add>import tech.sirwellington.alchemy.http.*; <ide> <ide> /** <ide> * Thrown when an error occurs trying to parse JSON, or unwrap JSON into a
Java
apache-2.0
fee3a4ba14e40f564a385e9b4f2a8b223ffaba30
0
skyscreamer/yoga,skyscreamer/yoga
package org.skyscreamer.yoga.demo.view; import org.skyscreamer.yoga.controller.ControllerResponse; import org.skyscreamer.yoga.populator.ObjectFieldPopulator; import org.skyscreamer.yoga.selector.Selector; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.ui.ExtendedModelMap; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.View; import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Method; import java.util.Collection; import java.util.List; import java.util.Map; public class SelectorModelAndViewResolver implements ModelAndViewResolver { @Autowired ObjectFieldPopulator _objectFieldPopulator; MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter(); @SuppressWarnings("rawtypes") public ModelAndView resolveModelAndView( Method handlerMethod, Class handlerType, Object returnValue, ExtendedModelMap implicitModel, NativeWebRequest webRequest ) { if ( returnValue instanceof ControllerResponse ) { ControllerResponse controllerResponse = (ControllerResponse)returnValue; if ( controllerResponse.getData() != null && AnnotationUtils.findAnnotation( handlerMethod, ResponseBody.class ) != null ) { return render( controllerResponse, webRequest ); } } return UNRESOLVED; } protected ModelAndView render( final ControllerResponse controllerResponse, NativeWebRequest webRequest ) { final MediaType accept = getAcceptableAcccept( controllerResponse.getData().getClass(), webRequest ); if ( accept == null ) { return null; } return new ModelAndView( new View() { public void render( Map<String, ?> input, HttpServletRequest request, HttpServletResponse response ) throws Exception { Object toRender = getModel( input.values().iterator().next(), controllerResponse.getSelector() ); mappingJacksonHttpMessageConverter.write( toRender, accept, new ServletServerHttpResponse( response ) ); } public String getContentType() { return accept.toString(); } } ).addObject( controllerResponse.getData() ); } protected Object getModel( Object returnValue, Selector selector ) { if ( returnValue instanceof Collection<?> ) { return _objectFieldPopulator.populate( (Collection<?>) returnValue, selector ); } else { return _objectFieldPopulator.populate( returnValue, selector ); } } protected MediaType getAcceptableAcccept( Class<?> returnType, NativeWebRequest nativeWebRequest ) { HttpServletRequest req = nativeWebRequest.getNativeRequest( HttpServletRequest.class ); ServletServerHttpRequest servletServerHttpRequest = new ServletServerHttpRequest( req ); List<MediaType> accepts = servletServerHttpRequest.getHeaders().getAccept(); for ( MediaType mediaType : accepts ) { if ( mappingJacksonHttpMessageConverter.canWrite( returnType, mediaType ) ) { return mediaType; } } return null; } }
demos/yoga-springmvc/src/main/java/org/skyscreamer/yoga/demo/view/SelectorModelAndViewResolver.java
package org.skyscreamer.yoga.demo.view; import java.lang.reflect.Method; import java.util.Collection; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.skyscreamer.yoga.populator.ObjectFieldPopulator; import org.skyscreamer.yoga.selector.CombinedSelector; import org.skyscreamer.yoga.selector.CoreSelector; import org.skyscreamer.yoga.selector.ParseSelectorException; import org.skyscreamer.yoga.selector.Selector; import org.skyscreamer.yoga.selector.SelectorParser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.ui.ExtendedModelMap; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.View; import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver; public class SelectorModelAndViewResolver implements ModelAndViewResolver { @Autowired ObjectFieldPopulator _objectFieldPopulator; MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter(); @SuppressWarnings("rawtypes") @Override public ModelAndView resolveModelAndView(Method handlerMethod, Class handlerType, Object returnValue, ExtendedModelMap implicitModel, NativeWebRequest webRequest) { if (returnValue == null || AnnotationUtils.findAnnotation(handlerMethod, ResponseBody.class) == null) { return null; } return render(returnValue, webRequest); } protected ModelAndView render(final Object returnValue, NativeWebRequest webRequest) { HttpServletRequest req = webRequest.getNativeRequest(HttpServletRequest.class); final MediaType accept = getAcceptableAcccept(returnValue.getClass(), req); if (accept == null) { return null; } return new ModelAndView(new View() { @Override public void render(Map<String, ?> input, HttpServletRequest request, HttpServletResponse response) throws Exception { Object toRender = getModel(input.values().iterator().next(), request); mappingJacksonHttpMessageConverter.write(toRender, accept, new ServletServerHttpResponse(response)); } @Override public String getContentType() { return accept.toString(); } }).addObject(returnValue); } protected Object getModel(Object returnValue, HttpServletRequest req) { if (returnValue instanceof Collection<?>) { return _objectFieldPopulator.populate((Collection<?>) returnValue, getSelector(req)); } else { return _objectFieldPopulator.populate(returnValue, getSelector(req)); } } protected Selector getSelector(HttpServletRequest req) { CoreSelector coreSelector = new CoreSelector(); String selectorStr = req.getParameter("selector"); if (selectorStr != null) { try { return new CombinedSelector(coreSelector, SelectorParser.parse(selectorStr)); } catch (ParseSelectorException e) { // TODO: Add logging here. Spring spits out // "no matching editors or conversion strategy found", which // is vague and misleading. (ie, A URL typo looks like a // configuration error) throw new IllegalArgumentException("Could not parse selector", e); } } return coreSelector; } protected MediaType getAcceptableAcccept(Class<?> returnType, HttpServletRequest req) { ServletServerHttpRequest servletServerHttpRequest = new ServletServerHttpRequest(req); List<MediaType> accepts = servletServerHttpRequest.getHeaders().getAccept(); for (MediaType mediaType : accepts) { if (mappingJacksonHttpMessageConverter.canWrite(returnType, mediaType)) { return mediaType; } } return null; } }
Binding the selector at the beginning of the controller method to enable DTO population
demos/yoga-springmvc/src/main/java/org/skyscreamer/yoga/demo/view/SelectorModelAndViewResolver.java
Binding the selector at the beginning of the controller method to enable DTO population
<ide><path>emos/yoga-springmvc/src/main/java/org/skyscreamer/yoga/demo/view/SelectorModelAndViewResolver.java <ide> package org.skyscreamer.yoga.demo.view; <ide> <del>import java.lang.reflect.Method; <del>import java.util.Collection; <del>import java.util.List; <del>import java.util.Map; <del> <del>import javax.servlet.http.HttpServletRequest; <del>import javax.servlet.http.HttpServletResponse; <del> <add>import org.skyscreamer.yoga.controller.ControllerResponse; <ide> import org.skyscreamer.yoga.populator.ObjectFieldPopulator; <del>import org.skyscreamer.yoga.selector.CombinedSelector; <del>import org.skyscreamer.yoga.selector.CoreSelector; <del>import org.skyscreamer.yoga.selector.ParseSelectorException; <ide> import org.skyscreamer.yoga.selector.Selector; <del>import org.skyscreamer.yoga.selector.SelectorParser; <ide> import org.springframework.beans.factory.annotation.Autowired; <ide> import org.springframework.core.annotation.AnnotationUtils; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.web.servlet.View; <ide> import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver; <ide> <del>public class SelectorModelAndViewResolver implements ModelAndViewResolver { <add>import javax.servlet.http.HttpServletRequest; <add>import javax.servlet.http.HttpServletResponse; <add>import java.lang.reflect.Method; <add>import java.util.Collection; <add>import java.util.List; <add>import java.util.Map; <ide> <del> @Autowired <del> ObjectFieldPopulator _objectFieldPopulator; <add>public class SelectorModelAndViewResolver implements ModelAndViewResolver <add>{ <add> @Autowired <add> ObjectFieldPopulator _objectFieldPopulator; <ide> <del> MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter(); <add> MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter(); <ide> <del> @SuppressWarnings("rawtypes") <del> @Override <del> public ModelAndView resolveModelAndView(Method handlerMethod, Class handlerType, Object returnValue, ExtendedModelMap implicitModel, NativeWebRequest webRequest) { <del> if (returnValue == null || AnnotationUtils.findAnnotation(handlerMethod, ResponseBody.class) == null) { <del> return null; <del> } <del> return render(returnValue, webRequest); <del> } <add> @SuppressWarnings("rawtypes") <add> public ModelAndView resolveModelAndView( Method handlerMethod, Class handlerType, Object returnValue, <add> ExtendedModelMap implicitModel, NativeWebRequest webRequest ) <add> { <add> if ( returnValue instanceof ControllerResponse ) <add> { <add> ControllerResponse controllerResponse = (ControllerResponse)returnValue; <add> if ( controllerResponse.getData() != null && <add> AnnotationUtils.findAnnotation( handlerMethod, ResponseBody.class ) != null ) <add> { <add> return render( controllerResponse, webRequest ); <add> } <add> } <add> return UNRESOLVED; <add> } <ide> <del> protected ModelAndView render(final Object returnValue, NativeWebRequest webRequest) { <del> HttpServletRequest req = webRequest.getNativeRequest(HttpServletRequest.class); <del> final MediaType accept = getAcceptableAcccept(returnValue.getClass(), req); <del> <del> if (accept == null) { <del> return null; <del> } <del> <del> return new ModelAndView(new View() { <del> @Override <del> public void render(Map<String, ?> input, HttpServletRequest request, HttpServletResponse response) throws Exception { <del> Object toRender = getModel(input.values().iterator().next(), request); <del> mappingJacksonHttpMessageConverter.write(toRender, accept, new ServletServerHttpResponse(response)); <del> } <del> <del> @Override <del> public String getContentType() { <del> return accept.toString(); <del> } <del> }).addObject(returnValue); <del> } <add> protected ModelAndView render( final ControllerResponse controllerResponse, NativeWebRequest webRequest ) <add> { <add> final MediaType accept = getAcceptableAcccept( controllerResponse.getData().getClass(), webRequest ); <ide> <del> protected Object getModel(Object returnValue, HttpServletRequest req) { <del> if (returnValue instanceof Collection<?>) { <del> return _objectFieldPopulator.populate((Collection<?>) returnValue, getSelector(req)); <del> } else { <del> return _objectFieldPopulator.populate(returnValue, getSelector(req)); <del> } <del> } <add> if ( accept == null ) <add> { <add> return null; <add> } <ide> <del> protected Selector getSelector(HttpServletRequest req) { <del> CoreSelector coreSelector = new CoreSelector(); <del> String selectorStr = req.getParameter("selector"); <del> if (selectorStr != null) { <del> try { <del> return new CombinedSelector(coreSelector, SelectorParser.parse(selectorStr)); <del> } catch (ParseSelectorException e) { <del> // TODO: Add logging here. Spring spits out <del> // "no matching editors or conversion strategy found", which <del> // is vague and misleading. (ie, A URL typo looks like a <del> // configuration error) <del> throw new IllegalArgumentException("Could not parse selector", e); <del> } <del> } <del> return coreSelector; <del> } <add> return new ModelAndView( new View() <add> { <add> public void render( Map<String, ?> input, HttpServletRequest request, HttpServletResponse response ) <add> throws Exception <add> { <add> Object toRender = getModel( input.values().iterator().next(), controllerResponse.getSelector() ); <add> mappingJacksonHttpMessageConverter.write( toRender, accept, new ServletServerHttpResponse( response ) ); <add> } <ide> <del> protected MediaType getAcceptableAcccept(Class<?> returnType, HttpServletRequest req) { <del> ServletServerHttpRequest servletServerHttpRequest = new ServletServerHttpRequest(req); <del> List<MediaType> accepts = servletServerHttpRequest.getHeaders().getAccept(); <del> for (MediaType mediaType : accepts) { <del> if (mappingJacksonHttpMessageConverter.canWrite(returnType, mediaType)) { <del> return mediaType; <del> } <del> } <del> return null; <del> } <add> public String getContentType() <add> { <add> return accept.toString(); <add> } <add> } ).addObject( controllerResponse.getData() ); <add> } <add> <add> protected Object getModel( Object returnValue, Selector selector ) <add> { <add> if ( returnValue instanceof Collection<?> ) <add> { <add> return _objectFieldPopulator.populate( (Collection<?>) returnValue, selector ); <add> } <add> else <add> { <add> return _objectFieldPopulator.populate( returnValue, selector ); <add> } <add> } <add> <add> protected MediaType getAcceptableAcccept( Class<?> returnType, NativeWebRequest nativeWebRequest ) <add> { <add> HttpServletRequest req = nativeWebRequest.getNativeRequest( HttpServletRequest.class ); <add> ServletServerHttpRequest servletServerHttpRequest = new ServletServerHttpRequest( req ); <add> List<MediaType> accepts = servletServerHttpRequest.getHeaders().getAccept(); <add> for ( MediaType mediaType : accepts ) <add> { <add> if ( mappingJacksonHttpMessageConverter.canWrite( returnType, mediaType ) ) <add> { <add> return mediaType; <add> } <add> } <add> return null; <add> } <ide> }
Java
apache-2.0
2eef5ad197e4477b47f080d99c22a5379d257cc9
0
bradparks/mamute,GEBIT/mamute,csokol/mamute,c2tarun/mamute,superm1a3/mamute,khajavi/mamute,JamesSullivan/mamute,cristianospsp/mamute,jasonwjones/mamute,bradparks/mamute,dhieugo/mamute,shomabegoo/shomabegoo,bradparks/mamute,dhieugo/mamute,MatejBalantic/mamute,c2tarun/mamute,caelum/mamute,jasonwjones/mamute,csokol/mamute,caelum/mamute,xdarklight/mamute,MatejBalantic/mamute,GEBIT/mamute,MatejBalantic/mamute,khajavi/mamute,superm1a3/mamute,khajavi/mamute,caelum/mamute,xdarklight/mamute,shomabegoo/shomabegoo,cristianospsp/mamute,jasonwjones/mamute,cristianospsp/mamute,GEBIT/mamute,csokol/mamute,xdarklight/mamute,shomabegoo/shomabegoo,superm1a3/mamute,JamesSullivan/mamute,c2tarun/mamute,dhieugo/mamute,shomabegoo/shomabegoo,JamesSullivan/mamute
package org.mamute.auth; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.apache.commons.lang.StringUtils.isNotEmpty; import static org.mamute.model.SanitizedText.fromTrustedText; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.apache.directory.api.ldap.model.cursor.CursorException; import org.apache.directory.api.ldap.model.cursor.EntryCursor; import org.apache.directory.api.ldap.model.entry.Attribute; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.entry.Value; import org.apache.directory.api.ldap.model.exception.LdapAuthenticationException; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; import org.mamute.dao.LoginMethodDAO; import org.mamute.dao.UserDAO; import org.mamute.model.LoginMethod; import org.mamute.model.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import br.com.caelum.vraptor.environment.Environment; /** * LDAP authentication API */ public class LDAPApi { private static final Logger logger = LoggerFactory.getLogger(LDAPApi.class); public static final String LDAP_AUTH = "ldap"; public static final String LDAP_HOST = "ldap.host"; public static final String LDAP_PORT = "ldap.port"; public static final String LDAP_USER = "ldap.user"; public static final String LDAP_PASS = "ldap.pass"; public static final String LDAP_USER_DN = "ldap.userDn"; public static final String LDAP_EMAIL = "ldap.emailAttr"; public static final String LDAP_NAME = "ldap.nameAttr"; public static final String LDAP_SURNAME = "ldap.surnameAttr"; public static final String LDAP_GROUP = "ldap.groupAttr"; public static final String LDAP_LOOKUP = "ldap.lookupAttr"; public static final String LDAP_MODERATOR_GROUP = "ldap.moderatorGroup"; public static final String PLACHOLDER_PASSWORD = "ldap-password-ignore-me"; @Inject private Environment env; @Inject private UserDAO users; @Inject private LoginMethodDAO loginMethods; private String host; private Integer port; private String user; private String pass; private String userDn; private String emailAttr; private String nameAttr; private String surnameAttr; private String groupAttr; private String[] lookupAttrs; private String moderatorGroup; /** * Ensure that required variables are set if LDAP auth * is enabled */ @PostConstruct public void init() { if (env.supports("feature.auth.ldap")) { //required host = assertValuePresent(LDAP_HOST); port = Integer.parseInt(assertValuePresent(LDAP_PORT)); user = assertValuePresent(LDAP_USER); pass = assertValuePresent(LDAP_PASS); userDn = assertValuePresent(LDAP_USER_DN); emailAttr = assertValuePresent(LDAP_EMAIL); nameAttr = assertValuePresent(LDAP_NAME); //optional surnameAttr = env.get(LDAP_SURNAME, ""); groupAttr = env.get(LDAP_GROUP, ""); moderatorGroup = env.get(LDAP_MODERATOR_GROUP, ""); lookupAttrs = env.get(LDAP_LOOKUP, "").split(","); } } /** * Attempt to authenticate against LDAP directory. Accepts email addresses * as well as plain usernames; emails will have the '@mail.com' portion * stripped off before read. * * @param username * @param password * @return */ public boolean authenticate(String username, String password) { try (LDAPResource ldap = new LDAPResource()) { String cn = userCn(username); ldap.verifyCredentials(cn, password); createUserIfNeeded(ldap, cn); return true; } catch (LdapAuthenticationException e) { logger.debug("LDAP auth attempt failed"); return false; } catch (LdapException | IOException e) { logger.debug("LDAP connection error", e); throw new AuthenticationException(LDAP_AUTH, "LDAP connection error", e); } } /** * Find the email address for a given username * * @param username * @return */ public String getEmail(String username) { try (LDAPResource ldap = new LDAPResource()) { Entry ldapUser = ldap.getUser(userCn(username)); return ldap.getAttribute(ldapUser, emailAttr); } catch (LdapException | IOException e) { logger.debug("LDAP connection error", e); throw new AuthenticationException(LDAP_AUTH, "LDAP connection error", e); } } private String userCn(String username) { if (lookupAttrs.length > 0) { try (LDAPResource ldap = new LDAPResource()) { Entry user = ldap.lookupUser(username); if (user != null) { return user.getDn().getName(); } } catch (LdapException | IOException e) { logger.debug("LDAP connection error", e); throw new AuthenticationException(LDAP_AUTH, "LDAP connection error", e); } } // fallback: assume lookup by CN String sanitizedUser = username.replaceAll("[,=]", ""); String cn = "cn=" + sanitizedUser + "," + userDn; return cn; } private void createUserIfNeeded(LDAPResource ldap, String cn) throws LdapException { Entry ldapUser = ldap.getUser(cn); String email = ldap.getAttribute(ldapUser, emailAttr); User user = users.findByEmail(email); if (user == null) { String fullName = ldap.getAttribute(ldapUser, nameAttr); if (isNotEmpty(surnameAttr)) { fullName += " " + ldap.getAttribute(ldapUser, surnameAttr); } user = new User(fromTrustedText(fullName.trim()), email); LoginMethod brutalLogin = LoginMethod.brutalLogin(user, email, PLACHOLDER_PASSWORD); user.add(brutalLogin); users.save(user); loginMethods.save(brutalLogin); } //update moderator status if (isNotEmpty(moderatorGroup) && ldap.getGroups(ldapUser).contains(moderatorGroup)) { user = user.asModerator(); } else { user.removeModerator(); } users.save(user); } private String assertValuePresent(String field) { String value = env.get(field, ""); if (isEmpty(value)) { throw new RuntimeException("Field [" + field + "] is required when using LDAP authentication"); } return value; } /** * Acts as a session-level LDAP connection. */ private class LDAPResource implements AutoCloseable { LdapConnection connection; private LDAPResource() throws LdapException { connection = connection(user, pass); } private void verifyCredentials(String userCn, String password) throws LdapException, IOException { try (LdapConnection conn = connection(userCn, password)) { logger.debug("LDAP login from [" + userCn + "]"); } } private LdapConnection connection(String username, String password) throws LdapException { LdapNetworkConnection conn = new LdapNetworkConnection(host, port); conn.bind(username, password); return conn; } private List<String> getGroups(Entry user) { List<String> groupCns = new ArrayList<>(); if (isNotEmpty(groupAttr)) { Attribute grpEntry = user.get(groupAttr); if (grpEntry != null) { for (Value grp : grpEntry) { groupCns.add(grp.getString()); } } } return groupCns; } private Entry getUser(String cn) throws LdapException { return connection.lookup(cn); } private Entry lookupUser(String username) throws LdapException { StringBuilder userQuery = new StringBuilder(); userQuery.append("(&(objectclass=user)(|"); boolean hasCondition = false; for (String lookupAttr : lookupAttrs) { String attrName = lookupAttr.trim(); if (!attrName.isEmpty()) { userQuery.append('(').append(attrName).append('=').append(username).append(')'); hasCondition = true; } } userQuery.append("))"); if (!hasCondition) { return null; } for (String lookupAttr : lookupAttrs) { String attrName = lookupAttr.trim(); if (!attrName.isEmpty()) { EntryCursor responseCursor = connection.search(userDn, userQuery.toString(), SearchScope.SUBTREE); try { try { if (responseCursor != null && responseCursor.next()) { return responseCursor.get(); } } catch (CursorException e) { logger.debug("LDAP search error", e); return null; } } finally { responseCursor.close(); } } } return null; } private String getAttribute(Entry entry, String attribute) throws LdapException { return entry.get(attribute).getString(); } @Override public void close() throws IOException { connection.close(); } } }
src/main/java/org/mamute/auth/LDAPApi.java
package org.mamute.auth; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.apache.commons.lang.StringUtils.isNotEmpty; import static org.mamute.model.SanitizedText.fromTrustedText; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.apache.directory.api.ldap.model.cursor.CursorException; import org.apache.directory.api.ldap.model.cursor.EntryCursor; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.entry.Value; import org.apache.directory.api.ldap.model.exception.LdapAuthenticationException; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; import org.mamute.dao.LoginMethodDAO; import org.mamute.dao.UserDAO; import org.mamute.model.LoginMethod; import org.mamute.model.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import br.com.caelum.vraptor.environment.Environment; /** * LDAP authentication API */ public class LDAPApi { private static final Logger logger = LoggerFactory.getLogger(LDAPApi.class); public static final String LDAP_AUTH = "ldap"; public static final String LDAP_HOST = "ldap.host"; public static final String LDAP_PORT = "ldap.port"; public static final String LDAP_USER = "ldap.user"; public static final String LDAP_PASS = "ldap.pass"; public static final String LDAP_USER_DN = "ldap.userDn"; public static final String LDAP_EMAIL = "ldap.emailAttr"; public static final String LDAP_NAME = "ldap.nameAttr"; public static final String LDAP_SURNAME = "ldap.surnameAttr"; public static final String LDAP_GROUP = "ldap.groupAttr"; public static final String LDAP_LOOKUP = "ldap.lookupAttr"; public static final String LDAP_MODERATOR_GROUP = "ldap.moderatorGroup"; public static final String PLACHOLDER_PASSWORD = "ldap-password-ignore-me"; @Inject private Environment env; @Inject private UserDAO users; @Inject private LoginMethodDAO loginMethods; private String host; private Integer port; private String user; private String pass; private String userDn; private String emailAttr; private String nameAttr; private String surnameAttr; private String groupAttr; private String[] lookupAttrs; private String moderatorGroup; /** * Ensure that required variables are set if LDAP auth * is enabled */ @PostConstruct public void init() { if (env.supports("feature.auth.ldap")) { //required host = assertValuePresent(LDAP_HOST); port = Integer.parseInt(assertValuePresent(LDAP_PORT)); user = assertValuePresent(LDAP_USER); pass = assertValuePresent(LDAP_PASS); userDn = assertValuePresent(LDAP_USER_DN); emailAttr = assertValuePresent(LDAP_EMAIL); nameAttr = assertValuePresent(LDAP_NAME); //optional surnameAttr = env.get(LDAP_SURNAME, ""); groupAttr = env.get(LDAP_GROUP, ""); moderatorGroup = env.get(LDAP_MODERATOR_GROUP, ""); lookupAttrs = env.get(LDAP_LOOKUP, "").split(","); } } /** * Attempt to authenticate against LDAP directory. Accepts email addresses * as well as plain usernames; emails will have the '@mail.com' portion * stripped off before read. * * @param username * @param password * @return */ public boolean authenticate(String username, String password) { try (LDAPResource ldap = new LDAPResource()) { String cn = userCn(username); ldap.verifyCredentials(cn, password); createUserIfNeeded(ldap, cn); return true; } catch (LdapAuthenticationException e) { logger.debug("LDAP auth attempt failed"); return false; } catch (LdapException | IOException e) { logger.debug("LDAP connection error", e); throw new AuthenticationException(LDAP_AUTH, "LDAP connection error", e); } } /** * Find the email address for a given username * * @param username * @return */ public String getEmail(String username) { try (LDAPResource ldap = new LDAPResource()) { Entry ldapUser = ldap.getUser(userCn(username)); return ldap.getAttribute(ldapUser, emailAttr); } catch (LdapException | IOException e) { logger.debug("LDAP connection error", e); throw new AuthenticationException(LDAP_AUTH, "LDAP connection error", e); } } private String userCn(String username) { if (lookupAttrs.length > 0) { try (LDAPResource ldap = new LDAPResource()) { Entry user = ldap.lookupUser(username); if (user != null) { return user.getDn().getName(); } } catch (LdapException | IOException e) { logger.debug("LDAP connection error", e); throw new AuthenticationException(LDAP_AUTH, "LDAP connection error", e); } } // fallback: assume lookup by CN String sanitizedUser = username.replaceAll("[,=]", ""); String cn = "cn=" + sanitizedUser + "," + userDn; return cn; } private void createUserIfNeeded(LDAPResource ldap, String cn) throws LdapException { Entry ldapUser = ldap.getUser(cn); String email = ldap.getAttribute(ldapUser, emailAttr); User user = users.findByEmail(email); if (user == null) { String fullName = ldap.getAttribute(ldapUser, nameAttr); if (isNotEmpty(surnameAttr)) { fullName += " " + ldap.getAttribute(ldapUser, surnameAttr); } user = new User(fromTrustedText(fullName.trim()), email); LoginMethod brutalLogin = LoginMethod.brutalLogin(user, email, PLACHOLDER_PASSWORD); user.add(brutalLogin); users.save(user); loginMethods.save(brutalLogin); } //update moderator status if (isNotEmpty(moderatorGroup) && ldap.getGroups(ldapUser).contains(moderatorGroup)) { user = user.asModerator(); } else { user.removeModerator(); } users.save(user); } private String assertValuePresent(String field) { String value = env.get(field, ""); if (isEmpty(value)) { throw new RuntimeException("Field [" + field + "] is required when using LDAP authentication"); } return value; } /** * Acts as a session-level LDAP connection. */ private class LDAPResource implements AutoCloseable { LdapConnection connection; private LDAPResource() throws LdapException { connection = connection(user, pass); } private void verifyCredentials(String userCn, String password) throws LdapException, IOException { try (LdapConnection conn = connection(userCn, password)) { logger.debug("LDAP login from [" + userCn + "]"); } } private LdapConnection connection(String username, String password) throws LdapException { LdapNetworkConnection conn = new LdapNetworkConnection(host, port); conn.bind(username, password); return conn; } private List<String> getGroups(Entry user) { List<String> groupCns = new ArrayList<>(); if (isNotEmpty(groupAttr)) { for (Value grp : user.get(groupAttr)) { groupCns.add(grp.getString()); } } return groupCns; } private Entry getUser(String cn) throws LdapException { return connection.lookup(cn); } private Entry lookupUser(String username) throws LdapException { StringBuilder userQuery = new StringBuilder(); userQuery.append("(&(objectclass=user)(|"); boolean hasCondition = false; for (String lookupAttr : lookupAttrs) { String attrName = lookupAttr.trim(); if (!attrName.isEmpty()) { userQuery.append('(').append(attrName).append('=').append(username).append(')'); hasCondition = true; } } userQuery.append("))"); if (!hasCondition) { return null; } for (String lookupAttr : lookupAttrs) { String attrName = lookupAttr.trim(); if (!attrName.isEmpty()) { EntryCursor responseCursor = connection.search(userDn, userQuery.toString(), SearchScope.SUBTREE); try { try { if (responseCursor != null && responseCursor.next()) { return responseCursor.get(); } } catch (CursorException e) { logger.debug("LDAP search error", e); return null; } } finally { responseCursor.close(); } } } return null; } private String getAttribute(Entry entry, String attribute) throws LdapException { return entry.get(attribute).getString(); } @Override public void close() throws IOException { connection.close(); } } }
Fixed NPE in group lookup if attribute is not present
src/main/java/org/mamute/auth/LDAPApi.java
Fixed NPE in group lookup if attribute is not present
<ide><path>rc/main/java/org/mamute/auth/LDAPApi.java <ide> <ide> import org.apache.directory.api.ldap.model.cursor.CursorException; <ide> import org.apache.directory.api.ldap.model.cursor.EntryCursor; <add>import org.apache.directory.api.ldap.model.entry.Attribute; <ide> import org.apache.directory.api.ldap.model.entry.Entry; <ide> import org.apache.directory.api.ldap.model.entry.Value; <ide> import org.apache.directory.api.ldap.model.exception.LdapAuthenticationException; <ide> private List<String> getGroups(Entry user) { <ide> List<String> groupCns = new ArrayList<>(); <ide> if (isNotEmpty(groupAttr)) { <del> for (Value grp : user.get(groupAttr)) { <del> groupCns.add(grp.getString()); <add> Attribute grpEntry = user.get(groupAttr); <add> if (grpEntry != null) { <add> for (Value grp : grpEntry) { <add> groupCns.add(grp.getString()); <add> } <ide> } <ide> } <ide> return groupCns;
JavaScript
agpl-3.0
c7759d1a9191fabc6877a736df1307c81290aec5
0
rowhit/tagspaces,cbop-dev/tagspaces,cbop-dev/tagspaces,rowhit/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,rowhit/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,cbop-dev/tagspaces,rowhit/tagspaces
/* Copyright (c) 2012-2015 The TagSpaces Authors. All rights reserved. * Use of this source code is governed by a AGPL3 license that * can be found in the LICENSE file. */ /* undef: true, unused: false */ /* global define, Mousetrap, Handlebars */ define(function(require, exports, module) { 'use strict'; console.log('Loading fileopener...'); var TSCORE = require('tscore'); var _openedFilePath; var _openedFileProperties; var _isFileOpened = false; var _isFileChanged = false; var _tsEditor; var generatedTagButtons; // Backup cancel button <!--button type="button" class="btn editable-cancel"><i class="fa fa-times fa-lg"></i></button--> $.fn.editableform.buttons = '<button type="submit" class="btn btn-primary editable-submit"><i class="fa fa-check fa-lg"></i></button>'; // If a file is currently opened for editing, this var should be true var _isEditMode = false; window.onbeforeunload = function() { if (_isFileChanged) { return "Confirm close"; } }; function initUI() { $('#editDocument').click(function() { editFile(_openedFilePath); }); $('#saveDocument').click(function() { saveFile(); }); $('#closeOpenedFile').click(function() { closeFile(); }); $('#nextFileButton').click(function() { TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getNextFile(_openedFilePath)); }); $('#prevFileButton').click(function() { TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getPrevFile(_openedFilePath)); }); $('#closeFile').click(function() { closeFile(); }); $('#reloadFile').click(function() { TSCORE.FileOpener.openFile(_openedFilePath); }); $('#sendFile').click(function() { TSCORE.IO.sendFile(_openedFilePath); }); $('#openFileInNewWindow').click(function() { if (isWeb) { if (location.port === '') { window.open(location.protocol + '//' + location.hostname + _openedFilePath); } else { window.open(location.protocol + '//' + location.hostname + ':' + location.port + _openedFilePath); } } else { window.open('file:///' + _openedFilePath); } }); $('#printFile').click(function() { $('iframe').get(0).contentWindow.print(); }); $('#tagFile').click(function() { if (_isFileChanged) { TSCORE.showAlertDialog($.i18n.t('ns.dialogs:operationNotPermittedInEditModeAlert')); } else { TSCORE.PerspectiveManager.clearSelectedFiles(); TSCORE.selectedFiles.push(_openedFilePath); TSCORE.showAddTagsDialog(); } }); $('#suggestTagsFile').click(function() { $('tagSuggestionsMenu').dropdown('toggle'); }); $('#renameFile').click(function() { if (_isFileChanged) { TSCORE.showAlertDialog($.i18n.t('ns.dialogs:operationNotPermittedInEditModeAlert')); } else { TSCORE.showFileRenameDialog(_openedFilePath); } }); $('#duplicateFile').click(function() { var currentDateTime = TSCORE.TagUtils.formatDateTime4Tag(new Date(), true); var fileNameWithOutExt = TSCORE.TagUtils.extractFileNameWithoutExt(_openedFilePath); var fileExt = TSCORE.TagUtils.extractFileExtension(_openedFilePath); var newFilePath = TSCORE.currentPath + TSCORE.dirSeparator + fileNameWithOutExt + '_' + currentDateTime + '.' + fileExt; TSCORE.IO.copyFile(_openedFilePath, newFilePath); }); $('#toggleFullWidthButton').click(function() { TSCORE.toggleFullWidth(); }); $('#deleteFile').click(function() { TSCORE.showFileDeleteDialog(_openedFilePath); }); $('#openNatively').click(function() { TSCORE.IO.openFile(_openedFilePath); }); $('#openDirectory').click(function() { TSCORE.IO.openDirectory(TSCORE.TagUtils.extractParentDirectoryPath(_openedFilePath)); }); $('#fullscreenFile').click(function() { var docElm = $('#viewer')[0]; if (docElm.requestFullscreen) { docElm.requestFullscreen(); } else if (docElm.mozRequestFullScreen) { docElm.mozRequestFullScreen(); } else if (docElm.webkitRequestFullScreen) { docElm.webkitRequestFullScreen(); } }); $('#openProperties').click(function() { showFilePropertiesDialog(); }); } function isFileChanged() { return _isFileChanged; } function setFileChanged(value) { var $fileExt = $('#fileExtText'); var $fileTitle = $('#fileTitle'); if (value && !_isFileChanged) { $fileExt.text($fileExt.text() + '*'); $fileTitle.editable('disable'); $('#fileTags').find('button').prop('disabled', true); $('#addTagFileViewer').prop('disabled', true); } if (!value) { $fileExt.text(TSCORE.TagUtils.extractFileExtension(_openedFilePath)); $fileTitle.editable('enable'); $('#fileTags').find('button').prop('disabled', false); $('#addTagFileViewer').prop('disabled', false); } _isFileChanged = value; } function isFileEdited() { return _isEditMode; } function isFileOpened() { return _isFileOpened; } function getOpenedFilePath() { return _openedFilePath; } function closeFile(forceClose) { if (isFileChanged()) { if (forceClose) { cleanViewer(); } else { TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:closingEditedFileTitleConfirm'), $.i18n.t('ns.dialogs:closingEditedFileContentConfirm'), function() { cleanViewer(); }); } } else { cleanViewer(); } } function cleanViewer() { //TSCORE.PerspectiveManager.clearSelectedFiles(); TSCORE.closeFileViewer(); // Cleaning the viewer/editor //document.getElementById("viewer").innerHTML = ""; $('#viewer').find('*').off().unbind(); $('#viewer').find('iframe').remove(); $('#viewer').find('*').children().remove(); _isFileOpened = false; _isEditMode = false; _isFileChanged = false; Mousetrap.unbind(TSCORE.Config.getEditDocumentKeyBinding()); Mousetrap.unbind(TSCORE.Config.getSaveDocumentKeyBinding()); Mousetrap.unbind(TSCORE.Config.getCloseViewerKeyBinding()); Mousetrap.unbind(TSCORE.Config.getReloadDocumentKeyBinding()); Mousetrap.unbind(TSCORE.Config.getDeleteDocumentKeyBinding()); Mousetrap.unbind(TSCORE.Config.getPropertiesDocumentKeyBinding()); Mousetrap.unbind(TSCORE.Config.getPrevDocumentKeyBinding()); Mousetrap.unbind(TSCORE.Config.getNextDocumentKeyBinding()); } function openFileOnStartup(filePath) { TSCORE.Config.setLastOpenedLocation(undefined); // quick and dirty solution, should use flag later TSCORE.toggleFullWidth(); TSCORE.FileOpener.openFile(filePath); TSCORE.openLocation(TSCORE.TagUtils.extractContainingDirectoryPath(filePath)); } function openFile(filePath, editMode) { console.log('Opening file: ' + filePath); if (filePath === undefined) { return false; } if (TSCORE.FileOpener.isFileChanged()) { // TODO use closeFile method if (confirm($.i18n.t('ns.dialogs:closingEditedFileConfirm'))) { $('#saveDocument').hide(); _isEditMode = false; } else { return false; } } $('#fileTags').find('button').prop('disabled', false); $('#addTagFileViewer').prop('disabled', false); _isEditMode = false; _isFileChanged = false; _openedFilePath = filePath; //$("#selectedFilePath").val(_openedFilePath.replace("\\\\","\\")); if (isWeb) { var downloadLink; if (location.port === '') { downloadLink = location.protocol + '//' + location.hostname + _openedFilePath; } else { downloadLink = location.protocol + '//' + location.hostname + ':' + location.port + _openedFilePath; } $('#downloadFile').attr('href', downloadLink).attr('download', TSCORE.TagUtils.extractFileName(_openedFilePath)); } else { $('#downloadFile').attr('href', 'file:///' + _openedFilePath).attr('download', TSCORE.TagUtils.extractFileName(_openedFilePath)); } var fileExt = TSCORE.TagUtils.extractFileExtension(filePath); // Getting the viewer for the file extension/type var viewerExt = TSCORE.Config.getFileTypeViewer(fileExt); var editorExt = TSCORE.Config.getFileTypeEditor(fileExt); console.log('File Viewer: ' + viewerExt + ' File Editor: ' + editorExt); // Handling the edit button depending on existense of an editor if (editorExt === false || editorExt === 'false' || editorExt === '') { $('#editDocument').hide(); } else { $('#editDocument').show(); } var $viewer = $('#viewer'); $viewer.find('*').off(); $viewer.find('*').unbind(); $viewer.find('*').remove(); TSCORE.IO.checkAccessFileURLAllowed(); TSCORE.IO.getFileProperties(filePath.replace('\\\\', '\\')); updateUI(); if (editMode) { // opening file for editing editFile(filePath); } else { // opening file for viewing if (!viewerExt) { require([TSCORE.Config.getExtensionPath() + '/viewerText/extension.js'], function(viewer) { _tsEditor = viewer; _tsEditor.init(filePath, 'viewer', true); }); } else { require([TSCORE.Config.getExtensionPath() + '/' + viewerExt + '/extension.js'], function(viewer) { _tsEditor = viewer; _tsEditor.init(filePath, 'viewer', true); }); } } initTagSuggestionMenu(filePath); // Clearing file selection on file load and adding the current file path to the selection TSCORE.PerspectiveManager.clearSelectedFiles(); TSCORE.selectedFiles.push(filePath); _isFileOpened = true; TSCORE.openFileViewer(); // Handling the keybindings Mousetrap.unbind(TSCORE.Config.getSaveDocumentKeyBinding()); Mousetrap.bindGlobal(TSCORE.Config.getSaveDocumentKeyBinding(), function() { saveFile(); return false; }); Mousetrap.unbind(TSCORE.Config.getCloseViewerKeyBinding()); Mousetrap.bindGlobal(TSCORE.Config.getCloseViewerKeyBinding(), function() { closeFile(); return false; }); Mousetrap.unbind(TSCORE.Config.getReloadDocumentKeyBinding()); Mousetrap.bindGlobal(TSCORE.Config.getReloadDocumentKeyBinding(), function() { reloadFile(); return false; }); /*Mousetrap.unbind(TSCORE.Config.getDeleteDocumentKeyBinding()); Mousetrap.bind(TSCORE.Config.getDeleteDocumentKeyBinding(), function() { TSCORE.showFileDeleteDialog(_openedFilePath); return false; });*/ Mousetrap.unbind(TSCORE.Config.getPropertiesDocumentKeyBinding()); Mousetrap.bindGlobal(TSCORE.Config.getPropertiesDocumentKeyBinding(), function() { showFilePropertiesDialog(); return false; }); Mousetrap.unbind(TSCORE.Config.getPrevDocumentKeyBinding()); Mousetrap.bind(TSCORE.Config.getPrevDocumentKeyBinding(), function() { TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getPrevFile(_openedFilePath)); return false; }); Mousetrap.unbind(TSCORE.Config.getNextDocumentKeyBinding()); Mousetrap.bind(TSCORE.Config.getNextDocumentKeyBinding(), function() { TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getNextFile(_openedFilePath)); return false; }); Mousetrap.unbind(TSCORE.Config.getEditDocumentKeyBinding()); Mousetrap.bindGlobal(TSCORE.Config.getEditDocumentKeyBinding(), function() { editFile(_openedFilePath); return false; }); } function setFileProperties(fileProperties) { _openedFileProperties = fileProperties; } function updateEditorContent(fileContent) { console.log('Updating editor'); // with data: "+fileContent); _tsEditor.setContent(fileContent); } // Should return false if no editor found function getFileEditor(filePath) { var fileExt = TSCORE.TagUtils.extractFileExtension(filePath); // Getting the editor for the file extension/type var editorExt = TSCORE.Config.getFileTypeEditor(fileExt); console.log('File Editor: ' + editorExt); return editorExt; } function editFile(filePath) { console.log('Editing file: ' + filePath); $('#viewer').children().remove(); var editorExt = getFileEditor(filePath); try { require([TSCORE.Config.getExtensionPath() + '/' + editorExt + '/extension.js'], function(editr) { _tsEditor = editr; _tsEditor.init(filePath, 'viewer', false); }); _isEditMode = true; $('#editDocument').hide(); $('#saveDocument').show(); } catch (ex) { console.error('Loading editing extension failed: ' + ex); } } function reloadFile() { console.log('Reloading current file.'); TSCORE.FileOpener.openFile(_openedFilePath); } function saveFile() { console.log('Save current file: ' + _openedFilePath); var content = _tsEditor.getContent(); /*var title = TSCORE.TagUtils.extractTitle(_openedFilePath); if(title.length < 1 && content.length > 1) { title = content.substring(0,content.indexOf("\n")); if(title.length > 100) { title = title.substring(0,99); } }*/ TSCORE.IO.saveTextFile(_openedFilePath, content); } function updateUI() { $('#saveDocument').hide(); // Initialize File Extension var fileExtension = TSCORE.TagUtils.extractFileExtension(_openedFilePath); $('#fileExtText').text(fileExtension); // Initialize File Title Editor var title = TSCORE.TagUtils.extractTitle(_openedFilePath); var $fileTitle = $('#fileTitle'); $fileTitle.editable('destroy'); $fileTitle.text(title); $fileTitle.editable({ type: 'text', //placement: 'bottom', title: 'Change Title', mode: 'inline', success: function(response, newValue) { TSCORE.TagUtils.changeTitle(_openedFilePath, newValue); } }); // Generate tag & ext buttons // Appending tag buttons var tags = TSCORE.TagUtils.extractTags(_openedFilePath); var tagString = ''; tags.forEach(function(value, index) { if (index === 0) { tagString = value; } else { tagString = tagString + ',' + value; } }); generatedTagButtons = TSCORE.generateTagButtons(tagString, _openedFilePath); var $fileTags = $('#fileTags'); $fileTags.children().remove(); $fileTags.append(generatedTagButtons); $('#tagsContainer').droppable({ greedy: 'true', accept: '.tagButton', hoverClass: 'activeRow', drop: function(event, ui) { if (_isFileChanged) { TSCORE.showAlertDialog($.i18n.t('ns.dialogs:operationNotPermittedInEditModeAlert')); } else { console.log('Tagging file: ' + TSCORE.selectedTag + ' to ' + _openedFilePath); TSCORE.TagUtils.addTag([_openedFilePath], [TSCORE.selectedTag]); //$(ui.helper).remove(); } } }); // Init Tag Context Menus $fileTags.on('contextmenu click', '.tagButton', function() { TSCORE.hideAllDropDownMenus(); TSCORE.openTagMenu(this, $(this).attr('tag'), $(this).attr('filepath')); TSCORE.showContextMenu('#tagMenu', $(this)); return false; }); } function initTagSuggestionMenu(filePath) { var tags = TSCORE.TagUtils.extractTags(filePath); var suggTags = TSCORE.TagUtils.suggestTags(filePath); var tsMenu = $('#tagSuggestionsMenu'); tsMenu.children().remove(); tsMenu.attr('style', 'overflow-y: auto; max-height: 500px;'); tsMenu.append($('<li>', { class: 'dropdown-header', text: $.i18n.t('ns.common:tagOperations') }).append('<button type="button" class="close">\xD7</button>')); tsMenu.append($('<li>').append($('<a>', { title: $.i18n.t('ns.common:addRemoveTagsTooltip'), filepath: filePath, text: ' ' + $.i18n.t('ns.common:addRemoveTags') }).prepend('<i class=\'fa fa-tag\'></i>').click(function() { TSCORE.PerspectiveManager.clearSelectedFiles(); TSCORE.selectedFiles.push(filePath); TSCORE.showAddTagsDialog(); }))); tsMenu.append($('<li>', { class: 'dropdown-header', text: $.i18n.t('ns.common:suggestedTags') })); // Add tag suggestion based on the last modified date if (_openedFileProperties !== undefined && _openedFileProperties.lmdt !== undefined) { suggTags.push(TSCORE.TagUtils.formatDateTime4Tag(_openedFileProperties.lmdt)); suggTags.push(TSCORE.TagUtils.formatDateTime4Tag(_openedFileProperties.lmdt, true)); } // Adding context menu entries for creating tags according to the suggested tags for (var i = 0; i < suggTags.length; i++) { // Ignoring the tags already assigned to a file if (tags.indexOf(suggTags[i]) < 0) { tsMenu.append($('<li>', { name: suggTags[i] }).append($('<a>', {}).append($('<button>', { title: $.i18n.t('ns.common:tagWithTooltip', { tagName: suggTags[i] }), 'class': 'btn btn-sm btn-success tagButton', filepath: filePath, tagname: suggTags[i], text: suggTags[i] }).click(function() { var tagName = $(this).attr('tagname'); var filePath = $(this).attr('filepath'); console.log('Tag suggestion clicked: ' + tagName); TSCORE.TagUtils.writeTagsToFile(filePath, [tagName]); return false; })))); // jshint ignore:line } } } // TODO Make file properties dialog accessible from core function showFilePropertiesDialog() { require(['text!templates/FilePropertiesDialog.html'], function(uiTPL) { if ($('#dialogFileProperties').length < 1) { var uiTemplate = Handlebars.compile(uiTPL); $('body').append(uiTemplate()); } $('#filePathProperty').val(_openedFileProperties.path); $('#fileSizeProperty').val(_openedFileProperties.size); $('#fileLMDTProperty').val(new Date(_openedFileProperties.lmdt)); var $fileTagsProperty = $('#fileTagsProperty'); $fileTagsProperty.children().remove(); $fileTagsProperty.append(generatedTagButtons); $fileTagsProperty.find('.caret').hide(); // hiding the dropdown trigger $('#dialogFileProperties').i18n().modal({ backdrop: 'static', show: true }); }); } // Public API definition exports.initUI = initUI; exports.openFile = openFile; exports.openFileOnStartup = openFileOnStartup; exports.closeFile = closeFile; exports.saveFile = saveFile; exports.isFileOpened = isFileOpened; exports.isFileEdited = isFileEdited; exports.isFileChanged = isFileChanged; exports.setFileChanged = setFileChanged; exports.getOpenedFilePath = getOpenedFilePath; exports.updateEditorContent = updateEditorContent; exports.setFileProperties = setFileProperties; });
data/js/fileopener.js
/* Copyright (c) 2012-2015 The TagSpaces Authors. All rights reserved. * Use of this source code is governed by a AGPL3 license that * can be found in the LICENSE file. */ /* undef: true, unused: false */ /* global define, Mousetrap, Handlebars */ define(function(require, exports, module) { 'use strict'; console.log('Loading fileopener...'); var TSCORE = require('tscore'); var _openedFilePath; var _openedFileProperties; var _isFileOpened = false; var _isFileChanged = false; var _tsEditor; var generatedTagButtons; // Backup cancel button <!--button type="button" class="btn editable-cancel"><i class="fa fa-times fa-lg"></i></button--> $.fn.editableform.buttons = '<button type="submit" class="btn btn-primary editable-submit"><i class="fa fa-check fa-lg"></i></button>'; // If a file is currently opened for editing, this var should be true var _isEditMode = false; window.onbeforeunload = function() { if (_isFileChanged) { return "Confirm close"; } }; function initUI() { $('#editDocument').click(function() { editFile(_openedFilePath); }); $('#saveDocument').click(function() { saveFile(); }); $('#closeOpenedFile').click(function() { closeFile(); }); $('#nextFileButton').click(function() { TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getNextFile(_openedFilePath)); }); $('#prevFileButton').click(function() { TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getPrevFile(_openedFilePath)); }); $('#closeFile').click(function() { closeFile(); }); $('#reloadFile').click(function() { TSCORE.FileOpener.openFile(_openedFilePath); }); $('#sendFile').click(function() { TSCORE.IO.sendFile(_openedFilePath); }); $('#openFileInNewWindow').click(function() { if (isWeb) { if (location.port === '') { window.open(location.protocol + '//' + location.hostname + _openedFilePath); } else { window.open(location.protocol + '//' + location.hostname + ':' + location.port + _openedFilePath); } } else { window.open('file:///' + _openedFilePath); } }); $('#printFile').click(function() { $('iframe').get(0).contentWindow.print(); }); $('#tagFile').click(function() { if (_isFileChanged) { TSCORE.showAlertDialog($.i18n.t('ns.dialogs:operationNotPermittedInEditModeAlert')); } else { TSCORE.PerspectiveManager.clearSelectedFiles(); TSCORE.selectedFiles.push(_openedFilePath); TSCORE.showAddTagsDialog(); } }); $('#suggestTagsFile').click(function() { $('tagSuggestionsMenu').dropdown('toggle'); }); $('#renameFile').click(function() { if (_isFileChanged) { TSCORE.showAlertDialog($.i18n.t('ns.dialogs:operationNotPermittedInEditModeAlert')); } else { TSCORE.showFileRenameDialog(_openedFilePath); } }); $('#duplicateFile').click(function() { var currentDateTime = TSCORE.TagUtils.formatDateTime4Tag(new Date(), true); var fileNameWithOutExt = TSCORE.TagUtils.extractFileNameWithoutExt(_openedFilePath); var fileExt = TSCORE.TagUtils.extractFileExtension(_openedFilePath); var newFilePath = TSCORE.currentPath + TSCORE.dirSeparator + fileNameWithOutExt + '_' + currentDateTime + '.' + fileExt; TSCORE.IO.copyFile(_openedFilePath, newFilePath); }); $('#toggleFullWidthButton').click(function() { TSCORE.toggleFullWidth(); }); $('#deleteFile').click(function() { TSCORE.showFileDeleteDialog(_openedFilePath); }); $('#openNatively').click(function() { TSCORE.IO.openFile(_openedFilePath); }); $('#openDirectory').click(function() { TSCORE.IO.openDirectory(TSCORE.TagUtils.extractParentDirectoryPath(_openedFilePath)); }); $('#fullscreenFile').click(function() { var docElm = $('#viewer')[0]; if (docElm.requestFullscreen) { docElm.requestFullscreen(); } else if (docElm.mozRequestFullScreen) { docElm.mozRequestFullScreen(); } else if (docElm.webkitRequestFullScreen) { docElm.webkitRequestFullScreen(); } }); $('#openProperties').click(function() { showFilePropertiesDialog(); }); } function isFileChanged() { return _isFileChanged; } function setFileChanged(value) { var $fileExt = $('#fileExtText'); var $fileTitle = $('#fileTitle'); if (value && !_isFileChanged) { $fileExt.text($fileExt.text() + '*'); $fileTitle.editable('disable'); $('#fileTags').find('button').prop('disabled', true); $('#addTagFileViewer').prop('disabled', true); } if (!value) { $fileExt.text(TSCORE.TagUtils.extractFileExtension(_openedFilePath)); $fileTitle.editable('enable'); $('#fileTags').find('button').prop('disabled', false); $('#addTagFileViewer').prop('disabled', false); } _isFileChanged = value; } function isFileEdited() { return _isEditMode; } function isFileOpened() { return _isFileOpened; } function getOpenedFilePath() { return _openedFilePath; } function closeFile(forceClose) { if (isFileChanged()) { if (forceClose) { cleanViewer(); } else { TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:closingEditedFileTitleConfirm'), $.i18n.t('ns.dialogs:closingEditedFileContentConfirm'), function() { cleanViewer(); }); } } else { cleanViewer(); } } function cleanViewer() { //TSCORE.PerspectiveManager.clearSelectedFiles(); TSCORE.closeFileViewer(); // Cleaning the viewer/editor //document.getElementById("viewer").innerHTML = ""; $('#viewer').find('*').off().unbind(); $('#viewer').find('iframe').remove(); $('#viewer').find('*').children().remove(); _isFileOpened = false; _isEditMode = false; _isFileChanged = false; Mousetrap.unbind(TSCORE.Config.getEditDocumentKeyBinding()); Mousetrap.unbind(TSCORE.Config.getSaveDocumentKeyBinding()); Mousetrap.unbind(TSCORE.Config.getCloseViewerKeyBinding()); Mousetrap.unbind(TSCORE.Config.getReloadDocumentKeyBinding()); Mousetrap.unbind(TSCORE.Config.getDeleteDocumentKeyBinding()); Mousetrap.unbind(TSCORE.Config.getPropertiesDocumentKeyBinding()); Mousetrap.unbind(TSCORE.Config.getPrevDocumentKeyBinding()); Mousetrap.unbind(TSCORE.Config.getNextDocumentKeyBinding()); } function openFileOnStartup(filePath) { TSCORE.Config.setLastOpenedLocation(undefined); // quick and dirty solution, should use flag later TSCORE.toggleFullWidth(); TSCORE.FileOpener.openFile(filePath); TSCORE.openLocation(TSCORE.TagUtils.extractContainingDirectoryPath(filePath)); } function openFile(filePath, editMode) { console.log('Opening file: ' + filePath); if (filePath === undefined) { return false; } if (TSCORE.FileOpener.isFileChanged()) { // TODO use closeFile method if (confirm($.i18n.t('ns.dialogs:closingEditedFileConfirm'))) { $('#saveDocument').hide(); _isEditMode = false; } else { return false; } } _isEditMode = false; _isFileChanged = false; _openedFilePath = filePath; //$("#selectedFilePath").val(_openedFilePath.replace("\\\\","\\")); if (isWeb) { var downloadLink; if (location.port === '') { downloadLink = location.protocol + '//' + location.hostname + _openedFilePath; } else { downloadLink = location.protocol + '//' + location.hostname + ':' + location.port + _openedFilePath; } $('#downloadFile').attr('href', downloadLink).attr('download', TSCORE.TagUtils.extractFileName(_openedFilePath)); } else { $('#downloadFile').attr('href', 'file:///' + _openedFilePath).attr('download', TSCORE.TagUtils.extractFileName(_openedFilePath)); } var fileExt = TSCORE.TagUtils.extractFileExtension(filePath); // Getting the viewer for the file extension/type var viewerExt = TSCORE.Config.getFileTypeViewer(fileExt); var editorExt = TSCORE.Config.getFileTypeEditor(fileExt); console.log('File Viewer: ' + viewerExt + ' File Editor: ' + editorExt); // Handling the edit button depending on existense of an editor if (editorExt === false || editorExt === 'false' || editorExt === '') { $('#editDocument').hide(); } else { $('#editDocument').show(); } var $viewer = $('#viewer'); $viewer.find('*').off(); $viewer.find('*').unbind(); $viewer.find('*').remove(); TSCORE.IO.checkAccessFileURLAllowed(); TSCORE.IO.getFileProperties(filePath.replace('\\\\', '\\')); updateUI(); if (editMode) { // opening file for editing editFile(filePath); } else { // opening file for viewing if (!viewerExt) { require([TSCORE.Config.getExtensionPath() + '/viewerText/extension.js'], function(viewer) { _tsEditor = viewer; _tsEditor.init(filePath, 'viewer', true); }); } else { require([TSCORE.Config.getExtensionPath() + '/' + viewerExt + '/extension.js'], function(viewer) { _tsEditor = viewer; _tsEditor.init(filePath, 'viewer', true); }); } } initTagSuggestionMenu(filePath); // Clearing file selection on file load and adding the current file path to the selection TSCORE.PerspectiveManager.clearSelectedFiles(); TSCORE.selectedFiles.push(filePath); _isFileOpened = true; TSCORE.openFileViewer(); // Handling the keybindings Mousetrap.unbind(TSCORE.Config.getSaveDocumentKeyBinding()); Mousetrap.bindGlobal(TSCORE.Config.getSaveDocumentKeyBinding(), function() { saveFile(); return false; }); Mousetrap.unbind(TSCORE.Config.getCloseViewerKeyBinding()); Mousetrap.bindGlobal(TSCORE.Config.getCloseViewerKeyBinding(), function() { closeFile(); return false; }); Mousetrap.unbind(TSCORE.Config.getReloadDocumentKeyBinding()); Mousetrap.bindGlobal(TSCORE.Config.getReloadDocumentKeyBinding(), function() { reloadFile(); return false; }); /*Mousetrap.unbind(TSCORE.Config.getDeleteDocumentKeyBinding()); Mousetrap.bind(TSCORE.Config.getDeleteDocumentKeyBinding(), function() { TSCORE.showFileDeleteDialog(_openedFilePath); return false; });*/ Mousetrap.unbind(TSCORE.Config.getPropertiesDocumentKeyBinding()); Mousetrap.bindGlobal(TSCORE.Config.getPropertiesDocumentKeyBinding(), function() { showFilePropertiesDialog(); return false; }); Mousetrap.unbind(TSCORE.Config.getPrevDocumentKeyBinding()); Mousetrap.bind(TSCORE.Config.getPrevDocumentKeyBinding(), function() { TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getPrevFile(_openedFilePath)); return false; }); Mousetrap.unbind(TSCORE.Config.getNextDocumentKeyBinding()); Mousetrap.bind(TSCORE.Config.getNextDocumentKeyBinding(), function() { TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getNextFile(_openedFilePath)); return false; }); Mousetrap.unbind(TSCORE.Config.getEditDocumentKeyBinding()); Mousetrap.bindGlobal(TSCORE.Config.getEditDocumentKeyBinding(), function() { editFile(_openedFilePath); return false; }); } function setFileProperties(fileProperties) { _openedFileProperties = fileProperties; } function updateEditorContent(fileContent) { console.log('Updating editor'); // with data: "+fileContent); _tsEditor.setContent(fileContent); } // Should return false if no editor found function getFileEditor(filePath) { var fileExt = TSCORE.TagUtils.extractFileExtension(filePath); // Getting the editor for the file extension/type var editorExt = TSCORE.Config.getFileTypeEditor(fileExt); console.log('File Editor: ' + editorExt); return editorExt; } function editFile(filePath) { console.log('Editing file: ' + filePath); $('#viewer').children().remove(); var editorExt = getFileEditor(filePath); try { require([TSCORE.Config.getExtensionPath() + '/' + editorExt + '/extension.js'], function(editr) { _tsEditor = editr; _tsEditor.init(filePath, 'viewer', false); }); _isEditMode = true; $('#editDocument').hide(); $('#saveDocument').show(); } catch (ex) { console.error('Loading editing extension failed: ' + ex); } } function reloadFile() { console.log('Reloading current file.'); TSCORE.FileOpener.openFile(_openedFilePath); } function saveFile() { console.log('Save current file: ' + _openedFilePath); var content = _tsEditor.getContent(); /*var title = TSCORE.TagUtils.extractTitle(_openedFilePath); if(title.length < 1 && content.length > 1) { title = content.substring(0,content.indexOf("\n")); if(title.length > 100) { title = title.substring(0,99); } }*/ TSCORE.IO.saveTextFile(_openedFilePath, content); } function updateUI() { $('#saveDocument').hide(); // Initialize File Extension var fileExtension = TSCORE.TagUtils.extractFileExtension(_openedFilePath); $('#fileExtText').text(fileExtension); // Initialize File Title Editor var title = TSCORE.TagUtils.extractTitle(_openedFilePath); var $fileTitle = $('#fileTitle'); $fileTitle.editable('destroy'); $fileTitle.text(title); $fileTitle.editable({ type: 'text', //placement: 'bottom', title: 'Change Title', mode: 'inline', success: function(response, newValue) { TSCORE.TagUtils.changeTitle(_openedFilePath, newValue); } }); // Generate tag & ext buttons // Appending tag buttons var tags = TSCORE.TagUtils.extractTags(_openedFilePath); var tagString = ''; tags.forEach(function(value, index) { if (index === 0) { tagString = value; } else { tagString = tagString + ',' + value; } }); generatedTagButtons = TSCORE.generateTagButtons(tagString, _openedFilePath); var $fileTags = $('#fileTags'); $fileTags.children().remove(); $fileTags.append(generatedTagButtons); $('#tagsContainer').droppable({ greedy: 'true', accept: '.tagButton', hoverClass: 'activeRow', drop: function(event, ui) { if (_isFileChanged) { TSCORE.showAlertDialog($.i18n.t('ns.dialogs:operationNotPermittedInEditModeAlert')); } else { console.log('Tagging file: ' + TSCORE.selectedTag + ' to ' + _openedFilePath); TSCORE.TagUtils.addTag([_openedFilePath], [TSCORE.selectedTag]); //$(ui.helper).remove(); } } }); // Init Tag Context Menus $fileTags.on('contextmenu click', '.tagButton', function() { TSCORE.hideAllDropDownMenus(); TSCORE.openTagMenu(this, $(this).attr('tag'), $(this).attr('filepath')); TSCORE.showContextMenu('#tagMenu', $(this)); return false; }); } function initTagSuggestionMenu(filePath) { var tags = TSCORE.TagUtils.extractTags(filePath); var suggTags = TSCORE.TagUtils.suggestTags(filePath); var tsMenu = $('#tagSuggestionsMenu'); tsMenu.children().remove(); tsMenu.attr('style', 'overflow-y: auto; max-height: 500px;'); tsMenu.append($('<li>', { class: 'dropdown-header', text: $.i18n.t('ns.common:tagOperations') }).append('<button type="button" class="close">\xD7</button>')); tsMenu.append($('<li>').append($('<a>', { title: $.i18n.t('ns.common:addRemoveTagsTooltip'), filepath: filePath, text: ' ' + $.i18n.t('ns.common:addRemoveTags') }).prepend('<i class=\'fa fa-tag\'></i>').click(function() { TSCORE.PerspectiveManager.clearSelectedFiles(); TSCORE.selectedFiles.push(filePath); TSCORE.showAddTagsDialog(); }))); tsMenu.append($('<li>', { class: 'dropdown-header', text: $.i18n.t('ns.common:suggestedTags') })); // Add tag suggestion based on the last modified date if (_openedFileProperties !== undefined && _openedFileProperties.lmdt !== undefined) { suggTags.push(TSCORE.TagUtils.formatDateTime4Tag(_openedFileProperties.lmdt)); suggTags.push(TSCORE.TagUtils.formatDateTime4Tag(_openedFileProperties.lmdt, true)); } // Adding context menu entries for creating tags according to the suggested tags for (var i = 0; i < suggTags.length; i++) { // Ignoring the tags already assigned to a file if (tags.indexOf(suggTags[i]) < 0) { tsMenu.append($('<li>', { name: suggTags[i] }).append($('<a>', {}).append($('<button>', { title: $.i18n.t('ns.common:tagWithTooltip', { tagName: suggTags[i] }), 'class': 'btn btn-sm btn-success tagButton', filepath: filePath, tagname: suggTags[i], text: suggTags[i] }).click(function() { var tagName = $(this).attr('tagname'); var filePath = $(this).attr('filepath'); console.log('Tag suggestion clicked: ' + tagName); TSCORE.TagUtils.writeTagsToFile(filePath, [tagName]); return false; })))); // jshint ignore:line } } } // TODO Make file properties dialog accessible from core function showFilePropertiesDialog() { require(['text!templates/FilePropertiesDialog.html'], function(uiTPL) { if ($('#dialogFileProperties').length < 1) { var uiTemplate = Handlebars.compile(uiTPL); $('body').append(uiTemplate()); } $('#filePathProperty').val(_openedFileProperties.path); $('#fileSizeProperty').val(_openedFileProperties.size); $('#fileLMDTProperty').val(new Date(_openedFileProperties.lmdt)); var $fileTagsProperty = $('#fileTagsProperty'); $fileTagsProperty.children().remove(); $fileTagsProperty.append(generatedTagButtons); $fileTagsProperty.find('.caret').hide(); // hiding the dropdown trigger $('#dialogFileProperties').i18n().modal({ backdrop: 'static', show: true }); }); } // Public API definition exports.initUI = initUI; exports.openFile = openFile; exports.openFileOnStartup = openFileOnStartup; exports.closeFile = closeFile; exports.saveFile = saveFile; exports.isFileOpened = isFileOpened; exports.isFileEdited = isFileEdited; exports.isFileChanged = isFileChanged; exports.setFileChanged = setFileChanged; exports.getOpenedFilePath = getOpenedFilePath; exports.updateEditorContent = updateEditorContent; exports.setFileProperties = setFileProperties; });
fixing disabled tagging functionality in the file opener
data/js/fileopener.js
fixing disabled tagging functionality in the file opener
<ide><path>ata/js/fileopener.js <ide> return false; <ide> } <ide> } <add> <add> $('#fileTags').find('button').prop('disabled', false); <add> $('#addTagFileViewer').prop('disabled', false); <add> <ide> _isEditMode = false; <ide> _isFileChanged = false; <ide> _openedFilePath = filePath;
Java
apache-2.0
0a2a41c677f0be3d2076036ebe3d6631d5d0e4d7
0
gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom
/* * Copyright 2016 Crown Copyright * * 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 stroom.search.elastic; import stroom.search.elastic.shared.ElasticConnectionConfig; import stroom.search.elastic.shared.ElasticConnectionTestAction; import stroom.task.server.AbstractTaskHandler; import stroom.task.server.TaskHandlerBean; import stroom.util.shared.SharedString; import stroom.util.spring.StroomScope; import org.elasticsearch.ResourceNotFoundException; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.core.MainResponse; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.client.indices.GetIndexResponse; import org.springframework.context.annotation.Scope; @TaskHandlerBean(task = ElasticConnectionTestAction.class) @Scope(StroomScope.TASK) public class ElasticConnectionTestHandler extends AbstractTaskHandler<ElasticConnectionTestAction, SharedString> { @Override public SharedString exec(final ElasticConnectionTestAction action) { try { final ElasticConnectionConfig connectionConfig = action.getElasticIndex().getConnectionConfig(); final RestHighLevelClient elasticClient = new ElasticClientFactory().create(connectionConfig); MainResponse response = elasticClient.info(RequestOptions.DEFAULT); final StringBuilder sb = new StringBuilder(); sb.append("Cluster URLs: "); sb.append(connectionConfig.getConnectionUrls()); sb.append("\nCluster name: "); sb.append(response.getClusterName()); sb.append("\nCluster UUID: "); sb.append(response.getClusterUuid()); sb.append("\nNode name: "); sb.append(response.getNodeName()); sb.append("\nVersion: "); sb.append(response.getVersion().getNumber()); // Check whether the specified index exists final String indexName = action.getElasticIndex().getIndexName(); final GetIndexRequest getIndexRequest = new GetIndexRequest(indexName); GetIndexResponse getIndexResponse = elasticClient.indices().get(getIndexRequest, RequestOptions.DEFAULT); if (getIndexResponse.getIndices().length < 1) { throw new ResourceNotFoundException("Index '" + indexName + "' was not found"); } return SharedString.wrap(sb.toString()); } catch (final Exception e) { throw new RuntimeException(e.getMessage(), e); } } }
stroom-search/stroom-search-elastic/src/main/java/stroom/search/elastic/ElasticConnectionTestHandler.java
/* * Copyright 2016 Crown Copyright * * 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 stroom.search.elastic; import stroom.search.elastic.shared.ElasticConnectionConfig; import stroom.search.elastic.shared.ElasticConnectionTestAction; import stroom.task.server.AbstractTaskHandler; import stroom.task.server.TaskHandlerBean; import stroom.util.shared.SharedString; import stroom.util.spring.StroomScope; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.core.MainResponse; import org.springframework.context.annotation.Scope; @TaskHandlerBean(task = ElasticConnectionTestAction.class) @Scope(StroomScope.TASK) public class ElasticConnectionTestHandler extends AbstractTaskHandler<ElasticConnectionTestAction, SharedString> { @Override public SharedString exec(final ElasticConnectionTestAction action) { try { final ElasticConnectionConfig connectionConfig = action.getElasticIndex().getConnectionConfig(); final RestHighLevelClient elasticClient = new ElasticClientFactory().create(connectionConfig); MainResponse response = elasticClient.info(RequestOptions.DEFAULT); final StringBuilder sb = new StringBuilder(); sb.append("Cluster URLs: "); sb.append(connectionConfig.getConnectionUrls()); sb.append("\nCluster name: "); sb.append(response.getClusterName()); sb.append("\nCluster UUID: "); sb.append(response.getClusterUuid()); sb.append("\nNode name: "); sb.append(response.getNodeName()); sb.append("\nVersion: "); sb.append(response.getVersion().getNumber()); return SharedString.wrap(sb.toString()); } catch (final Exception e) { throw new RuntimeException(e.getMessage(), e); } } }
Test ES index exists during connection test
stroom-search/stroom-search-elastic/src/main/java/stroom/search/elastic/ElasticConnectionTestHandler.java
Test ES index exists during connection test
<ide><path>troom-search/stroom-search-elastic/src/main/java/stroom/search/elastic/ElasticConnectionTestHandler.java <ide> import stroom.util.shared.SharedString; <ide> import stroom.util.spring.StroomScope; <ide> <add>import org.elasticsearch.ResourceNotFoundException; <ide> import org.elasticsearch.client.RequestOptions; <ide> import org.elasticsearch.client.RestHighLevelClient; <ide> import org.elasticsearch.client.core.MainResponse; <add>import org.elasticsearch.client.indices.GetIndexRequest; <add>import org.elasticsearch.client.indices.GetIndexResponse; <ide> import org.springframework.context.annotation.Scope; <ide> <ide> @TaskHandlerBean(task = ElasticConnectionTestAction.class) <ide> sb.append("\nVersion: "); <ide> sb.append(response.getVersion().getNumber()); <ide> <add> // Check whether the specified index exists <add> final String indexName = action.getElasticIndex().getIndexName(); <add> final GetIndexRequest getIndexRequest = new GetIndexRequest(indexName); <add> GetIndexResponse getIndexResponse = elasticClient.indices().get(getIndexRequest, RequestOptions.DEFAULT); <add> if (getIndexResponse.getIndices().length < 1) { <add> throw new ResourceNotFoundException("Index '" + indexName + "' was not found"); <add> } <add> <ide> return SharedString.wrap(sb.toString()); <ide> } catch (final Exception e) { <ide> throw new RuntimeException(e.getMessage(), e);
Java
mit
error: pathspec 'src/main/java/leetcode/Problem722.java' did not match any file(s) known to git
2bb733ed0b511f3504702c276358e28c2c689e92
1
fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode
package leetcode; import java.util.List; /** * https://leetcode.com/problems/remove-comments/ */ public class Problem722 { public List<String> removeComments(String[] source) { return null; } public static void main(String[] args) { Problem722 prob = new Problem722(); System.out.println(prob.removeComments(new String[]{ "/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"})); // ["int main()","{ "," ","int a, b, c;","a = b + c;","}"] System.out.println(prob.removeComments(new String[]{"a/*comment", "line", "more_comment*/b"})); // [ab] } }
src/main/java/leetcode/Problem722.java
Skeleton for problem 722
src/main/java/leetcode/Problem722.java
Skeleton for problem 722
<ide><path>rc/main/java/leetcode/Problem722.java <add>package leetcode; <add> <add>import java.util.List; <add> <add>/** <add> * https://leetcode.com/problems/remove-comments/ <add> */ <add>public class Problem722 { <add> public List<String> removeComments(String[] source) { <add> return null; <add> } <add> <add> public static void main(String[] args) { <add> Problem722 prob = new Problem722(); <add> System.out.println(prob.removeComments(new String[]{ <add> "/*Test program */", <add> "int main()", "{ ", <add> " // variable declaration ", <add> "int a, b, c;", <add> "/* This is a test", <add> " multiline ", <add> " comment for ", <add> " testing */", <add> "a = b + c;", "}"})); // ["int main()","{ "," ","int a, b, c;","a = b + c;","}"] <add> System.out.println(prob.removeComments(new String[]{"a/*comment", "line", "more_comment*/b"})); // [ab] <add> } <add>}
Java
apache-2.0
3cf36ff3d43c096196646104b353e5d92ad32bda
0
apiman/apiman,msavy/apiman,apiman/apiman,msavy/apiman,msavy/apiman,EricWittmann/apiman,apiman/apiman,apiman/apiman,EricWittmann/apiman,EricWittmann/apiman,apiman/apiman,msavy/apiman,EricWittmann/apiman,EricWittmann/apiman,msavy/apiman
/* * Copyright 2014 JBoss 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 io.apiman.manager.api.rest.impl; import com.fasterxml.jackson.databind.ObjectMapper; import io.apiman.common.util.crypt.DataEncryptionContext; import io.apiman.common.util.crypt.IDataEncrypter; import io.apiman.gateway.engine.beans.SystemStatus; import io.apiman.manager.api.beans.BeanUtils; import io.apiman.manager.api.beans.gateways.GatewayBean; import io.apiman.manager.api.beans.gateways.GatewayType; import io.apiman.manager.api.beans.gateways.NewGatewayBean; import io.apiman.manager.api.beans.gateways.RestGatewayConfigBean; import io.apiman.manager.api.beans.gateways.UpdateGatewayBean; import io.apiman.manager.api.beans.summary.GatewaySummaryBean; import io.apiman.manager.api.beans.summary.GatewayTestResultBean; import io.apiman.manager.api.core.IStorage; import io.apiman.manager.api.core.IStorageQuery; import io.apiman.manager.api.core.exceptions.StorageException; import io.apiman.manager.api.core.logging.ApimanLogger; import io.apiman.common.logging.IApimanLogger; import io.apiman.manager.api.gateway.GatewayAuthenticationException; import io.apiman.manager.api.gateway.IGatewayLink; import io.apiman.manager.api.gateway.IGatewayLinkFactory; import io.apiman.manager.api.rest.contract.IGatewayResource; import io.apiman.manager.api.rest.contract.exceptions.AbstractRestException; import io.apiman.manager.api.rest.contract.exceptions.GatewayAlreadyExistsException; import io.apiman.manager.api.rest.contract.exceptions.GatewayNotFoundException; import io.apiman.manager.api.rest.contract.exceptions.NotAuthorizedException; import io.apiman.manager.api.rest.contract.exceptions.SystemErrorException; import io.apiman.manager.api.rest.impl.i18n.Messages; import io.apiman.manager.api.rest.impl.util.ExceptionFactory; import io.apiman.manager.api.security.ISecurityContext; import java.util.Date; import java.util.List; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; /** * Implementation of the Gateway API. * * @author [email protected] */ @ApplicationScoped public class GatewayResourceImpl implements IGatewayResource { @Inject IStorage storage; @Inject IStorageQuery query; @Inject ISecurityContext securityContext; @Inject IGatewayLinkFactory gatewayLinkFactory; @Inject @ApimanLogger(GatewayResourceImpl.class) IApimanLogger log; @Inject IDataEncrypter encrypter; private static final ObjectMapper mapper = new ObjectMapper(); /** * Constructor. */ public GatewayResourceImpl() { } /** * @see io.apiman.manager.api.rest.contract.IGatewayResource#test(io.apiman.manager.api.beans.gateways.NewGatewayBean) */ @Override public GatewayTestResultBean test(NewGatewayBean bean) throws NotAuthorizedException { if (!securityContext.isAdmin()) throw ExceptionFactory.notAuthorizedException(); GatewayTestResultBean rval = new GatewayTestResultBean(); try { GatewayBean testGateway = new GatewayBean(); testGateway.setName(bean.getName()); testGateway.setType(bean.getType()); testGateway.setConfiguration(bean.getConfiguration()); IGatewayLink gatewayLink = gatewayLinkFactory.create(testGateway); SystemStatus status = gatewayLink.getStatus(); String detail = mapper.writer().writeValueAsString(status); rval.setSuccess(true); rval.setDetail(detail); } catch (GatewayAuthenticationException e) { rval.setSuccess(false); rval.setDetail(Messages.i18n.format("GatewayResourceImpl.AuthenticationFailed")); //$NON-NLS-1$ } catch (Exception e) { rval.setSuccess(false); rval.setDetail(e.getMessage()); } return rval; } /** * @see io.apiman.manager.api.rest.contract.IGatewayResource#list() */ @Override public List<GatewaySummaryBean> list() throws NotAuthorizedException { try { return query.listGateways(); } catch (StorageException e) { throw new SystemErrorException(e); } } /** * @see io.apiman.manager.api.rest.contract.IGatewayResource#create(io.apiman.manager.api.beans.gateways.NewGatewayBean) */ @Override public GatewayBean create(NewGatewayBean bean) throws GatewayAlreadyExistsException { if (!securityContext.isAdmin()) throw ExceptionFactory.notAuthorizedException(); Date now = new Date(); GatewayBean gateway = new GatewayBean(); gateway.setId(BeanUtils.idFromName(bean.getName())); gateway.setName(bean.getName()); gateway.setDescription(bean.getDescription()); gateway.setType(bean.getType()); gateway.setConfiguration(bean.getConfiguration()); gateway.setCreatedBy(securityContext.getCurrentUser()); gateway.setCreatedOn(now); gateway.setModifiedBy(securityContext.getCurrentUser()); gateway.setModifiedOn(now); try { storage.beginTx(); if (storage.getGateway(gateway.getId()) != null) { throw ExceptionFactory.gatewayAlreadyExistsException(gateway.getName()); } // Store/persist the new gateway encryptPasswords(gateway); storage.createGateway(gateway); storage.commitTx(); } catch (AbstractRestException e) { storage.rollbackTx(); throw e; } catch (Exception e) { storage.rollbackTx(); throw new SystemErrorException(e); } decryptPasswords(gateway); log.debug(String.format("Successfully created new gateway %s: %s", gateway.getName(), gateway)); //$NON-NLS-1$ return gateway; } /** * @see io.apiman.manager.api.rest.contract.IGatewayResource#get(java.lang.String) */ @Override public GatewayBean get(String gatewayId) throws GatewayNotFoundException, NotAuthorizedException { try { storage.beginTx(); GatewayBean bean = storage.getGateway(gatewayId); if (bean == null) { throw ExceptionFactory.gatewayNotFoundException(gatewayId); } if (!securityContext.isAdmin()) { bean.setConfiguration(null); } else { decryptPasswords(bean); } storage.commitTx(); log.debug(String.format("Successfully fetched gateway %s: %s", bean.getName(), bean)); //$NON-NLS-1$ return bean; } catch (AbstractRestException e) { storage.rollbackTx(); throw e; } catch (Exception e) { storage.rollbackTx(); throw new SystemErrorException(e); } } /** * @see io.apiman.manager.api.rest.contract.IGatewayResource#update(java.lang.String, io.apiman.manager.api.beans.gateways.UpdateGatewayBean) */ @Override public void update(String gatewayId, UpdateGatewayBean bean) throws GatewayNotFoundException, NotAuthorizedException { if (!securityContext.isAdmin()) throw ExceptionFactory.notAuthorizedException(); try { storage.beginTx(); Date now = new Date(); GatewayBean gbean = storage.getGateway(gatewayId); if (gbean == null) { throw ExceptionFactory.gatewayNotFoundException(gatewayId); } gbean.setModifiedBy(securityContext.getCurrentUser()); gbean.setModifiedOn(now); if (bean.getDescription() != null) gbean.setDescription(bean.getDescription()); if (bean.getType() != null) gbean.setType(bean.getType()); if (bean.getConfiguration() != null) gbean.setConfiguration(bean.getConfiguration()); encryptPasswords(gbean); storage.updateGateway(gbean); storage.commitTx(); log.debug(String.format("Successfully updated gateway %s: %s", gbean.getName(), gbean)); //$NON-NLS-1$ } catch (AbstractRestException e) { storage.rollbackTx(); throw e; } catch (Exception e) { storage.rollbackTx(); throw new SystemErrorException(e); } } /** * @see io.apiman.manager.api.rest.contract.IGatewayResource#delete(java.lang.String) */ @Override public void delete(String gatewayId) throws GatewayNotFoundException, NotAuthorizedException { if (!securityContext.isAdmin()) throw ExceptionFactory.notAuthorizedException(); try { storage.beginTx(); GatewayBean gbean = storage.getGateway(gatewayId); if (gbean == null) { throw ExceptionFactory.gatewayNotFoundException(gatewayId); } storage.deleteGateway(gbean); storage.commitTx(); log.debug(String.format("Successfully deleted gateway %s: %s", gbean.getName(), gbean)); //$NON-NLS-1$ } catch (AbstractRestException e) { storage.rollbackTx(); throw e; } catch (Exception e) { storage.rollbackTx(); throw new SystemErrorException(e); } } /** * @param bean */ private void encryptPasswords(GatewayBean bean) { if (bean.getConfiguration() == null) { return; } try { if (bean.getType() == GatewayType.REST) { RestGatewayConfigBean configBean = mapper.readValue(bean.getConfiguration(), RestGatewayConfigBean.class); configBean.setPassword(encrypter.encrypt(configBean.getPassword(), new DataEncryptionContext())); bean.setConfiguration(mapper.writeValueAsString(configBean)); } } catch (Exception e) { throw new RuntimeException(e); } } /** * @param bean */ private void decryptPasswords(GatewayBean bean) { if (bean.getConfiguration() == null) { return; } try { if (bean.getType() == GatewayType.REST) { RestGatewayConfigBean configBean = mapper.readValue(bean.getConfiguration(), RestGatewayConfigBean.class); configBean.setPassword(encrypter.decrypt(configBean.getPassword(), new DataEncryptionContext())); bean.setConfiguration(mapper.writeValueAsString(configBean)); } } catch (Exception e) { throw new RuntimeException(e); } } /** * @return the storage */ public IStorage getStorage() { return storage; } /** * @param storage the storage to set */ public void setStorage(IStorage storage) { this.storage = storage; } /** * @return the securityContext */ public ISecurityContext getSecurityContext() { return securityContext; } /** * @param securityContext the securityContext to set */ public void setSecurityContext(ISecurityContext securityContext) { this.securityContext = securityContext; } }
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/GatewayResourceImpl.java
/* * Copyright 2014 JBoss 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 io.apiman.manager.api.rest.impl; import com.fasterxml.jackson.databind.ObjectMapper; import io.apiman.common.util.crypt.DataEncryptionContext; import io.apiman.common.util.crypt.IDataEncrypter; import io.apiman.gateway.engine.beans.SystemStatus; import io.apiman.manager.api.beans.BeanUtils; import io.apiman.manager.api.beans.gateways.GatewayBean; import io.apiman.manager.api.beans.gateways.GatewayType; import io.apiman.manager.api.beans.gateways.NewGatewayBean; import io.apiman.manager.api.beans.gateways.RestGatewayConfigBean; import io.apiman.manager.api.beans.gateways.UpdateGatewayBean; import io.apiman.manager.api.beans.summary.GatewaySummaryBean; import io.apiman.manager.api.beans.summary.GatewayTestResultBean; import io.apiman.manager.api.core.IStorage; import io.apiman.manager.api.core.IStorageQuery; import io.apiman.manager.api.core.exceptions.StorageException; import io.apiman.manager.api.core.logging.ApimanLogger; import io.apiman.common.logging.IApimanLogger; import io.apiman.manager.api.gateway.GatewayAuthenticationException; import io.apiman.manager.api.gateway.IGatewayLink; import io.apiman.manager.api.gateway.IGatewayLinkFactory; import io.apiman.manager.api.rest.contract.IGatewayResource; import io.apiman.manager.api.rest.contract.exceptions.AbstractRestException; import io.apiman.manager.api.rest.contract.exceptions.GatewayAlreadyExistsException; import io.apiman.manager.api.rest.contract.exceptions.GatewayNotFoundException; import io.apiman.manager.api.rest.contract.exceptions.NotAuthorizedException; import io.apiman.manager.api.rest.contract.exceptions.SystemErrorException; import io.apiman.manager.api.rest.impl.i18n.Messages; import io.apiman.manager.api.rest.impl.util.ExceptionFactory; import io.apiman.manager.api.security.ISecurityContext; import java.util.Date; import java.util.List; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; /** * Implementation of the Gateway API. * * @author [email protected] */ @ApplicationScoped public class GatewayResourceImpl implements IGatewayResource { @Inject IStorage storage; @Inject IStorageQuery query; @Inject ISecurityContext securityContext; @Inject IGatewayLinkFactory gatewayLinkFactory; @Inject @ApimanLogger(GatewayResourceImpl.class) IApimanLogger log; @Inject IDataEncrypter encrypter; private static final ObjectMapper mapper = new ObjectMapper(); /** * Constructor. */ public GatewayResourceImpl() { } /** * @see io.apiman.manager.api.rest.contract.IGatewayResource#test(io.apiman.manager.api.beans.gateways.NewGatewayBean) */ @Override public GatewayTestResultBean test(NewGatewayBean bean) throws NotAuthorizedException { if (!securityContext.isAdmin()) throw ExceptionFactory.notAuthorizedException(); GatewayTestResultBean rval = new GatewayTestResultBean(); try { GatewayBean testGateway = new GatewayBean(); testGateway.setName(bean.getName()); testGateway.setType(bean.getType()); testGateway.setConfiguration(bean.getConfiguration()); IGatewayLink gatewayLink = gatewayLinkFactory.create(testGateway); SystemStatus status = gatewayLink.getStatus(); String detail = mapper.writer().writeValueAsString(status); rval.setSuccess(true); rval.setDetail(detail); } catch (GatewayAuthenticationException e) { rval.setSuccess(false); rval.setDetail(Messages.i18n.format("GatewayResourceImpl.AuthenticationFailed")); //$NON-NLS-1$ } catch (Exception e) { rval.setSuccess(false); rval.setDetail(e.getMessage()); } return rval; } /** * @see io.apiman.manager.api.rest.contract.IGatewayResource#list() */ @Override public List<GatewaySummaryBean> list() throws NotAuthorizedException { try { return query.listGateways(); } catch (StorageException e) { throw new SystemErrorException(e); } } /** * @see io.apiman.manager.api.rest.contract.IGatewayResource#create(io.apiman.manager.api.beans.gateways.NewGatewayBean) */ @Override public GatewayBean create(NewGatewayBean bean) throws GatewayAlreadyExistsException { if (!securityContext.isAdmin()) throw ExceptionFactory.notAuthorizedException(); Date now = new Date(); GatewayBean gateway = new GatewayBean(); gateway.setId(BeanUtils.idFromName(bean.getName())); gateway.setName(bean.getName()); gateway.setDescription(bean.getDescription()); gateway.setType(bean.getType()); gateway.setConfiguration(bean.getConfiguration()); gateway.setCreatedBy(securityContext.getCurrentUser()); gateway.setCreatedOn(now); gateway.setModifiedBy(securityContext.getCurrentUser()); gateway.setModifiedOn(now); try { storage.beginTx(); if (storage.getGateway(gateway.getId()) != null) { throw ExceptionFactory.gatewayAlreadyExistsException(gateway.getName()); } // Store/persist the new gateway encryptPasswords(gateway); storage.createGateway(gateway); storage.commitTx(); } catch (AbstractRestException e) { storage.rollbackTx(); throw e; } catch (Exception e) { storage.rollbackTx(); throw new SystemErrorException(e); } decryptPasswords(gateway); log.debug(String.format("Successfully created new gateway %s: %s", gateway.getName(), gateway)); //$NON-NLS-1$ return gateway; } /** * @see io.apiman.manager.api.rest.contract.IGatewayResource#get(java.lang.String) */ @Override public GatewayBean get(String gatewayId) throws GatewayNotFoundException, NotAuthorizedException { try { storage.beginTx(); GatewayBean bean = storage.getGateway(gatewayId); if (bean == null) { throw ExceptionFactory.gatewayNotFoundException(gatewayId); } if (!securityContext.isAdmin()) { bean.setConfiguration(null); } else { decryptPasswords(bean); } storage.commitTx(); log.debug(String.format("Successfully fetched gateway %s: %s", bean.getName(), bean)); //$NON-NLS-1$ return bean; } catch (Exception e) { attemptRollback(e); return null; } } /** * @see io.apiman.manager.api.rest.contract.IGatewayResource#update(java.lang.String, io.apiman.manager.api.beans.gateways.UpdateGatewayBean) */ @Override public void update(String gatewayId, UpdateGatewayBean bean) throws GatewayNotFoundException, NotAuthorizedException { if (!securityContext.isAdmin()) throw ExceptionFactory.notAuthorizedException(); try { storage.beginTx(); Date now = new Date(); GatewayBean gbean = storage.getGateway(gatewayId); if (gbean == null) { throw ExceptionFactory.gatewayNotFoundException(gatewayId); } gbean.setModifiedBy(securityContext.getCurrentUser()); gbean.setModifiedOn(now); if (bean.getDescription() != null) gbean.setDescription(bean.getDescription()); if (bean.getType() != null) gbean.setType(bean.getType()); if (bean.getConfiguration() != null) gbean.setConfiguration(bean.getConfiguration()); encryptPasswords(gbean); storage.updateGateway(gbean); storage.commitTx(); log.debug(String.format("Successfully updated gateway %s: %s", gbean.getName(), gbean)); //$NON-NLS-1$ } catch (Exception e) { attemptRollback(e); } } /** * @see io.apiman.manager.api.rest.contract.IGatewayResource#delete(java.lang.String) */ @Override public void delete(String gatewayId) throws GatewayNotFoundException, NotAuthorizedException { if (!securityContext.isAdmin()) throw ExceptionFactory.notAuthorizedException(); try { storage.beginTx(); GatewayBean gbean = storage.getGateway(gatewayId); if (gbean == null) { throw ExceptionFactory.gatewayNotFoundException(gatewayId); } storage.deleteGateway(gbean); storage.commitTx(); log.debug(String.format("Successfully deleted gateway %s: %s", gbean.getName(), gbean)); //$NON-NLS-1$ } catch (Exception e) { attemptRollback(e); } } /** * Attempt to rollback the transaction. If the rollback itself fails, add the rollback failure * as a suppressed {@link Exception}. * @param cause the original cause */ private void attemptRollback(Exception cause) throws SystemErrorException { final SystemErrorException exToThrow = new SystemErrorException(cause); try { storage.rollbackTx(); } catch (Exception rollbackEx) { // rollback failed; wrap the reason and add the cause as a suppressed exception exToThrow.addSuppressed(rollbackEx); } throw exToThrow; } /** * @param bean */ private void encryptPasswords(GatewayBean bean) { if (bean.getConfiguration() == null) { return; } try { if (bean.getType() == GatewayType.REST) { RestGatewayConfigBean configBean = mapper.readValue(bean.getConfiguration(), RestGatewayConfigBean.class); configBean.setPassword(encrypter.encrypt(configBean.getPassword(), new DataEncryptionContext())); bean.setConfiguration(mapper.writeValueAsString(configBean)); } } catch (Exception e) { throw new RuntimeException(e); } } /** * @param bean */ private void decryptPasswords(GatewayBean bean) { if (bean.getConfiguration() == null) { return; } try { if (bean.getType() == GatewayType.REST) { RestGatewayConfigBean configBean = mapper.readValue(bean.getConfiguration(), RestGatewayConfigBean.class); configBean.setPassword(encrypter.decrypt(configBean.getPassword(), new DataEncryptionContext())); bean.setConfiguration(mapper.writeValueAsString(configBean)); } } catch (Exception e) { throw new RuntimeException(e); } } /** * @return the storage */ public IStorage getStorage() { return storage; } /** * @param storage the storage to set */ public void setStorage(IStorage storage) { this.storage = storage; } /** * @return the securityContext */ public ISecurityContext getSecurityContext() { return securityContext; } /** * @param securityContext the securityContext to set */ public void setSecurityContext(ISecurityContext securityContext) { this.securityContext = securityContext; } }
Revert "Prevents the root cause for storage exceptions being swallowed by a failure to roll back the transaction." This reverts commit d9f95c2990f01197152c5d5f3ed855aca1ea5bc9. Caused certain HTTP error codes not to be displayed properly. Signed-off-by: Marc Savy <[email protected]>
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/GatewayResourceImpl.java
Revert "Prevents the root cause for storage exceptions being swallowed by a failure to roll back the transaction."
<ide><path>anager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/GatewayResourceImpl.java <ide> <ide> log.debug(String.format("Successfully fetched gateway %s: %s", bean.getName(), bean)); //$NON-NLS-1$ <ide> return bean; <del> } catch (Exception e) { <del> attemptRollback(e); <del> return null; <add> } catch (AbstractRestException e) { <add> storage.rollbackTx(); <add> throw e; <add> } catch (Exception e) { <add> storage.rollbackTx(); <add> throw new SystemErrorException(e); <ide> } <ide> } <ide> <ide> storage.commitTx(); <ide> <ide> log.debug(String.format("Successfully updated gateway %s: %s", gbean.getName(), gbean)); //$NON-NLS-1$ <del> } catch (Exception e) { <del> attemptRollback(e); <add> } catch (AbstractRestException e) { <add> storage.rollbackTx(); <add> throw e; <add> } catch (Exception e) { <add> storage.rollbackTx(); <add> throw new SystemErrorException(e); <ide> } <ide> } <ide> <ide> storage.commitTx(); <ide> <ide> log.debug(String.format("Successfully deleted gateway %s: %s", gbean.getName(), gbean)); //$NON-NLS-1$ <del> } catch (Exception e) { <del> attemptRollback(e); <del> } <del> } <del> <del> /** <del> * Attempt to rollback the transaction. If the rollback itself fails, add the rollback failure <del> * as a suppressed {@link Exception}. <del> * @param cause the original cause <del> */ <del> private void attemptRollback(Exception cause) throws SystemErrorException { <del> final SystemErrorException exToThrow = new SystemErrorException(cause); <del> try { <del> storage.rollbackTx(); <del> } catch (Exception rollbackEx) { <del> // rollback failed; wrap the reason and add the cause as a suppressed exception <del> exToThrow.addSuppressed(rollbackEx); <del> } <del> throw exToThrow; <add> } catch (AbstractRestException e) { <add> storage.rollbackTx(); <add> throw e; <add> } catch (Exception e) { <add> storage.rollbackTx(); <add> throw new SystemErrorException(e); <add> } <ide> } <ide> <ide> /**
Java
apache-2.0
7692e5713f765a79e917c6066657dec7fc5ca4ad
0
MatthewTamlin/Spyglass
package com.matthewtamlin.spyglass.library.use_annotations; import com.matthewtamlin.spyglass.library.meta_annotations.Use; import com.matthewtamlin.spyglass.library.use_adapters.UseIntAdapter; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Use(adapterClass = UseIntAdapter.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface UseInt { int value(); }
library/src/main/java/com/matthewtamlin/spyglass/library/use_annotations/UseInt.java
package com.matthewtamlin.spyglass.library.use_annotations; import com.matthewtamlin.spyglass.library.meta_annotations.Use; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Use(adapterClass = UseInt.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface UseInt { int value(); }
Changed adapter class declaration
library/src/main/java/com/matthewtamlin/spyglass/library/use_annotations/UseInt.java
Changed adapter class declaration
<ide><path>ibrary/src/main/java/com/matthewtamlin/spyglass/library/use_annotations/UseInt.java <ide> package com.matthewtamlin.spyglass.library.use_annotations; <ide> <ide> import com.matthewtamlin.spyglass.library.meta_annotations.Use; <add>import com.matthewtamlin.spyglass.library.use_adapters.UseIntAdapter; <ide> <ide> import java.lang.annotation.ElementType; <ide> import java.lang.annotation.Retention; <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <ide> <del>@Use(adapterClass = UseInt.class) <add>@Use(adapterClass = UseIntAdapter.class) <ide> @Retention(RetentionPolicy.RUNTIME) <ide> @Target(ElementType.PARAMETER) <ide> public @interface UseInt {
Java
mpl-2.0
581a3f3ff4cf24ba608a8739fc6ee6a9f1b95fe5
0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: FieldDescription.java,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2005-12-28 17:23:05 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ package com.sun.star.wizards.table; import java.util.Hashtable; import java.util.Vector; import com.sun.star.beans.PropertyValue; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.beans.XPropertySet; import com.sun.star.container.XNameAccess; import com.sun.star.lang.Locale; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.uno.UnoRuntime; import com.sun.star.wizards.common.ConfigGroup; import com.sun.star.wizards.common.Configuration; import com.sun.star.wizards.common.Desktop; import com.sun.star.wizards.common.Properties; public class FieldDescription{ int category; private String tablename = ""; // String fieldname; private String keyname; private XNameAccess xNameAccessTableNode; private XPropertySet xPropertySet; private Vector aPropertyValues; // PropertyValue[] aPropertyValues; private Integer Type; private Integer Scale; private Integer Precision; private Boolean DefaultValue; private String Name; private XMultiServiceFactory xMSF; private Locale aLocale; public FieldDescription(XMultiServiceFactory _xMSF, Locale _aLocale, ScenarioSelector _curscenarioselector, String _fieldname, String _keyname, int _nmaxcharCount){ xMSF = _xMSF; aLocale = _aLocale; category = _curscenarioselector.getCategory(); tablename = _curscenarioselector.getTableName(); Name = _fieldname; keyname = _keyname; aPropertyValues = new Vector(); xNameAccessTableNode = _curscenarioselector.oCGTable.xNameAccessFieldsNode; XNameAccess xNameAccessFieldNode; if (_curscenarioselector.bcolumnnameislimited) xNameAccessFieldNode = Configuration.getChildNodebyDisplayName(xMSF, aLocale, xNameAccessTableNode,keyname, "ShortName", _nmaxcharCount); else xNameAccessFieldNode = Configuration.getChildNodebyDisplayName(xMSF, aLocale, xNameAccessTableNode,keyname, "Name", _nmaxcharCount); setFieldProperties(xNameAccessFieldNode); } public FieldDescription(String _fieldname){ Name = _fieldname; aPropertyValues = new Vector(); Type = new Integer(com.sun.star.sdbc.DataType.VARCHAR); aPropertyValues.addElement(Properties.createProperty("Name", _fieldname) ); aPropertyValues.addElement(Properties.createProperty("Type", Type) ); } public void setName(String _newfieldname){ for (int i = 0; i < aPropertyValues.size(); i++){ PropertyValue aPropertyValue = (PropertyValue) aPropertyValues.get(i); if (aPropertyValue.Name.equals("Name")){ aPropertyValue.Value = _newfieldname; aPropertyValues.set(i, aPropertyValue); Name = _newfieldname; return; } } } public String getName(){ return Name; } public String gettablename(){ return tablename; } private boolean propertyexists(String _propertyname){ boolean bexists = false; try { if (xPropertySet.getPropertySetInfo().hasPropertyByName(_propertyname)){ Object oValue = xPropertySet.getPropertyValue(_propertyname); bexists = (!com.sun.star.uno.AnyConverter.isVoid(oValue)); } } catch (Exception e) { e.printStackTrace(System.out); } return bexists; } public void setFieldProperties(XNameAccess _xNameAccessFieldNode){ try { xPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, _xNameAccessFieldNode); // Integer Index = (Integer) xPropertySet.getPropertyValue("Index"); if (propertyexists("Name")) aPropertyValues.addElement(Properties.createProperty("Name", Name)); if (propertyexists("Type")) aPropertyValues.addElement(Properties.createProperty("Type", (Integer) xPropertySet.getPropertyValue("Type"))); if (propertyexists("Scale")) aPropertyValues.addElement(Properties.createProperty("Scale", (Integer) xPropertySet.getPropertyValue("Scale"))); // Scale = if (propertyexists("Precision")) aPropertyValues.addElement(Properties.createProperty("Precision", (Integer) xPropertySet.getPropertyValue("Precision"))); // Precision = (Integer) xPropertySet.getPropertyValue("Precision"); if (propertyexists("DefaultValue")) aPropertyValues.addElement(Properties.createProperty("DefaultValue",(Boolean) xPropertySet.getPropertyValue("DefaultValue"))); // DefaultValue = (Boolean) xPropertySet.getPropertyValue("DefaultValue"); //Type = new Integer(4); // TODO wo ist der Fehler?(Integer) xPropertySet.getPropertyValue("Type"); } catch (Exception e) { e.printStackTrace(System.out); }} public PropertyValue[] getPropertyValues(){ if (aPropertyValues != null){ PropertyValue[] aProperties = new PropertyValue[aPropertyValues.size()]; aPropertyValues.toArray(aProperties); return aProperties; } return null; } }
wizards/com/sun/star/wizards/table/FieldDescription.java
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: FieldDescription.java,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 09:40:00 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ package com.sun.star.wizards.table; import java.util.Hashtable; import java.util.Vector; import com.sun.star.beans.PropertyValue; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.beans.XPropertySet; import com.sun.star.container.XNameAccess; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.uno.UnoRuntime; import com.sun.star.wizards.common.ConfigGroup; import com.sun.star.wizards.common.Configuration; import com.sun.star.wizards.common.Properties; public class FieldDescription{ int category; private String tablename = ""; // String fieldname; private String keyname; private XNameAccess xNameAccessTableNode; private XPropertySet xPropertySet; private Vector aPropertyValues; // PropertyValue[] aPropertyValues; private Integer Type; private Integer Scale; private Integer Precision; private Boolean DefaultValue; private String Name; public FieldDescription(ScenarioSelector _curscenarioselector, String _fieldname, String _keyname){ category = _curscenarioselector.getCategory(); tablename = _curscenarioselector.getTableName(); Name = _fieldname; keyname = _keyname; aPropertyValues = new Vector(); xNameAccessTableNode = _curscenarioselector.oCGTable.xNameAccessFieldsNode; XNameAccess xNameAccessFieldNode; if (_curscenarioselector.bcolumnnameislimited) xNameAccessFieldNode = Configuration.getChildNodebyDisplayName(xNameAccessTableNode, keyname, "ShortName"); else xNameAccessFieldNode = Configuration.getChildNodebyDisplayName(xNameAccessTableNode,keyname, "Name"); setFieldProperties(xNameAccessFieldNode); } public FieldDescription(String _fieldname){ Name = _fieldname; aPropertyValues = new Vector(); Type = new Integer(com.sun.star.sdbc.DataType.VARCHAR); aPropertyValues.addElement(Properties.createProperty("Name", _fieldname) ); aPropertyValues.addElement(Properties.createProperty("Type", Type) ); } public void setName(String _newfieldname){ for (int i = 0; i < aPropertyValues.size(); i++){ PropertyValue aPropertyValue = (PropertyValue) aPropertyValues.get(i); if (aPropertyValue.Name.equals("Name")){ aPropertyValue.Value = _newfieldname; aPropertyValues.set(i, aPropertyValue); Name = _newfieldname; return; } } } public String getName(){ return Name; } public String gettablename(){ return tablename; } private boolean propertyexists(String _propertyname){ boolean bexists = false; try { if (xPropertySet.getPropertySetInfo().hasPropertyByName(_propertyname)){ Object oValue = xPropertySet.getPropertyValue(_propertyname); bexists = (!com.sun.star.uno.AnyConverter.isVoid(oValue)); } } catch (Exception e) { e.printStackTrace(System.out); } return bexists; } public void setFieldProperties(XNameAccess _xNameAccessFieldNode){ try { xPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, _xNameAccessFieldNode); // Integer Index = (Integer) xPropertySet.getPropertyValue("Index"); if (propertyexists("Name")) aPropertyValues.addElement(Properties.createProperty("Name", Name)); if (propertyexists("Type")) aPropertyValues.addElement(Properties.createProperty("Type", (Integer) xPropertySet.getPropertyValue("Type"))); if (propertyexists("Scale")) aPropertyValues.addElement(Properties.createProperty("Scale", (Integer) xPropertySet.getPropertyValue("Scale"))); // Scale = if (propertyexists("Precision")) aPropertyValues.addElement(Properties.createProperty("Precision", (Integer) xPropertySet.getPropertyValue("Precision"))); // Precision = (Integer) xPropertySet.getPropertyValue("Precision"); if (propertyexists("DefaultValue")) aPropertyValues.addElement(Properties.createProperty("DefaultValue",(Boolean) xPropertySet.getPropertyValue("DefaultValue"))); // DefaultValue = (Boolean) xPropertySet.getPropertyValue("DefaultValue"); //Type = new Integer(4); // TODO wo ist der Fehler?(Integer) xPropertySet.getPropertyValue("Type"); } catch (Exception e) { e.printStackTrace(System.out); }} public PropertyValue[] getPropertyValues(){ if (aPropertyValues != null){ PropertyValue[] aProperties = new PropertyValue[aPropertyValues.size()]; aPropertyValues.toArray(aProperties); return aProperties; } return null; } }
INTEGRATION: CWS dbwizardpp1 (1.3.44); FILE MERGED 2005/12/15 14:33:52 bc 1.3.44.3: #i49327# Shortname now alwas contatenated 2005/12/06 01:06:29 bc 1.3.44.2: RESYNC: (1.3-1.4); FILE MERGED 2005/08/26 16:11:08 bc 1.3.44.1: #i49327#handling of special characters in fieldnames modified
wizards/com/sun/star/wizards/table/FieldDescription.java
INTEGRATION: CWS dbwizardpp1 (1.3.44); FILE MERGED 2005/12/15 14:33:52 bc 1.3.44.3: #i49327# Shortname now alwas contatenated 2005/12/06 01:06:29 bc 1.3.44.2: RESYNC: (1.3-1.4); FILE MERGED 2005/08/26 16:11:08 bc 1.3.44.1: #i49327#handling of special characters in fieldnames modified
<ide><path>izards/com/sun/star/wizards/table/FieldDescription.java <ide> * <ide> * $RCSfile: FieldDescription.java,v $ <ide> * <del> * $Revision: 1.4 $ <add> * $Revision: 1.5 $ <ide> * <del> * last change: $Author: rt $ $Date: 2005-09-09 09:40:00 $ <add> * last change: $Author: hr $ $Date: 2005-12-28 17:23:05 $ <ide> * <ide> * The Contents of this file are made available subject to <ide> * the terms of GNU Lesser General Public License Version 2.1. <ide> import com.sun.star.beans.UnknownPropertyException; <ide> import com.sun.star.beans.XPropertySet; <ide> import com.sun.star.container.XNameAccess; <add>import com.sun.star.lang.Locale; <ide> import com.sun.star.lang.WrappedTargetException; <ide> import com.sun.star.lang.XMultiServiceFactory; <ide> import com.sun.star.uno.UnoRuntime; <ide> import com.sun.star.wizards.common.ConfigGroup; <ide> import com.sun.star.wizards.common.Configuration; <add>import com.sun.star.wizards.common.Desktop; <ide> import com.sun.star.wizards.common.Properties; <ide> <ide> <ide> private Integer Precision; <ide> private Boolean DefaultValue; <ide> private String Name; <add> private XMultiServiceFactory xMSF; <add> private Locale aLocale; <ide> <del> public FieldDescription(ScenarioSelector _curscenarioselector, String _fieldname, String _keyname){ <add> public FieldDescription(XMultiServiceFactory _xMSF, Locale _aLocale, ScenarioSelector _curscenarioselector, String _fieldname, String _keyname, int _nmaxcharCount){ <add> xMSF = _xMSF; <add> aLocale = _aLocale; <ide> category = _curscenarioselector.getCategory(); <ide> tablename = _curscenarioselector.getTableName(); <ide> Name = _fieldname; <ide> xNameAccessTableNode = _curscenarioselector.oCGTable.xNameAccessFieldsNode; <ide> XNameAccess xNameAccessFieldNode; <ide> if (_curscenarioselector.bcolumnnameislimited) <del> xNameAccessFieldNode = Configuration.getChildNodebyDisplayName(xNameAccessTableNode, keyname, "ShortName"); <add> xNameAccessFieldNode = Configuration.getChildNodebyDisplayName(xMSF, aLocale, xNameAccessTableNode,keyname, "ShortName", _nmaxcharCount); <ide> else <del> xNameAccessFieldNode = Configuration.getChildNodebyDisplayName(xNameAccessTableNode,keyname, "Name"); <add> xNameAccessFieldNode = Configuration.getChildNodebyDisplayName(xMSF, aLocale, xNameAccessTableNode,keyname, "Name", _nmaxcharCount); <ide> setFieldProperties(xNameAccessFieldNode); <ide> } <ide>
Java
apache-2.0
72529bf13cddfc3d220d85fd7b229be682c24391
0
Reissner/maven-latex-plugin,Reissner/maven-latex-plugin,Reissner/maven-latex-plugin,Reissner/maven-latex-plugin,Reissner/maven-latex-plugin
package eu.simuline.m2latex.core; import java.util.HashMap; import java.util.Map; enum Converter { PdfLatex { String getCommand() { return "pdflatex"; } /** * The version pattern at a first sight consists of three parts: * <ul> * <li>the tex version which is an approximation of pi * and which will be frozen as Donald Knuth will die at $\pi$ * (meant maybe in double precision)</li> * <li>the etex version which is a two integer version. * It has to be clarified, whether there is a new release to be expected. </li> * <li>the pdftex version. </li> * </ul> * It is quite sure from the examples found, * that the latter does not start from the beginning * when the former is increased. * This means that the first of the two version numbers are informative only * and must thus be included in the environment. * @see #getVersionEnvironment() */ String getVersionPattern() { // 3.1415926-2.3-1.40.12 // 3.14159265-2.6-1.40.21 return X_X_X; } /** * For an explanation why part of the version string is in the environment, * see {@link #getVersionPattern()}. */ String getVersionEnvironment() { return "^pdfTeX 3\\.[0-9]*-[0-9]+\\.[0-9]+-%s \\(TeX Live"; } }, LuaLatex { String getCommand() { return "lualatex"; } String getVersionPattern() { return X_X_X; } String getVersionEnvironment() { return "^This is LuaHBTeX, Version %s \\(TeX Live"; } }, XeLatex { String getCommand() { return "xelatex"; } /** * The version pattern at a first sight consists of three parts: * <ul> * <li>the tex version which is an approximation of pi * and which will be frozen as Donald Knuth will die at $\pi$ * (meant maybe in double precision)</li> * <li>the etex version which is a two integer version. * It has to be clarified, whether there is a new release to be expected. </li> * <li>the xetex version. </li> * </ul> * It is quite sure from the examples found, * that the latter does not start from the beginning * when the former is increased. * This means that the first of the two version numbers are informative only * and must thus be included in the environment. * @see #getVersionEnvironment() */ String getVersionPattern() { return "((0\\.[0-9]*))"; } /** * For an explanation why part of the version string is in the environment, * see {@link #getVersionPattern()}. */ String getVersionEnvironment() { return "^XeTeX 3\\.[0-9]*-[0-9]+\\.[0-9]+-%s \\(TeX Live"; } }, Latex2rtf { String getCommand() { return "latex2rtf"; } String getVersionPattern() { return "(([0-9]+)\\.([0-9]+)\\.([0-9]+) r([0-9]+))"; } String getVersionEnvironment() { return "^latex2rtf %s \\(released"; } }, Odt2doc { String getCommand() { return "odt2doc"; } String getVersionOption() { return "--version"; } // TBC: not clear whether this is the significant version String getVersionPattern() { return X_X_X; } String getVersionEnvironment() { return "^unoconv %s\n"; } }, Pdf2txt { String getCommand() { return "pdftotext"; } String getVersionPattern() { return X_X_X; } String getVersionEnvironment() { return "^pdftotext version %s\n"; } }, Dvips { String getCommand() { return "dvips"; } String getVersionPattern() { return "(([0-9\\.]{4})\\.([0-9]))"; } String getVersionEnvironment() { return "^This is dvips\\(k\\) %s " + "Copyright [0-9]+ Radical Eye Software \\(www\\.radicaleye\\.com\\)\n"; } }, Dvipdfm { String getCommand() { return "dvipdfm"; } String getVersionOption() { return "--version"; } String getVersionPattern() { return YYYYMMDD; } String getVersionEnvironment() { return "^This is xdvipdfmx Version %s " + "by the DVIPDFMx project team,\n"; } }, Dvipdfmx { String getCommand() { return "dvipdfmx"; } String getVersionOption() { return "--version"; } String getVersionPattern() { return YYYYMMDD; } String getVersionEnvironment() { return "^This is dvipdfmx Version %s " + "by the DVIPDFMx project team,\n"; } }, XDvipdfmx { String getCommand() { return "xdvipdfmx"; } String getVersionOption() { return "--version"; } String getVersionPattern() { return YYYYMMDD; } String getVersionEnvironment() { return "^This is xdvipdfmx Version %s " + "by the DVIPDFMx project team,\n"; } }, Dvipdft { String getCommand() { return "dvipdft"; } String getVersionOption() { return "--version"; } String getVersionPattern() { return "(([0-9]{4})([0-9]{2})([0-9]{2})\\.([0-9]{4}))"; } String getVersionEnvironment() { return "^dvipdft version %s by Thomas Esser and others\n"; } }, GS { String getCommand() { return "gs"; } String getVersionPattern() { return "(([0-9]+)\\.([0-9]+)(?:\\.([0-9]+))?)"; } String getVersionEnvironment() { return "^GPL Ghostscript %s \\([0-9]{4}-[0-9]{2}-[0-9]{2}\\)\n"; } }, Chktex { String getCommand() { return "chktex"; } String getVersionOption() { return "-W"; } String getVersionPattern() { return X_X_X; } String getVersionEnvironment() { return "^ChkTeX v%s - " + "Copyright [0-9]{4}-[0-9]{2} Jens T. Berger Thielemann.\n"; } }, Bibtex { String getCommand() { return "bibtex"; } String getVersionPattern() { return "((0\\.[0-9]*)([a-z]))"; } String getVersionEnvironment() { return "^BibTeX %s \\(TeX Live "; } }, Bibtexu { String getCommand() { return "bibtexu"; } /** * Returns the pattern for the version string. * Note that <code>bibtexu -v</code> yields three versions, * the version of bibtex (something like 0.99d) * which is something like the specification version, * the ICU version and the release version (and date). * What is returned is the latter version. * * @return * the pattern for the version string. */ String getVersionPattern() { return X_X; } String getVersionEnvironment() { return "^[^\n]*\n[^\n]*\n" + "Release version: %s \\([0-9]{2} [a-z]{3} [0-9]{4}\\)\n"; } }, Bibtex8 { String getCommand() { return "bibtex8"; } /** * Returns the pattern for the version string. * Note that <code>bibtex8 -v</code> yields three versions, * the version of bibtex (something like 0.99d) * which is something like the specification version, * the ICU version and the release version (and date). * What is returned is the latter version. * * @return * the pattern for the version string. */ String getVersionPattern() { return X_X; } String getVersionEnvironment() { return "^[^\n]*\n[^\n]*\n" + "Release version: %s \\([0-9]{2} [a-z]{3} [0-9]{4}\\)\n"; } }, // Makeindex { // String getCommand() { // return "makeindex"; // } // String getVersionOption() { // return "-q"; // } // String getVersionPattern() { // return "^(.*)\n"; // } // }, // TBC: maybe this replaces makeindex Upmendex { String getCommand() { return "upmendex"; } String getVersionOption() { return "-h"; } String getVersionPattern() { return X_X; } String getVersionEnvironment() { return "^upmendex - index processor, version %s " + "\\(TeX Live [0-9]{4}\\).\n"; } }, Splitindex { String getCommand() { return "splitindex"; } String getVersionOption() { return "--version"; } String getVersionPattern() { return X_X; } String getVersionEnvironment() { return "^splitindex.pl %s\n"; } }, // TBC: which of the versions is the relevant one? Xindy { String getCommand() { return "xindy"; } String getVersionOption() { return "-V"; } // TBC: not clear whether this is the significant version String getVersionPattern() { return X_X_X; } String getVersionEnvironment() { return "^xindy release: %s\n"; } }, Makeglossaries { String getCommand() { return "makeglossaries"; } String getVersionOption() { return "--help"; } String getVersionPattern() { return X_X; } String getVersionEnvironment() { return "^Makeglossaries Version %s " + "\\([0-9]{4}-[0-9]{2}-[0-9]{2}\\)\n"; } }, Mpost { String getCommand() { return "mpost"; } String getVersionPattern() { return X_X; } String getVersionEnvironment() { return "^MetaPost %s \\(TeX Live "; } }, Ebb { String getCommand() { return "ebb"; } String getVersionOption() { return "--version"; } // 2nd line String getVersionPattern() { return YYYYMMDD; } String getVersionEnvironment() { return "^[^\n]*\nThis is ebb Version %s\n"; } }, Gnuplot { String getCommand() { return "gnuplot"; } String getVersionOption() { return "-V"; } // TBC: we allow here patchlevel 0 only. Is this appropriate? String getVersionPattern() { return X_X; } String getVersionEnvironment() { return "^gnuplot %s patchlevel 0\n"; } }, Inkscape { String getCommand() { return "inkscape"; } String getVersionOption() { return "-V"; } String getVersionPattern() { return X_X_X; } // TBD: sometimes the pango line ' Pango version: 1.46.2' comes first. String getVersionEnvironment() { return "^Inkscape %s \\([0-9a-f]+, [0-9]{4}-[0-9]{2}-[0-9]{2}\\)\n"; } }, Fig2Dev { String getCommand() { return "fig2dev"; } String getVersionOption() { return "-V"; } String getVersionPattern() { return "(([0-9]+)\\.([0-9]+)\\.([0-9]+)([a-z]))"; } String getVersionEnvironment() { return "^fig2dev Version %s\n"; } }; private final static String X_X_X = "(([0-9]+)\\.([0-9]+)\\.([0-9]+))"; private final static String X_X = "(([0-9]+)\\.([0-9]+))"; private final static String YYYYMMDD = "(([0-9]{4})([0-9]{2})([0-9]{2}))"; // TBC: needed? final static Map<String, Converter> cmd2conv; static { cmd2conv = new HashMap<String, Converter>(); for (Converter conv : Converter.values()) { cmd2conv.put(conv.getCommand(), conv); } } /** * Returns the command which which to invoke this converter. * * @return * the command of this converter. */ abstract String getCommand(); /** * Returns the option which just displays information * given by {@link #getVersionEnvironment()} and among that version information * as descried by {@link #getVersionPattern()}. * * @return * the option to display (a string containing) version information. * As a default, this is <code>-v</code> which is the most common such option. */ String getVersionOption() { return "-v"; } /** * Returns the pattern of the version for this converter as a regular expression. * All is enclosed by brackets indicating a capturing group. * Non capturing groups may occur without restriction * but capturing groups except the outermost one must come sequential. * This patters is part of the converters output * as indicated by {@link #getVersionEnvironment()}. * * @return * the pattern of the version for this converter. */ abstract String getVersionPattern(); /** * Returns the pattern of the output of this converter * if invoked with command {@link #getCommand()} and option {@link #getVersionOption()}. * Here, the literal <code>%s</code> indicates the location * of the proper version pattern given by {@link #getVersionPattern()}. * If this is included a regular expression emerges. * * @return * the pattern of the output of this converter containing its version. */ abstract String getVersionEnvironment(); }
maven-latex-plugin/src/main/java/eu/simuline/m2latex/core/Converter.java
package eu.simuline.m2latex.core; import java.util.HashMap; import java.util.Map; enum Converter { PdfLatex { String getCommand() { return "pdflatex"; } /** * The version pattern at a first sight consists of three parts: * <ul> * <li>the tex version which is an approximation of pi * and which will be frozen as Donald Knuth will die at $\pi$ * (meant maybe in double precision)</li> * <li>the etex version which is a two integer version. * It has to be clarified, whether there is a new release to be expected. </li> * <li>the pdftex version. </li> * </ul> * It is quite sure from the examples found, * that the latter does not start from the beginning * when the former is increased. * This means that the first of the two version numbers are informative only * and must thus be included in the environment. * @see #getVersionEnvironment() */ String getVersionPattern() { // 3.1415926-2.3-1.40.12 // 3.14159265-2.6-1.40.21 return X_X_X; } /** * For an explanation why part of the version string is in the environment, * see {@link #getVersionPattern()}. */ String getVersionEnvironment() { return "^pdfTeX 3\\.[0-9]*-[0-9]+\\.[0-9]+-%s \\(TeX Live"; } }, LuaLatex { String getCommand() { return "lualatex"; } String getVersionPattern() { return X_X_X; } String getVersionEnvironment() { return "^This is LuaHBTeX, Version %s \\(TeX Live"; } }, XeLatex { String getCommand() { return "xelatex"; } /** * The version pattern at a first sight consists of three parts: * <ul> * <li>the tex version which is an approximation of pi * and which will be frozen as Donald Knuth will die at $\pi$ * (meant maybe in double precision)</li> * <li>the etex version which is a two integer version. * It has to be clarified, whether there is a new release to be expected. </li> * <li>the xetex version. </li> * </ul> * It is quite sure from the examples found, * that the latter does not start from the beginning * when the former is increased. * This means that the first of the two version numbers are informative only * and must thus be included in the environment. * @see #getVersionEnvironment() */ String getVersionPattern() { return "((0\\.[0-9]*))"; } /** * For an explanation why part of the version string is in the environment, * see {@link #getVersionPattern()}. */ String getVersionEnvironment() { return "^XeTeX 3\\.[0-9]*-[0-9]+\\.[0-9]+-%s \\(TeX Live"; } }, Latex2rtf { String getCommand() { return "latex2rtf"; } String getVersionPattern() { return "(([0-9]+)\\.([0-9]+)\\.([0-9]+) r([0-9]+))"; } String getVersionEnvironment() { return "^latex2rtf %s \\(released"; } }, Odt2doc { String getCommand() { return "odt2doc"; } String getVersionOption() { return "--version"; } // TBC: not clear whether this is the significant version String getVersionPattern() { return X_X_X; } String getVersionEnvironment() { return "^unoconv %s\n"; } }, Pdf2txt { String getCommand() { return "pdftotext"; } String getVersionPattern() { return X_X_X; } String getVersionEnvironment() { return "^pdftotext version %s\n"; } }, Dvips { String getCommand() { return "dvips"; } String getVersionPattern() { return "(([0-9\\.]{4})\\.([0-9]))"; } String getVersionEnvironment() { return "^This is dvips\\(k\\) %s " + "Copyright [0-9]+ Radical Eye Software \\(www\\.radicaleye\\.com\\)\n"; } }, Dvipdfm { String getCommand() { return "dvipdfm"; } String getVersionOption() { return "--version"; } String getVersionPattern() { return YYYYMMDD; } String getVersionEnvironment() { return "^This is xdvipdfmx Version %s " + "by the DVIPDFMx project team,\n"; } }, Dvipdfmx { String getCommand() { return "dvipdfmx"; } String getVersionOption() { return "--version"; } String getVersionPattern() { return YYYYMMDD; } String getVersionEnvironment() { return "^This is dvipdfmx Version %s " + "by the DVIPDFMx project team,\n"; } }, XDvipdfmx { String getCommand() { return "xdvipdfmx"; } String getVersionOption() { return "--version"; } String getVersionPattern() { return YYYYMMDD; } String getVersionEnvironment() { return "^This is xdvipdfmx Version %s " + "by the DVIPDFMx project team,\n"; } }, Dvipdft { String getCommand() { return "dvipdft"; } String getVersionOption() { return "--version"; } String getVersionPattern() { return "(([0-9]{4})([0-9]{2})([0-9]{2})\\.([0-9]{4}))"; } String getVersionEnvironment() { return "^dvipdft version %s by Thomas Esser and others\n"; } }, GS { String getCommand() { return "gs"; } String getVersionPattern() { return "(([0-9]+)\\.([0-9]+)(?:\\.([0-9]+))?)"; } String getVersionEnvironment() { return "^GPL Ghostscript %s \\([0-9]{4}-[0-9]{2}-[0-9]{2}\\)\n"; } }, Chktex { String getCommand() { return "chktex"; } String getVersionOption() { return "-W"; } String getVersionPattern() { return X_X_X; } String getVersionEnvironment() { return "^ChkTeX v%s - " + "Copyright [0-9]{4}-[0-9]{2} Jens T. Berger Thielemann.\n"; } }, Bibtex { String getCommand() { return "bibtex"; } String getVersionPattern() { return "((0\\.[0-9]*)([a-z]))"; } String getVersionEnvironment() { return "^BibTeX %s \\(TeX Live "; } }, Bibtexu { String getCommand() { return "bibtexu"; } /** * Returns the pattern for the version string. * Note that <code>bibtexu -v</code> yields three versions, * the version of bibtex (something like 0.99d) * which is something like the specification version, * the ICU version and the release version (and date). * What is returned is the latter version. * * @return * the pattern for the version string. */ String getVersionPattern() { return X_X; } String getVersionEnvironment() { return "^[^\n]*\n[^\n]*\n" + "Release version: %s \\([0-9]{2} [a-z]{3} [0-9]{4}\\)\n"; } }, Bibtex8 { String getCommand() { return "bibtex8"; } /** * Returns the pattern for the version string. * Note that <code>bibtex8 -v</code> yields three versions, * the version of bibtex (something like 0.99d) * which is something like the specification version, * the ICU version and the release version (and date). * What is returned is the latter version. * * @return * the pattern for the version string. */ String getVersionPattern() { return X_X; } String getVersionEnvironment() { return "^[^\n]*\n[^\n]*\n" + "Release version: %s \\([0-9]{2} [a-z]{3} [0-9]{4}\\)\n"; } }, // Makeindex { // String getCommand() { // return "makeindex"; // } // String getVersionOption() { // return "-q"; // } // String getVersionPattern() { // return "^(.*)\n"; // } // }, // TBC: maybe this replaces makeindex Upmendex { String getCommand() { return "upmendex"; } String getVersionOption() { return "-h"; } String getVersionPattern() { return X_X; } String getVersionEnvironment() { return "^upmendex - index processor, version %s " + "\\(TeX Live [0-9]{4}\\).\n"; } }, Splitindex { String getCommand() { return "splitindex"; } String getVersionOption() { return "--version"; } String getVersionPattern() { return X_X; } String getVersionEnvironment() { return "^splitindex.pl %s\n"; } }, // TBC: which of the versions is the relevant one? Xindy { String getCommand() { return "xindy"; } String getVersionOption() { return "-V"; } // TBC: not clear whether this is the significant version String getVersionPattern() { return X_X_X; } String getVersionEnvironment() { return "^xindy release: %s\n"; } }, Makeglossaries { String getCommand() { return "makeglossaries"; } String getVersionOption() { return "--help"; } String getVersionPattern() { return X_X; } String getVersionEnvironment() { return "^Makeglossaries Version %s " + "\\([0-9]{4}-[0-9]{2}-[0-9]{2}\\)\n"; } }, Mpost { String getCommand() { return "mpost"; } String getVersionPattern() { return X_X; } String getVersionEnvironment() { return "^MetaPost %s \\(TeX Live "; } }, Ebb { String getCommand() { return "ebb"; } String getVersionOption() { return "--version"; } // 2nd line String getVersionPattern() { return YYYYMMDD; } String getVersionEnvironment() { return "^[^\n]*\nThis is ebb Version %s\n"; } }, Gnuplot { String getCommand() { return "gnuplot"; } String getVersionOption() { return "-V"; } // TBC: we allow here patchlevel 0 only. Is this appropriate? String getVersionPattern() { return X_X; } String getVersionEnvironment() { return "^gnuplot %s patchlevel 0\n"; } }, Inkscape { String getCommand() { return "inkscape"; } String getVersionOption() { return "-V"; } String getVersionPattern() { return X_X_X; } // TBD: sometimes the pango line ' Pango version: 1.46.2' comes first. String getVersionEnvironment() { return "^Inkscape %s \\([0-9a-f]+, [0-9]{4}-[0-9]{2}-[0-9]{2}\\)\n"; } }, Fig2Dev { String getCommand() { return "fig2dev"; } String getVersionOption() { return "-V"; } String getVersionPattern() { return "(([0-9]+)\\.([0-9]+)\\.([0-9]+)([a-z]))"; } String getVersionEnvironment() { return "^fig2dev Version %s\n"; } }; private final static String X_X_X = "(([0-9]+)\\.([0-9]+)\\.([0-9]+))"; private final static String X_X = "(([0-9]+)\\.([0-9]+))"; private final static String YYYYMMDD = "(([0-9]{4})([0-9]{2})([0-9]{2}))"; // TBC: needed? final static Map<String, Converter> cmd2conv; static { cmd2conv = new HashMap<String, Converter>(); for (Converter conv : Converter.values()) { cmd2conv.put(conv.getCommand(), conv); } } abstract String getCommand(); String getVersionOption() { return "-v"; } abstract String getVersionPattern(); abstract String getVersionEnvironment(); }
Update Converter.java: added api docs.
maven-latex-plugin/src/main/java/eu/simuline/m2latex/core/Converter.java
Update Converter.java: added api docs.
<ide><path>aven-latex-plugin/src/main/java/eu/simuline/m2latex/core/Converter.java <ide> cmd2conv.put(conv.getCommand(), conv); <ide> } <ide> } <del> <add> <add> /** <add> * Returns the command which which to invoke this converter. <add> * <add> * @return <add> * the command of this converter. <add> */ <ide> abstract String getCommand(); <del> <add> <add> /** <add> * Returns the option which just displays information <add> * given by {@link #getVersionEnvironment()} and among that version information <add> * as descried by {@link #getVersionPattern()}. <add> * <add> * @return <add> * the option to display (a string containing) version information. <add> * As a default, this is <code>-v</code> which is the most common such option. <add> */ <ide> String getVersionOption() { <ide> return "-v"; <ide> } <add> <add> /** <add> * Returns the pattern of the version for this converter as a regular expression. <add> * All is enclosed by brackets indicating a capturing group. <add> * Non capturing groups may occur without restriction <add> * but capturing groups except the outermost one must come sequential. <add> * This patters is part of the converters output <add> * as indicated by {@link #getVersionEnvironment()}. <add> * <add> * @return <add> * the pattern of the version for this converter. <add> */ <ide> abstract String getVersionPattern(); <add> <add> /** <add> * Returns the pattern of the output of this converter <add> * if invoked with command {@link #getCommand()} and option {@link #getVersionOption()}. <add> * Here, the literal <code>%s</code> indicates the location <add> * of the proper version pattern given by {@link #getVersionPattern()}. <add> * If this is included a regular expression emerges. <add> * <add> * @return <add> * the pattern of the output of this converter containing its version. <add> */ <ide> abstract String getVersionEnvironment(); <ide> <ide> }
Java
agpl-3.0
87e393e845751d5da585c69aee7e305ef32c6434
0
opensourceBIM/BIMserver,opensourceBIM/BIMserver,opensourceBIM/BIMserver
package org.bimserver.ifc.step.serializer; /****************************************************************************** * Copyright (C) 2011 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 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/>. *****************************************************************************/ import java.io.OutputStream; import java.io.PrintWriter; import java.nio.ByteBuffer; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List; import org.bimserver.emf.IdEObject; import org.bimserver.ifc.IfcSerializer; import org.bimserver.models.ifc2x3.Ifc2x3Package; import org.bimserver.models.ifc2x3.IfcGloballyUniqueId; import org.bimserver.models.ifc2x3.Tristate; import org.bimserver.models.ifc2x3.WrappedValue; import org.bimserver.plugins.PluginException; import org.bimserver.plugins.PluginManager; import org.bimserver.plugins.schema.EntityDefinition; import org.bimserver.plugins.schema.SchemaDefinition; import org.bimserver.plugins.serializers.IfcModelInterface; import org.bimserver.plugins.serializers.ProjectInfo; import org.bimserver.plugins.serializers.SerializerException; import org.bimserver.utils.UTFPrintWriter; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EEnum; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.EcorePackage; import com.google.common.base.Charsets; public class IfcStepSerializer extends IfcSerializer { private static final EcorePackage ECORE_PACKAGE_INSTANCE = EcorePackage.eINSTANCE; private static final String NULL = "NULL"; private static final String OPEN_CLOSE_PAREN = "()"; private static final String ASTERISK = "*"; private static final String PAREN_CLOSE_SEMICOLON = ");"; private static final String DOT_0 = ".0"; private static final String DASH = "#"; private static final String IFC_LOGICAL = "IfcLogical"; private static final String IFC_BOOLEAN = "IfcBoolean"; private static final String DOT = "."; private static final String COMMA = ","; private static final String OPEN_CLOSE = "("; private static final String CLOSE_PAREN = ")"; private static final String BOOLEAN_UNDEFINED = ".U."; private static final String SINGLE_QUOTE = "'"; private static final String BOOLEAN_FALSE = ".F."; private static final String BOOLEAN_TRUE = ".T."; private static final String DOLLAR = "$"; private static final String WRAPPED_VALUE = "wrappedValue"; private String fileDescription = ""; private String name = ""; private String author = ""; private String organization = ""; private String originatingSystem = ""; private String authorization = ""; private String preProcessorVersion = ""; private Date date = new Date(); private Iterator<Long> iterator; private UTFPrintWriter out; @Override public void init(IfcModelInterface model, ProjectInfo projectInfo, PluginManager pluginManager) throws SerializerException { super.init(model, projectInfo, pluginManager); } @Override protected void reset() { setMode(Mode.HEADER); out = null; } public boolean write(OutputStream outputStream) throws SerializerException { if (out == null) { out = new UTFPrintWriter(outputStream); } if (getMode() == Mode.HEADER) { writeHeader(out); setMode(Mode.BODY); iterator = model.keySet().iterator(); out.flush(); return true; } else if (getMode() == Mode.BODY) { if (iterator.hasNext()) { long key = iterator.next(); if (key != -1) { write(out, key, model.get(key)); } } else { iterator = null; setMode(Mode.FOOTER); return write(outputStream); } return true; } else if (getMode() == Mode.FOOTER) { writeFooter(out); out.flush(); setMode(Mode.FINISHED); return true; } else if (getMode() == Mode.FINISHED) { return false; } return false; } public void setFileDescription(String fileDescription) { this.fileDescription = fileDescription; } public void setName(String name) { this.name = name; } public void setAuthor(String author) { this.author = author; } public void setOrganization(String organization) { this.organization = organization; } public void setOriginatingSystem(String originatingSystem) { this.originatingSystem = originatingSystem; } public void setAuthorization(String authorization) { this.authorization = authorization; } public void setDate(Date date) { this.date = date; } public void setPreProcessorVersion(String preProcessorVersion) { this.preProcessorVersion = preProcessorVersion; } private void writeFooter(UTFPrintWriter out) { out.println("ENDSEC;"); out.println("END-ISO-10303-21;"); } private void writeHeader(UTFPrintWriter out) { SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss"); String dateString = dateFormatter.format(date); out.println("ISO-10303-21;"); out.println("HEADER;"); out.println("FILE_DESCRIPTION (('" + fileDescription + "'), '2;1');"); out.println("FILE_NAME ('" + name + "', '" + dateString + "', ('" + author + "'), ('" + organization + "'), '" + preProcessorVersion + "', '" + originatingSystem + "', '" + authorization + "');"); out.println("FILE_SCHEMA (('IFC2X3'));"); out.println("ENDSEC;"); out.println("DATA;"); // out.println("//This program comes with ABSOLUTELY NO WARRANTY."); // out.println("//This is free software, and you are welcome to redistribute it under certain conditions. See www.bimserver.org <http://www.bimserver.org>"); } private void writePrimitive(PrintWriter out, Object val) { if (val instanceof Tristate) { Tristate bool = (Tristate) val; if (bool == Tristate.TRUE) { out.print(BOOLEAN_TRUE); } else if (bool == Tristate.FALSE) { out.print(BOOLEAN_FALSE); } else if (bool == Tristate.UNDEFINED) { out.print(BOOLEAN_UNDEFINED); } } else if (val instanceof Float || val instanceof Double) { String string = val.toString(); if (string.endsWith(DOT_0)) { out.print(string.substring(0, string.length() - 1)); } else { out.print(string); } } else if (val instanceof Boolean) { Boolean bool = (Boolean)val; if (bool) { out.print(BOOLEAN_TRUE); } else { out.print(BOOLEAN_FALSE); } } else if (val instanceof String) { out.print(SINGLE_QUOTE); String stringVal = (String)val; StringBuilder sb = new StringBuilder(); for (int i=0; i<stringVal.length(); i++) { char c = stringVal.charAt(i); if (c <= 126) { sb.append(c); // ISO 8859-1 } else { // ISO 8859-1 with -128 offset ByteBuffer encode = Charsets.ISO_8859_1.encode(new String(new char[]{(char) (c - 128)})); sb.append("\\S\\" + (char)encode.get()); } } out.print(sb.toString()); out.print(SINGLE_QUOTE); } else { out.print(val == null ? "$" : val.toString()); } } private void write(PrintWriter out, Long key, EObject object) throws SerializerException { EClass eClass = object.eClass(); out.print(DASH); out.print(String.valueOf(key)); out.print("= "); out.print(upperCases.get(eClass)); out.print(OPEN_CLOSE); boolean isFirst = true; for (EStructuralFeature feature : eClass.getEAllStructuralFeatures()) { if (!feature.isDerived() && !feature.isVolatile() && !feature.getName().endsWith("AsString")) { EClassifier type = feature.getEType(); if (type instanceof EEnum) { if (!isFirst) { out.print(COMMA); } writeEnum(out, object, feature); isFirst = false; } else if (type instanceof EClass) { if (!isInverse(feature)) { if (!isFirst) { out.print(COMMA); } writeEClass(out, object, feature); isFirst = false; } } else if (type instanceof EDataType) { if (!isFirst) { out.print(COMMA); } writeEDataType(out, object, feature); isFirst = false; } } } out.println(PAREN_CLOSE_SEMICOLON); } private void writeEDataType(PrintWriter out, EObject object, EStructuralFeature feature) throws SerializerException { SchemaDefinition schema; try { schema = getPluginManager().requireSchemaDefinition(); } catch (PluginException e) { throw new SerializerException(e); } EntityDefinition entityBN = schema.getEntityBNNoCaseConvert(upperCases.get(object.eClass())); if (entityBN != null && entityBN.isDerived(feature.getName())) { out.print(ASTERISK); } else if (feature.isMany()) { writeList(out, object, feature); } else { writeObject(out, object, feature); } } private void writeEClass(PrintWriter out, EObject object, EStructuralFeature feature) throws SerializerException { Object referencedObject = object.eGet(feature); if (referencedObject instanceof WrappedValue || referencedObject instanceof IfcGloballyUniqueId) { writeWrappedValue(out, object, feature, ((EObject)referencedObject).eClass()); } else { SchemaDefinition schema; try { schema = getPluginManager().requireSchemaDefinition(); } catch (PluginException e) { throw new SerializerException(e); } EntityDefinition entityBN = schema.getEntityBNNoCaseConvert(upperCases.get(object.eClass())); if (referencedObject instanceof EObject && model.contains((IdEObject) referencedObject)) { out.print(DASH); out.print(String.valueOf(model.get((IdEObject) referencedObject))); } else { if (entityBN != null && entityBN.isDerived(feature.getName())) { out.print(ASTERISK); } else if (feature.isMany()) { writeList(out, object, feature); } else { writeObject(out, object, feature); } } } } private void writeObject(PrintWriter out, EObject object, EStructuralFeature feature) { Object ref = object.eGet(feature); if (ref == null) { EClassifier type = feature.getEType(); if (type instanceof EClass) { EStructuralFeature structuralFeature = ((EClass) type).getEStructuralFeature(WRAPPED_VALUE); if (structuralFeature != null) { String name = structuralFeature.getEType().getName(); if (structuralFeature.isUnsettable()) { out.print(DOLLAR); } else if (name.equals(IFC_BOOLEAN) || name.equals(IFC_LOGICAL)) { out.print(BOOLEAN_UNDEFINED); } else { out.print(DOLLAR); } } else { out.print(DOLLAR); } } else { out.print(DOLLAR); } } else { if (ref instanceof EObject) { writeEmbedded(out, (EObject) ref); } else if (feature.getEType() == ECORE_PACKAGE_INSTANCE.getEFloat() || feature.getEType() == ECORE_PACKAGE_INSTANCE.getEDouble()) { Object eGet = object.eGet(object.eClass().getEStructuralFeature(feature.getName() + "AsString")); if (eGet != null) { out.print(eGet); } else { out.print(DOLLAR); } } else { writePrimitive(out, ref); } } } private void writeEmbedded(PrintWriter out, EObject eObject) { EClass class1 = eObject.eClass(); out.print(upperCases.get(class1)); out.print(OPEN_CLOSE); EStructuralFeature structuralFeature = class1.getEStructuralFeature(WRAPPED_VALUE); if (structuralFeature != null) { Object get = eObject.eGet(structuralFeature); if (structuralFeature.getEType() == ECORE_PACKAGE_INSTANCE.getEFloat() || structuralFeature.getEType() == ECORE_PACKAGE_INSTANCE.getEDouble()) { Object realVal = eObject.eGet(class1.getEStructuralFeature(structuralFeature.getName() + "AsString")); if (realVal != null) { out.print(realVal); } else { out.print(get); } } else { writePrimitive(out, get); } } out.print(CLOSE_PAREN); } private void writeList(PrintWriter out, EObject object, EStructuralFeature feature) { List<?> list = (List<?>) object.eGet(feature); if (list.size() == 0) { if (feature.isUnsettable()) { out.print(DOLLAR); } else { out.print(OPEN_CLOSE_PAREN); } } else { out.print(OPEN_CLOSE); boolean first = true; for (Object listObject : list) { if (!first) { out.print(COMMA); } if ((listObject instanceof IdEObject) && model.contains((IdEObject)listObject)) { IdEObject eObject = (IdEObject) listObject; out.print(DASH); out.print(String.valueOf(model.get(eObject))); } else { if (listObject == null) { out.print(DOLLAR); } else { if (listObject instanceof WrappedValue && Ifc2x3Package.eINSTANCE.getWrappedValue().isSuperTypeOf((EClass) feature.getEType())) { IdEObject eObject = (IdEObject) listObject; Object realVal = eObject.eGet(eObject.eClass().getEStructuralFeature("wrappedValue")); if (realVal instanceof Float || realVal instanceof Double) { Object stringVal = eObject.eGet(eObject.eClass().getEStructuralFeature("wrappedValueAsString")); if (stringVal != null) { out.print(stringVal); } else { out.print(realVal); } } else { writePrimitive(out, realVal); } } else if (listObject instanceof EObject) { IdEObject eObject = (IdEObject) listObject; EClass class1 = eObject.eClass(); EStructuralFeature structuralFeature = class1.getEStructuralFeature(WRAPPED_VALUE); if (structuralFeature != null) { Object realVal = eObject.eGet(structuralFeature); out.print(upperCases.get(class1)); out.print(OPEN_CLOSE); if (realVal instanceof Float || realVal instanceof Double) { Object stringVal = eObject.eGet(class1.getEStructuralFeature(structuralFeature.getName() + "AsString")); if (stringVal != null) { out.print(stringVal); } else { out.print(realVal); } } else { writePrimitive(out, realVal); } out.print(CLOSE_PAREN); } } else { writePrimitive(out, listObject); } } } first = false; } out.print(CLOSE_PAREN); } } private void writeWrappedValue(PrintWriter out, EObject object, EStructuralFeature feature, EClass ec) throws SerializerException { Object get = object.eGet(feature); boolean isWrapped = Ifc2x3Package.eINSTANCE.getWrappedValue().isSuperTypeOf(ec) || ec == Ifc2x3Package.eINSTANCE.getIfcGloballyUniqueId(); EStructuralFeature structuralFeature = ec.getEStructuralFeature(WRAPPED_VALUE); if (get instanceof EObject) { boolean isDefinedWrapped = Ifc2x3Package.eINSTANCE.getWrappedValue().isSuperTypeOf((EClass) feature.getEType()) || feature.getEType() == Ifc2x3Package.eINSTANCE.getIfcGloballyUniqueId(); EObject betweenObject = (EObject) get; if (betweenObject != null) { if (isWrapped && isDefinedWrapped) { Object val = betweenObject.eGet(structuralFeature); String name = structuralFeature.getEType().getName(); if ((name.equals(IFC_BOOLEAN) || name.equals(IFC_LOGICAL)) && val == null) { out.print(BOOLEAN_UNDEFINED); } else if (structuralFeature.getEType() == ECORE_PACKAGE_INSTANCE.getEFloat()) { Object stringVal = betweenObject.eGet(betweenObject.eClass().getEStructuralFeature("wrappedValueAsString")); if (stringVal != null) { out.print(stringVal); } else { out.print(val); } } else { writePrimitive(out, val); } } else { writeEmbedded(out, betweenObject); } } } else if (get instanceof EList<?>) { EList<?> list = (EList<?>) get; if (list.size() == 0) { if (feature.isUnsettable()) { out.print(DOLLAR); } else { out.print(OPEN_CLOSE_PAREN); } } else { out.print(OPEN_CLOSE); boolean first = true; for (Object o : list) { if (!first) { out.print(COMMA); } EObject object2 = (EObject) o; Object val = object2.eGet(structuralFeature); if (structuralFeature.getEType() == ECORE_PACKAGE_INSTANCE.getEFloat()) { out.print(object2.eGet(object2.eClass().getEStructuralFeature("stringValue" + structuralFeature.getName()))); } else { writePrimitive(out, val); } first = false; } out.print(CLOSE_PAREN); } } else { if (get == null) { EClassifier type = structuralFeature.getEType(); if (type == IFC_PACKAGE_INSTANCE.getIfcBoolean() || type == IFC_PACKAGE_INSTANCE.getIfcLogical() || type == ECORE_PACKAGE_INSTANCE.getEBoolean()) { if (feature.isUnsettable()) { out.print(DOLLAR); } else { out.print(BOOLEAN_UNDEFINED); } } else { SchemaDefinition schema; try { schema = getPluginManager().requireSchemaDefinition(); } catch (PluginException e) { throw new SerializerException(e); } EntityDefinition entityBN = schema.getEntityBN(object.eClass().getName()); if (entityBN != null && entityBN.isDerived(feature.getName())) { out.print("*"); } else { out.print(DOLLAR); } } } } } private void writeEnum(PrintWriter out, EObject object, EStructuralFeature feature) { Object val = object.eGet(feature); if (feature.getEType() == Ifc2x3Package.eINSTANCE.getTristate()) { writePrimitive(out, val); } else { if (val == null) { out.print(DOLLAR); } else { if (((Enum<?>) val).toString().equals(NULL)) { out.print(DOLLAR); } else { out.print(DOT); out.print(val.toString()); out.print(DOT); } } } } }
IfcPlugins/src/org/bimserver/ifc/step/serializer/IfcStepSerializer.java
package org.bimserver.ifc.step.serializer; /****************************************************************************** * Copyright (C) 2011 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 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/>. *****************************************************************************/ import java.io.OutputStream; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List; import org.bimserver.emf.IdEObject; import org.bimserver.ifc.IfcSerializer; import org.bimserver.models.ifc2x3.Ifc2x3Package; import org.bimserver.models.ifc2x3.IfcGloballyUniqueId; import org.bimserver.models.ifc2x3.Tristate; import org.bimserver.models.ifc2x3.WrappedValue; import org.bimserver.plugins.PluginException; import org.bimserver.plugins.PluginManager; import org.bimserver.plugins.schema.EntityDefinition; import org.bimserver.plugins.schema.SchemaDefinition; import org.bimserver.plugins.serializers.IfcModelInterface; import org.bimserver.plugins.serializers.ProjectInfo; import org.bimserver.plugins.serializers.SerializerException; import org.bimserver.utils.UTFPrintWriter; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EEnum; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.EcorePackage; public class IfcStepSerializer extends IfcSerializer { private static final EcorePackage ECORE_PACKAGE_INSTANCE = EcorePackage.eINSTANCE; private static final String NULL = "NULL"; private static final String OPEN_CLOSE_PAREN = "()"; private static final String ASTERISK = "*"; private static final String PAREN_CLOSE_SEMICOLON = ");"; private static final String DOT_0 = ".0"; private static final String DASH = "#"; private static final String IFC_LOGICAL = "IfcLogical"; private static final String IFC_BOOLEAN = "IfcBoolean"; private static final String DOT = "."; private static final String COMMA = ","; private static final String OPEN_CLOSE = "("; private static final String CLOSE_PAREN = ")"; private static final String BOOLEAN_UNDEFINED = ".U."; private static final String SINGLE_QUOTE = "'"; private static final String BOOLEAN_FALSE = ".F."; private static final String BOOLEAN_TRUE = ".T."; private static final String DOLLAR = "$"; private static final String WRAPPED_VALUE = "wrappedValue"; private String fileDescription = ""; private String name = ""; private String author = ""; private String organization = ""; private String originatingSystem = ""; private String authorization = ""; private String preProcessorVersion = ""; private Date date = new Date(); private Iterator<Long> iterator; private UTFPrintWriter out; @Override public void init(IfcModelInterface model, ProjectInfo projectInfo, PluginManager pluginManager) throws SerializerException { super.init(model, projectInfo, pluginManager); } @Override protected void reset() { setMode(Mode.HEADER); out = null; } public boolean write(OutputStream outputStream) throws SerializerException { if (out == null) { out = new UTFPrintWriter(outputStream); } if (getMode() == Mode.HEADER) { writeHeader(out); setMode(Mode.BODY); iterator = model.keySet().iterator(); out.flush(); return true; } else if (getMode() == Mode.BODY) { if (iterator.hasNext()) { long key = iterator.next(); if (key != -1) { write(out, key, model.get(key)); } } else { iterator = null; setMode(Mode.FOOTER); return write(outputStream); } return true; } else if (getMode() == Mode.FOOTER) { writeFooter(out); out.flush(); setMode(Mode.FINISHED); return true; } else if (getMode() == Mode.FINISHED) { return false; } return false; } public void setFileDescription(String fileDescription) { this.fileDescription = fileDescription; } public void setName(String name) { this.name = name; } public void setAuthor(String author) { this.author = author; } public void setOrganization(String organization) { this.organization = organization; } public void setOriginatingSystem(String originatingSystem) { this.originatingSystem = originatingSystem; } public void setAuthorization(String authorization) { this.authorization = authorization; } public void setDate(Date date) { this.date = date; } public void setPreProcessorVersion(String preProcessorVersion) { this.preProcessorVersion = preProcessorVersion; } private void writeFooter(UTFPrintWriter out) { out.println("ENDSEC;"); out.println("END-ISO-10303-21;"); } private void writeHeader(UTFPrintWriter out) { SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss"); String dateString = dateFormatter.format(date); out.println("ISO-10303-21;"); out.println("HEADER;"); out.println("FILE_DESCRIPTION (('" + fileDescription + "'), '2;1');"); out.println("FILE_NAME ('" + name + "', '" + dateString + "', ('" + author + "'), ('" + organization + "'), '" + preProcessorVersion + "', '" + originatingSystem + "', '" + authorization + "');"); out.println("FILE_SCHEMA (('IFC2X3'));"); out.println("ENDSEC;"); out.println("DATA;"); // out.println("//This program comes with ABSOLUTELY NO WARRANTY."); // out.println("//This is free software, and you are welcome to redistribute it under certain conditions. See www.bimserver.org <http://www.bimserver.org>"); } private void writePrimitive(PrintWriter out, Object val) { if (val instanceof Tristate) { Tristate bool = (Tristate) val; if (bool == Tristate.TRUE) { out.print(BOOLEAN_TRUE); } else if (bool == Tristate.FALSE) { out.print(BOOLEAN_FALSE); } else if (bool == Tristate.UNDEFINED) { out.print(BOOLEAN_UNDEFINED); } } else if (val instanceof Float || val instanceof Double) { String string = val.toString(); if (string.endsWith(DOT_0)) { out.print(string.substring(0, string.length() - 1)); } else { out.print(string); } } else if (val instanceof Boolean) { Boolean bool = (Boolean)val; if (bool) { out.print(BOOLEAN_TRUE); } else { out.print(BOOLEAN_FALSE); } } else if (val instanceof String) { out.print(SINGLE_QUOTE); out.print(val.toString()); out.print(SINGLE_QUOTE); } else { out.print(val == null ? "$" : val.toString()); } } private void write(PrintWriter out, Long key, EObject object) throws SerializerException { EClass eClass = object.eClass(); out.print(DASH); out.print(String.valueOf(key)); out.print("= "); out.print(upperCases.get(eClass)); out.print(OPEN_CLOSE); boolean isFirst = true; for (EStructuralFeature feature : eClass.getEAllStructuralFeatures()) { if (!feature.isDerived() && !feature.isVolatile() && !feature.getName().endsWith("AsString")) { EClassifier type = feature.getEType(); if (type instanceof EEnum) { if (!isFirst) { out.print(COMMA); } writeEnum(out, object, feature); isFirst = false; } else if (type instanceof EClass) { if (!isInverse(feature)) { if (!isFirst) { out.print(COMMA); } writeEClass(out, object, feature); isFirst = false; } } else if (type instanceof EDataType) { if (!isFirst) { out.print(COMMA); } writeEDataType(out, object, feature); isFirst = false; } } } out.println(PAREN_CLOSE_SEMICOLON); } private void writeEDataType(PrintWriter out, EObject object, EStructuralFeature feature) throws SerializerException { SchemaDefinition schema; try { schema = getPluginManager().requireSchemaDefinition(); } catch (PluginException e) { throw new SerializerException(e); } EntityDefinition entityBN = schema.getEntityBNNoCaseConvert(upperCases.get(object.eClass())); if (entityBN != null && entityBN.isDerived(feature.getName())) { out.print(ASTERISK); } else if (feature.isMany()) { writeList(out, object, feature); } else { writeObject(out, object, feature); } } private void writeEClass(PrintWriter out, EObject object, EStructuralFeature feature) throws SerializerException { Object referencedObject = object.eGet(feature); if (referencedObject instanceof WrappedValue || referencedObject instanceof IfcGloballyUniqueId) { writeWrappedValue(out, object, feature, ((EObject)referencedObject).eClass()); } else { SchemaDefinition schema; try { schema = getPluginManager().requireSchemaDefinition(); } catch (PluginException e) { throw new SerializerException(e); } EntityDefinition entityBN = schema.getEntityBNNoCaseConvert(upperCases.get(object.eClass())); if (referencedObject instanceof EObject && model.contains((IdEObject) referencedObject)) { out.print(DASH); out.print(String.valueOf(model.get((IdEObject) referencedObject))); } else { if (entityBN != null && entityBN.isDerived(feature.getName())) { out.print(ASTERISK); } else if (feature.isMany()) { writeList(out, object, feature); } else { writeObject(out, object, feature); } } } } private void writeObject(PrintWriter out, EObject object, EStructuralFeature feature) { Object ref = object.eGet(feature); if (ref == null) { EClassifier type = feature.getEType(); if (type instanceof EClass) { EStructuralFeature structuralFeature = ((EClass) type).getEStructuralFeature(WRAPPED_VALUE); if (structuralFeature != null) { String name = structuralFeature.getEType().getName(); if (structuralFeature.isUnsettable()) { out.print(DOLLAR); } else if (name.equals(IFC_BOOLEAN) || name.equals(IFC_LOGICAL)) { out.print(BOOLEAN_UNDEFINED); } else { out.print(DOLLAR); } } else { out.print(DOLLAR); } } else { out.print(DOLLAR); } } else { if (ref instanceof EObject) { writeEmbedded(out, (EObject) ref); } else if (feature.getEType() == ECORE_PACKAGE_INSTANCE.getEFloat() || feature.getEType() == ECORE_PACKAGE_INSTANCE.getEDouble()) { Object eGet = object.eGet(object.eClass().getEStructuralFeature(feature.getName() + "AsString")); if (eGet != null) { out.print(eGet); } else { out.print(DOLLAR); } } else { writePrimitive(out, ref); } } } private void writeEmbedded(PrintWriter out, EObject eObject) { EClass class1 = eObject.eClass(); out.print(upperCases.get(class1)); out.print(OPEN_CLOSE); EStructuralFeature structuralFeature = class1.getEStructuralFeature(WRAPPED_VALUE); if (structuralFeature != null) { Object get = eObject.eGet(structuralFeature); if (structuralFeature.getEType() == ECORE_PACKAGE_INSTANCE.getEFloat() || structuralFeature.getEType() == ECORE_PACKAGE_INSTANCE.getEDouble()) { Object realVal = eObject.eGet(class1.getEStructuralFeature(structuralFeature.getName() + "AsString")); if (realVal != null) { out.print(realVal); } else { out.print(get); } } else { writePrimitive(out, get); } } out.print(CLOSE_PAREN); } private void writeList(PrintWriter out, EObject object, EStructuralFeature feature) { List<?> list = (List<?>) object.eGet(feature); if (list.size() == 0) { if (feature.isUnsettable()) { out.print(DOLLAR); } else { out.print(OPEN_CLOSE_PAREN); } } else { out.print(OPEN_CLOSE); boolean first = true; for (Object listObject : list) { if (!first) { out.print(COMMA); } if ((listObject instanceof IdEObject) && model.contains((IdEObject)listObject)) { IdEObject eObject = (IdEObject) listObject; out.print(DASH); out.print(String.valueOf(model.get(eObject))); } else { if (listObject == null) { out.print(DOLLAR); } else { if (listObject instanceof WrappedValue && Ifc2x3Package.eINSTANCE.getWrappedValue().isSuperTypeOf((EClass) feature.getEType())) { IdEObject eObject = (IdEObject) listObject; Object realVal = eObject.eGet(eObject.eClass().getEStructuralFeature("wrappedValue")); if (realVal instanceof Float || realVal instanceof Double) { Object stringVal = eObject.eGet(eObject.eClass().getEStructuralFeature("wrappedValueAsString")); if (stringVal != null) { out.print(stringVal); } else { out.print(realVal); } } else { writePrimitive(out, realVal); } } else if (listObject instanceof EObject) { IdEObject eObject = (IdEObject) listObject; EClass class1 = eObject.eClass(); EStructuralFeature structuralFeature = class1.getEStructuralFeature(WRAPPED_VALUE); if (structuralFeature != null) { Object realVal = eObject.eGet(structuralFeature); out.print(upperCases.get(class1)); out.print(OPEN_CLOSE); if (realVal instanceof Float || realVal instanceof Double) { Object stringVal = eObject.eGet(class1.getEStructuralFeature(structuralFeature.getName() + "AsString")); if (stringVal != null) { out.print(stringVal); } else { out.print(realVal); } } else { writePrimitive(out, realVal); } out.print(CLOSE_PAREN); } } else { writePrimitive(out, listObject); } } } first = false; } out.print(CLOSE_PAREN); } } private void writeWrappedValue(PrintWriter out, EObject object, EStructuralFeature feature, EClass ec) throws SerializerException { Object get = object.eGet(feature); boolean isWrapped = Ifc2x3Package.eINSTANCE.getWrappedValue().isSuperTypeOf(ec) || ec == Ifc2x3Package.eINSTANCE.getIfcGloballyUniqueId(); EStructuralFeature structuralFeature = ec.getEStructuralFeature(WRAPPED_VALUE); if (get instanceof EObject) { boolean isDefinedWrapped = Ifc2x3Package.eINSTANCE.getWrappedValue().isSuperTypeOf((EClass) feature.getEType()) || feature.getEType() == Ifc2x3Package.eINSTANCE.getIfcGloballyUniqueId(); EObject betweenObject = (EObject) get; if (betweenObject != null) { if (isWrapped && isDefinedWrapped) { Object val = betweenObject.eGet(structuralFeature); String name = structuralFeature.getEType().getName(); if ((name.equals(IFC_BOOLEAN) || name.equals(IFC_LOGICAL)) && val == null) { out.print(BOOLEAN_UNDEFINED); } else if (structuralFeature.getEType() == ECORE_PACKAGE_INSTANCE.getEFloat()) { Object stringVal = betweenObject.eGet(betweenObject.eClass().getEStructuralFeature("wrappedValueAsString")); if (stringVal != null) { out.print(stringVal); } else { out.print(val); } } else { writePrimitive(out, val); } } else { writeEmbedded(out, betweenObject); } } } else if (get instanceof EList<?>) { EList<?> list = (EList<?>) get; if (list.size() == 0) { if (feature.isUnsettable()) { out.print(DOLLAR); } else { out.print(OPEN_CLOSE_PAREN); } } else { out.print(OPEN_CLOSE); boolean first = true; for (Object o : list) { if (!first) { out.print(COMMA); } EObject object2 = (EObject) o; Object val = object2.eGet(structuralFeature); if (structuralFeature.getEType() == ECORE_PACKAGE_INSTANCE.getEFloat()) { out.print(object2.eGet(object2.eClass().getEStructuralFeature("stringValue" + structuralFeature.getName()))); } else { writePrimitive(out, val); } first = false; } out.print(CLOSE_PAREN); } } else { if (get == null) { EClassifier type = structuralFeature.getEType(); if (type == IFC_PACKAGE_INSTANCE.getIfcBoolean() || type == IFC_PACKAGE_INSTANCE.getIfcLogical() || type == ECORE_PACKAGE_INSTANCE.getEBoolean()) { if (feature.isUnsettable()) { out.print(DOLLAR); } else { out.print(BOOLEAN_UNDEFINED); } } else { SchemaDefinition schema; try { schema = getPluginManager().requireSchemaDefinition(); } catch (PluginException e) { throw new SerializerException(e); } EntityDefinition entityBN = schema.getEntityBN(object.eClass().getName()); if (entityBN != null && entityBN.isDerived(feature.getName())) { out.print("*"); } else { out.print(DOLLAR); } } } } } private void writeEnum(PrintWriter out, EObject object, EStructuralFeature feature) { Object val = object.eGet(feature); if (feature.getEType() == Ifc2x3Package.eINSTANCE.getTristate()) { writePrimitive(out, val); } else { if (val == null) { out.print(DOLLAR); } else { if (((Enum<?>) val).toString().equals(NULL)) { out.print(DOLLAR); } else { out.print(DOT); out.print(val.toString()); out.print(DOT); } } } } }
http://code.google.com/p/bimserver/issues/detail?id=293
IfcPlugins/src/org/bimserver/ifc/step/serializer/IfcStepSerializer.java
http://code.google.com/p/bimserver/issues/detail?id=293
<ide><path>fcPlugins/src/org/bimserver/ifc/step/serializer/IfcStepSerializer.java <ide> <ide> import java.io.OutputStream; <ide> import java.io.PrintWriter; <add>import java.nio.ByteBuffer; <ide> import java.text.SimpleDateFormat; <ide> import java.util.Date; <ide> import java.util.Iterator; <ide> import org.eclipse.emf.ecore.EStructuralFeature; <ide> import org.eclipse.emf.ecore.EcorePackage; <ide> <add>import com.google.common.base.Charsets; <add> <ide> public class IfcStepSerializer extends IfcSerializer { <ide> private static final EcorePackage ECORE_PACKAGE_INSTANCE = EcorePackage.eINSTANCE; <ide> private static final String NULL = "NULL"; <ide> } <ide> } else if (val instanceof String) { <ide> out.print(SINGLE_QUOTE); <del> out.print(val.toString()); <add> String stringVal = (String)val; <add> StringBuilder sb = new StringBuilder(); <add> for (int i=0; i<stringVal.length(); i++) { <add> char c = stringVal.charAt(i); <add> if (c <= 126) { <add> sb.append(c); <add> // ISO 8859-1 <add> } else { <add> // ISO 8859-1 with -128 offset <add> ByteBuffer encode = Charsets.ISO_8859_1.encode(new String(new char[]{(char) (c - 128)})); <add> sb.append("\\S\\" + (char)encode.get()); <add> } <add> } <add> out.print(sb.toString()); <ide> out.print(SINGLE_QUOTE); <ide> } else { <ide> out.print(val == null ? "$" : val.toString());
Java
apache-2.0
b6889eec28c42c383b3a6c94d76b198590a1282c
0
izumin5210/Bletia
package info.izumin.android.bletia; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.support.test.runner.AndroidJUnit4; import org.jdeferred.Deferred; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import java.util.UUID; import info.izumin.android.bletia.action.EnableNotificationAction; import info.izumin.android.bletia.action.ReadCharacteristicAction; import info.izumin.android.bletia.action.ReadDescriptorAction; import info.izumin.android.bletia.action.ReadRemoteRssiAction; import info.izumin.android.bletia.action.WriteCharacteristicAction; import info.izumin.android.bletia.action.WriteDescriptorAction; import info.izumin.android.bletia.wrapper.BluetoothGattWrapper; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Created by izumin on 10/2/15. */ @RunWith(AndroidJUnit4.class) public class BluetoothGattCallbackHandlerTest { private BluetoothGattCallbackHandler mCallbackHandler; private ActionQueueContainer mQueueContainer; @Mock private BluetoothGattCallbackHandler.Callback mCallback; @Mock private BluetoothGattWrapper mGattWrapper; @Mock private BluetoothGattCharacteristic mCharacteristic; @Mock private BluetoothGattDescriptor mDescriptor; @Mock private ReadCharacteristicAction mReadCharacteristicAction; @Mock private WriteCharacteristicAction mWriteCharacteristicAction; @Mock private ReadDescriptorAction mReadDescriptorAction; @Mock private WriteDescriptorAction mWriteDescriptorAction; @Mock private EnableNotificationAction mNotificationAction; @Mock private ReadRemoteRssiAction mRssiAction; @Mock private Deferred<BluetoothGattCharacteristic, BletiaException, Void> mCharacteristicDeferred; @Mock private Deferred<BluetoothGattDescriptor, BletiaException, Void> mDescriptorDeferred; @Mock private Deferred<Integer, BletiaException, Void> mIntegerDeferred; private ArgumentCaptor<BletiaException> mExceptionCaptor; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); mQueueContainer = Mockito.mock(ActionQueueContainer.class, Mockito.RETURNS_DEEP_STUBS); mCallbackHandler = new BluetoothGattCallbackHandler(mCallback, mQueueContainer); when(mReadCharacteristicAction.getDeferred()).thenReturn(mCharacteristicDeferred); when(mWriteCharacteristicAction.getDeferred()).thenReturn(mCharacteristicDeferred); when(mReadDescriptorAction.getDeferred()).thenReturn(mDescriptorDeferred); when(mWriteDescriptorAction.getDeferred()).thenReturn(mDescriptorDeferred); when(mNotificationAction.getDeferred()).thenReturn(mCharacteristicDeferred); when(mRssiAction.getDeferred()).thenReturn(mIntegerDeferred); when(mQueueContainer.getReadCharacteristicActionQueue().dequeue(any(UUID.class))).thenReturn(mReadCharacteristicAction); when(mQueueContainer.getWriteCharacteristicActionQueue().dequeue(any(UUID.class))).thenReturn(mWriteCharacteristicAction); when(mQueueContainer.getReadDescriptorActionQueue().dequeue(any(UUID.class))).thenReturn(mReadDescriptorAction); when(mQueueContainer.getWriteDescriptorActionQueue().dequeue(any(UUID.class))).thenReturn(mWriteDescriptorAction); when(mQueueContainer.getEnableNotificationActionQueue().dequeue(any(UUID.class))).thenReturn(mNotificationAction); when(mQueueContainer.getReadRemoteRssiActionQueue().dequeue(null)).thenReturn(mRssiAction); when(mDescriptor.getUuid()).thenReturn(UUID.randomUUID()); when(mDescriptor.getCharacteristic()).thenReturn(mCharacteristic); mExceptionCaptor = ArgumentCaptor.forClass(BletiaException.class); } @Test public void onConnectionStateChange_WhenStatusIsSuccessAndNewStateIsConnected() throws Exception { mCallbackHandler.onConnectionStateChange(mGattWrapper, BluetoothGatt.GATT_SUCCESS, BluetoothGatt.STATE_CONNECTED); verify(mCallback, times(1)).onConnect(mGattWrapper); } @Test public void onConnectionStateChange_WhenStatusIsSuccessAndNewStateIsDisconnected() throws Exception { mCallbackHandler.onConnectionStateChange(mGattWrapper, BluetoothGatt.GATT_SUCCESS, BluetoothGatt.STATE_DISCONNECTED); verify(mCallback, times(1)).onDisconnect(mGattWrapper); } @Test public void onConnectionStateChange_WhenStatusIsFailureAndNewStateIsConnected() throws Exception { mCallbackHandler.onConnectionStateChange(mGattWrapper, BluetoothGatt.GATT_FAILURE, BluetoothGatt.STATE_CONNECTED); verify(mCallback, times(1)).onError(mExceptionCaptor.capture()); BletiaException e = mExceptionCaptor.getValue(); assertThat(e.getTag()).isEqualTo("onConnectionStateChange"); } @Test public void onConnectionStateChange_WhenStatusIsFailureAndNewStateIsDisconnected() throws Exception { mCallbackHandler.onConnectionStateChange(mGattWrapper, BluetoothGatt.GATT_FAILURE, BluetoothGatt.STATE_DISCONNECTED); verify(mCallback, times(1)).onDisconnect(mGattWrapper); } @Test public void onServiceDiscovered_WhenStatusIsSuccess() throws Exception { mCallbackHandler.onServicesDiscovered(mGattWrapper, BluetoothGatt.GATT_SUCCESS); verify(mCallback, times(1)).onServiceDiscovered(BluetoothGatt.GATT_SUCCESS); } @Test public void onServiceDiscovered_WhenStatusIsFailure() throws Exception { mCallbackHandler.onServicesDiscovered(mGattWrapper, BluetoothGatt.GATT_FAILURE); verify(mCallback, times(1)).onServiceDiscovered(BluetoothGatt.GATT_FAILURE); } @Test public void onCharacteristicRead_WhenStatusIsSuccess() throws Exception { mCallbackHandler.onCharacteristicRead(mGattWrapper, mCharacteristic, BluetoothGatt.GATT_SUCCESS); verify(mCharacteristicDeferred, times(1)).resolve(mCharacteristic); } @Test public void onCharacteristicRead_WhenStatusIsFailure() throws Exception { mCallbackHandler.onCharacteristicRead(mGattWrapper, mCharacteristic, BluetoothGatt.GATT_FAILURE); verify(mCharacteristicDeferred, times(1)).reject(mExceptionCaptor.capture()); BletiaException e = mExceptionCaptor.getValue(); assertThat(e.getAction()).isEqualTo(mReadCharacteristicAction); assertThat(e.getType()).isEqualTo(BleErrorType.FAILURE); } @Test public void onCharacteristicWrite_WhenStatusIsSuccess() throws Exception { mCallbackHandler.onCharacteristicWrite(mGattWrapper, mCharacteristic, BluetoothGatt.GATT_SUCCESS); verify(mCharacteristicDeferred, times(1)).resolve(mCharacteristic); } @Test public void onCharacteristicWrite_WhenStatusIsFailure() throws Exception { mCallbackHandler.onCharacteristicWrite(mGattWrapper, mCharacteristic, BluetoothGatt.GATT_FAILURE); verify(mCharacteristicDeferred, times(1)).reject(mExceptionCaptor.capture()); BletiaException e = mExceptionCaptor.getValue(); assertThat(e.getAction()).isEqualTo(mWriteCharacteristicAction); assertThat(e.getType()).isEqualTo(BleErrorType.FAILURE); } @Test public void onCharacteristicChanged() throws Exception { mCallbackHandler.onCharacteristicChanged(mGattWrapper, mCharacteristic); verify(mCallback, times(1)).onCharacteristicChanged(mCharacteristic); } @Test public void onDescriptorRead_WhenStatusIsSuccess() throws Exception { mCallbackHandler.onDescriptorRead(mGattWrapper, mDescriptor, BluetoothGatt.GATT_SUCCESS); verify(mDescriptorDeferred, times(1)).resolve(mDescriptor); } @Test public void onDescriptorRead_WhenStatusIsFailure() throws Exception { mCallbackHandler.onDescriptorRead(mGattWrapper, mDescriptor, BluetoothGatt.GATT_FAILURE); verify(mDescriptorDeferred, times(1)).reject(mExceptionCaptor.capture()); BletiaException e = mExceptionCaptor.getValue(); assertThat(e.getAction()).isEqualTo(mReadDescriptorAction); assertThat(e.getType()).isEqualTo(BleErrorType.FAILURE); } @Test public void onDescriptorWrite_WhenStatusIsSuccess() throws Exception { mCallbackHandler.onDescriptorWrite(mGattWrapper, mDescriptor, BluetoothGatt.GATT_SUCCESS); verify(mDescriptorDeferred, times(1)).resolve(mDescriptor); } @Test public void onDescriptorWrite_WhenStatusIsFailure() throws Exception { mCallbackHandler.onDescriptorWrite(mGattWrapper, mDescriptor, BluetoothGatt.GATT_FAILURE); verify(mDescriptorDeferred, times(1)).reject(mExceptionCaptor.capture()); BletiaException e = mExceptionCaptor.getValue(); assertThat(e.getAction()).isEqualTo(mWriteDescriptorAction); assertThat(e.getType()).isEqualTo(BleErrorType.FAILURE); } @Test public void onDescriptorWrite_ThatIsNotificationDescriptor_WhenStatusIsSuccess() throws Exception { when(mDescriptor.getUuid()).thenReturn(Bletia.CLIENT_CHARCTERISTIC_CONFIG); when(mDescriptor.getValue()).thenReturn(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); mCallbackHandler.onDescriptorWrite(mGattWrapper, mDescriptor, BluetoothGatt.GATT_SUCCESS); verify(mCharacteristicDeferred, times(1)).resolve(mCharacteristic); } @Test public void onDescriptorWrite_ThatIsNotificationDescriptor_WhenStatusIsFailure() throws Exception { when(mDescriptor.getUuid()).thenReturn(Bletia.CLIENT_CHARCTERISTIC_CONFIG); when(mDescriptor.getValue()).thenReturn(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); mCallbackHandler.onDescriptorWrite(mGattWrapper, mDescriptor, BluetoothGatt.GATT_FAILURE); verify(mCharacteristicDeferred, times(1)).reject(mExceptionCaptor.capture()); BletiaException e = mExceptionCaptor.getValue(); assertThat(e.getAction()).isEqualTo(mNotificationAction); assertThat(e.getType()).isEqualTo(BleErrorType.FAILURE); } @Test public void onReadRemoteRssi_WhenStatusIsSuccess() throws Exception { mCallbackHandler.onReadRemoteRssi(mGattWrapper, 10, BluetoothGatt.GATT_SUCCESS); verify(mIntegerDeferred, times(1)).resolve(10); } @Test public void onReadRemoteRssi_WhenStatusIsFailure() throws Exception { mCallbackHandler.onReadRemoteRssi(mGattWrapper, 10, BluetoothGatt.GATT_FAILURE); verify(mIntegerDeferred, times(1)).reject(mExceptionCaptor.capture()); BletiaException e = mExceptionCaptor.getValue(); assertThat(e.getAction()).isEqualTo(mRssiAction); assertThat(e.getType()).isEqualTo(BleErrorType.FAILURE); } }
bletia/src/androidTest/java/info/izumin/android/bletia/BluetoothGattCallbackHandlerTest.java
package info.izumin.android.bletia; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.support.test.runner.AndroidJUnit4; import org.jdeferred.Deferred; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import java.util.UUID; import info.izumin.android.bletia.action.EnableNotificationAction; import info.izumin.android.bletia.action.ReadCharacteristicAction; import info.izumin.android.bletia.action.ReadDescriptorAction; import info.izumin.android.bletia.action.ReadRemoteRssiAction; import info.izumin.android.bletia.action.WriteCharacteristicAction; import info.izumin.android.bletia.action.WriteDescriptorAction; import info.izumin.android.bletia.wrapper.BluetoothGattWrapper; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Created by izumin on 10/2/15. */ @RunWith(AndroidJUnit4.class) public class BluetoothGattCallbackHandlerTest { private BluetoothGattCallbackHandler mCallbackHandler; private ActionQueueContainer mQueueContainer; @Mock private BluetoothGattCallbackHandler.Callback mCallback; @Mock private BluetoothGattWrapper mGattWrapper; @Mock private BluetoothGattCharacteristic mCharacteristic; @Mock private BluetoothGattDescriptor mDescriptor; @Mock private ReadCharacteristicAction mReadCharacteristicAction; @Mock private WriteCharacteristicAction mWriteCharacteristicAction; @Mock private ReadDescriptorAction mReadDescriptorAction; @Mock private WriteDescriptorAction mWriteDescriptorAction; @Mock private EnableNotificationAction mNotificationAction; @Mock private ReadRemoteRssiAction mRssiAction; @Mock private Deferred<BluetoothGattCharacteristic, BletiaException, Object> mCharacteristicDeferred; @Mock private Deferred<BluetoothGattDescriptor, BletiaException, Object> mDescriptorDeferred; @Mock private Deferred<Integer, BletiaException, Object> mIntegerDeferred; private ArgumentCaptor<BletiaException> mExceptionCaptor; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); mQueueContainer = Mockito.mock(ActionQueueContainer.class, Mockito.RETURNS_DEEP_STUBS); mCallbackHandler = new BluetoothGattCallbackHandler(mCallback, mQueueContainer); when(mReadCharacteristicAction.getDeferred()).thenReturn(mCharacteristicDeferred); when(mWriteCharacteristicAction.getDeferred()).thenReturn(mCharacteristicDeferred); when(mReadDescriptorAction.getDeferred()).thenReturn(mDescriptorDeferred); when(mWriteDescriptorAction.getDeferred()).thenReturn(mDescriptorDeferred); when(mNotificationAction.getDeferred()).thenReturn(mCharacteristicDeferred); when(mRssiAction.getDeferred()).thenReturn(mIntegerDeferred); when(mQueueContainer.getReadCharacteristicActionQueue().dequeue(any(UUID.class))).thenReturn(mReadCharacteristicAction); when(mQueueContainer.getWriteCharacteristicActionQueue().dequeue(any(UUID.class))).thenReturn(mWriteCharacteristicAction); when(mQueueContainer.getReadDescriptorActionQueue().dequeue(any(UUID.class))).thenReturn(mReadDescriptorAction); when(mQueueContainer.getWriteDescriptorActionQueue().dequeue(any(UUID.class))).thenReturn(mWriteDescriptorAction); when(mQueueContainer.getEnableNotificationActionQueue().dequeue(any(UUID.class))).thenReturn(mNotificationAction); when(mQueueContainer.getReadRemoteRssiActionQueue().dequeue(null)).thenReturn(mRssiAction); when(mDescriptor.getUuid()).thenReturn(UUID.randomUUID()); when(mDescriptor.getCharacteristic()).thenReturn(mCharacteristic); mExceptionCaptor = ArgumentCaptor.forClass(BletiaException.class); } @Test public void onConnectionStateChange_WhenStatusIsSuccessAndNewStateIsConnected() throws Exception { mCallbackHandler.onConnectionStateChange(mGattWrapper, BluetoothGatt.GATT_SUCCESS, BluetoothGatt.STATE_CONNECTED); verify(mCallback, times(1)).onConnect(mGattWrapper); } @Test public void onConnectionStateChange_WhenStatusIsSuccessAndNewStateIsDisconnected() throws Exception { mCallbackHandler.onConnectionStateChange(mGattWrapper, BluetoothGatt.GATT_SUCCESS, BluetoothGatt.STATE_DISCONNECTED); verify(mCallback, times(1)).onDisconnect(mGattWrapper); } @Test public void onConnectionStateChange_WhenStatusIsFailureAndNewStateIsConnected() throws Exception { mCallbackHandler.onConnectionStateChange(mGattWrapper, BluetoothGatt.GATT_FAILURE, BluetoothGatt.STATE_CONNECTED); verify(mCallback, times(1)).onError(mExceptionCaptor.capture()); BletiaException e = mExceptionCaptor.getValue(); assertThat(e.getTag()).isEqualTo("onConnectionStateChange"); } @Test public void onConnectionStateChange_WhenStatusIsFailureAndNewStateIsDisconnected() throws Exception { mCallbackHandler.onConnectionStateChange(mGattWrapper, BluetoothGatt.GATT_FAILURE, BluetoothGatt.STATE_DISCONNECTED); verify(mCallback, times(1)).onDisconnect(mGattWrapper); } @Test public void onServiceDiscovered_WhenStatusIsSuccess() throws Exception { mCallbackHandler.onServicesDiscovered(mGattWrapper, BluetoothGatt.GATT_SUCCESS); verify(mCallback, times(1)).onServiceDiscovered(BluetoothGatt.GATT_SUCCESS); } @Test public void onServiceDiscovered_WhenStatusIsFailure() throws Exception { mCallbackHandler.onServicesDiscovered(mGattWrapper, BluetoothGatt.GATT_FAILURE); verify(mCallback, times(1)).onServiceDiscovered(BluetoothGatt.GATT_FAILURE); } @Test public void onCharacteristicRead_WhenStatusIsSuccess() throws Exception { mCallbackHandler.onCharacteristicRead(mGattWrapper, mCharacteristic, BluetoothGatt.GATT_SUCCESS); verify(mCharacteristicDeferred, times(1)).resolve(mCharacteristic); } @Test public void onCharacteristicRead_WhenStatusIsFailure() throws Exception { mCallbackHandler.onCharacteristicRead(mGattWrapper, mCharacteristic, BluetoothGatt.GATT_FAILURE); verify(mCharacteristicDeferred, times(1)).reject(mExceptionCaptor.capture()); BletiaException e = mExceptionCaptor.getValue(); assertThat(e.getAction()).isEqualTo(mReadCharacteristicAction); assertThat(e.getType()).isEqualTo(BleErrorType.FAILURE); } @Test public void onCharacteristicWrite_WhenStatusIsSuccess() throws Exception { mCallbackHandler.onCharacteristicWrite(mGattWrapper, mCharacteristic, BluetoothGatt.GATT_SUCCESS); verify(mCharacteristicDeferred, times(1)).resolve(mCharacteristic); } @Test public void onCharacteristicWrite_WhenStatusIsFailure() throws Exception { mCallbackHandler.onCharacteristicWrite(mGattWrapper, mCharacteristic, BluetoothGatt.GATT_FAILURE); verify(mCharacteristicDeferred, times(1)).reject(mExceptionCaptor.capture()); BletiaException e = mExceptionCaptor.getValue(); assertThat(e.getAction()).isEqualTo(mWriteCharacteristicAction); assertThat(e.getType()).isEqualTo(BleErrorType.FAILURE); } @Test public void onCharacteristicChanged() throws Exception { mCallbackHandler.onCharacteristicChanged(mGattWrapper, mCharacteristic); verify(mCallback, times(1)).onCharacteristicChanged(mCharacteristic); } @Test public void onDescriptorRead_WhenStatusIsSuccess() throws Exception { mCallbackHandler.onDescriptorRead(mGattWrapper, mDescriptor, BluetoothGatt.GATT_SUCCESS); verify(mDescriptorDeferred, times(1)).resolve(mDescriptor); } @Test public void onDescriptorRead_WhenStatusIsFailure() throws Exception { mCallbackHandler.onDescriptorRead(mGattWrapper, mDescriptor, BluetoothGatt.GATT_FAILURE); verify(mDescriptorDeferred, times(1)).reject(mExceptionCaptor.capture()); BletiaException e = mExceptionCaptor.getValue(); assertThat(e.getAction()).isEqualTo(mReadDescriptorAction); assertThat(e.getType()).isEqualTo(BleErrorType.FAILURE); } @Test public void onDescriptorWrite_WhenStatusIsSuccess() throws Exception { mCallbackHandler.onDescriptorWrite(mGattWrapper, mDescriptor, BluetoothGatt.GATT_SUCCESS); verify(mDescriptorDeferred, times(1)).resolve(mDescriptor); } @Test public void onDescriptorWrite_WhenStatusIsFailure() throws Exception { mCallbackHandler.onDescriptorWrite(mGattWrapper, mDescriptor, BluetoothGatt.GATT_FAILURE); verify(mDescriptorDeferred, times(1)).reject(mExceptionCaptor.capture()); BletiaException e = mExceptionCaptor.getValue(); assertThat(e.getAction()).isEqualTo(mWriteDescriptorAction); assertThat(e.getType()).isEqualTo(BleErrorType.FAILURE); } @Test public void onDescriptorWrite_ThatIsNotificationDescriptor_WhenStatusIsSuccess() throws Exception { when(mDescriptor.getUuid()).thenReturn(Bletia.CLIENT_CHARCTERISTIC_CONFIG); when(mDescriptor.getValue()).thenReturn(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); mCallbackHandler.onDescriptorWrite(mGattWrapper, mDescriptor, BluetoothGatt.GATT_SUCCESS); verify(mCharacteristicDeferred, times(1)).resolve(mCharacteristic); } @Test public void onDescriptorWrite_ThatIsNotificationDescriptor_WhenStatusIsFailure() throws Exception { when(mDescriptor.getUuid()).thenReturn(Bletia.CLIENT_CHARCTERISTIC_CONFIG); when(mDescriptor.getValue()).thenReturn(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); mCallbackHandler.onDescriptorWrite(mGattWrapper, mDescriptor, BluetoothGatt.GATT_FAILURE); verify(mCharacteristicDeferred, times(1)).reject(mExceptionCaptor.capture()); BletiaException e = mExceptionCaptor.getValue(); assertThat(e.getAction()).isEqualTo(mNotificationAction); assertThat(e.getType()).isEqualTo(BleErrorType.FAILURE); } @Test public void onReadRemoteRssi_WhenStatusIsSuccess() throws Exception { mCallbackHandler.onReadRemoteRssi(mGattWrapper, 10, BluetoothGatt.GATT_SUCCESS); verify(mIntegerDeferred, times(1)).resolve(10); } @Test public void onReadRemoteRssi_WhenStatusIsFailure() throws Exception { mCallbackHandler.onReadRemoteRssi(mGattWrapper, 10, BluetoothGatt.GATT_FAILURE); verify(mIntegerDeferred, times(1)).reject(mExceptionCaptor.capture()); BletiaException e = mExceptionCaptor.getValue(); assertThat(e.getAction()).isEqualTo(mRssiAction); assertThat(e.getType()).isEqualTo(BleErrorType.FAILURE); } }
Fix test
bletia/src/androidTest/java/info/izumin/android/bletia/BluetoothGattCallbackHandlerTest.java
Fix test
<ide><path>letia/src/androidTest/java/info/izumin/android/bletia/BluetoothGattCallbackHandlerTest.java <ide> @Mock private EnableNotificationAction mNotificationAction; <ide> @Mock private ReadRemoteRssiAction mRssiAction; <ide> <del> @Mock private Deferred<BluetoothGattCharacteristic, BletiaException, Object> mCharacteristicDeferred; <del> @Mock private Deferred<BluetoothGattDescriptor, BletiaException, Object> mDescriptorDeferred; <del> @Mock private Deferred<Integer, BletiaException, Object> mIntegerDeferred; <add> @Mock private Deferred<BluetoothGattCharacteristic, BletiaException, Void> mCharacteristicDeferred; <add> @Mock private Deferred<BluetoothGattDescriptor, BletiaException, Void> mDescriptorDeferred; <add> @Mock private Deferred<Integer, BletiaException, Void> mIntegerDeferred; <ide> <ide> private ArgumentCaptor<BletiaException> mExceptionCaptor; <ide>
Java
apache-2.0
73aa0d17cb826f1e6d9a9529c0a55d061cf80f1e
0
sevenOneHero/foursquared.eclair,dhysf/foursquared,bancool/foursquared,nara-l/foursquared,idmouh/foursquared,srikanthguduru/foursquared,thtak/foursquared.eclair,tamzi/foursquared,edwinsnao/foursquared.eclair,aasaandinesh/foursquared.eclair,haithemhamzaoui/foursquared,savelees/foursquared,abdallahynajar/foursquared,ewugreensignal/foursquared,rahul18cool/foursquared.eclair,foobarprime/foursquared,itrobertson/foursquared,Bishwajet/foursquared.eclair,starspace/foursquared,mypapit/foursquared,smakeit/foursquared,prashantkumar0509/foursquared,karthikkumar12/foursquared,AnthonyCAS/foursquared.eclair,nehalok/foursquared,nasvil/foursquared,idmouh/foursquared,ACCTFORGH/foursquared,coersum01/foursquared,smallperson/foursquared.eclair,omondiy/foursquared,daya-shankar/foursquared,santoshmehta82/foursquared,lepinay/foursquared.eclair,NarikSmouke228/foursquared.eclair,smakeit/foursquared,lenkyun/foursquared,nasvil/foursquared.eclair,abedmaatalla/foursquared,lxz2014/foursquared,andrewjsauer/foursquared,ckarademir/foursquared,ayndev/foursquared.eclair,sbolisetty/foursquared,smallperson/foursquared,starspace/foursquared,fatihcelik/foursquared,fuzhou0099/foursquared.eclair,gtostock/foursquared.eclair,waasilzamri/foursquared,edwinsnao/foursquared,osiloke/foursquared.eclair,NarikSmouke228/foursquared,izBasit/foursquared,varunprathap/foursquared.eclair,psvijayk/foursquared,mayankz/foursquared,suripaleru/foursquared.eclair,malathicode/foursquared,codingz/foursquared.eclair,BinodAryal/foursquared.eclair,ewugreensignal/foursquared,dreamapps786/foursquared,lxz2014/foursquared,davideuler/foursquared,kiruthikak/foursquared,savelees/foursquared,lepinay/foursquared,karanVkgp/foursquared.eclair,stonyyi/foursquared,Archenemy-xiatian/foursquared.eclair,martadewi/foursquared.eclair,RameshBhupathi/foursquared.eclair,karanVkgp/foursquared,ayndev/foursquared,azai91/foursquared,tianyong2/foursquared.eclair,mayankz/foursquared,aasaandinesh/foursquared,tyzhaoqi/foursquared.eclair,sathiamour/foursquared.eclair,ksrpraneeth/foursquared,suripaleru/foursquared,kvnh/foursquared,ming0627/foursquared.eclair,codingz/foursquared,BinodAryal/foursquared,sonyraj/foursquared,weizp/foursquared,prashantkumar0509/foursquared.eclair,ckarademir/foursquared.eclair,lxz2014/foursquared.eclair,dreamapps786/foursquared,zhoujianhanyu/foursquared,azizjonm/foursquared,ekospinach/foursquared,bancool/foursquared.eclair,weizp/foursquared.eclair,bubao/foursquared,hardikamal/foursquared,murat8505/foursquared,waasilzamri/foursquared.eclair,karanVkgp/foursquared.eclair,appoll/foursquared,sathiamour/foursquared,nluetkemeyer/foursquared,sakethkaparthi/foursquared,lepinay/foursquared,thenewnewbie/foursquared,CoderJackyHuang/foursquared.eclair,itzmesayooj/foursquared,EphraimKigamba/foursquared.eclair,sandeip-yadav/foursquared,mikehowson/foursquared.eclair,idmouh/foursquared.eclair,solubrew/foursquared,votinhaooo/foursquared,Bishwajet/foursquared,harajuko/foursquared.eclair,nara-l/foursquared,artificiallight92/foursquared.eclair,karthikkumar12/foursquared,gokultaka/foursquared,omondiy/foursquared.eclair,akhilesh9205/foursquared.eclair,dreamapps786/foursquared.eclair,nasvil/foursquared,edwinsnao/foursquared,abedmaatalla/foursquared,EphraimKigamba/foursquared,idmouh/foursquared,sonyraj/foursquared.eclair,isaiasmercadom/foursquared,stonyyi/foursquared.eclair,omondiy/foursquared,itzmesayooj/foursquared.eclair,xuyunhong/foursquared,gtostock/foursquared,gtostock/foursquared,itzmesayooj/foursquared,votinhaooo/foursquared,martinx/martinxus-foursquared,itrobertson/foursquared,fatihcelik/foursquared,isaiasmercadom/foursquared,nluetkemeyer/foursquared,nehalok/foursquared.eclair,zhoujianhanyu/foursquared,navesdad/foursquared.eclair,abdallahynajar/foursquared,yusuf-shalahuddin/foursquared,dhysf/foursquared,rahulnagar8/foursquared,sonyraj/foursquared.eclair,gabtni/foursquared,isaiasmercadom/foursquared,harajuko/foursquared,summerzhao/foursquared,xytrams/foursquared,tyzhaoqi/foursquared,tianyong2/foursquared.eclair,tahainfocreator/foursquared.eclair,thenewnewbie/foursquared.eclair,davideuler/foursquared.eclair,rahulnagar8/foursquared,fatihcelik/foursquared.eclair,srikanthguduru/foursquared.eclair,coersum01/foursquared.eclair,haithemhamzaoui/foursquared.eclair,NarikSmouke228/foursquared,bubao/foursquared,zhoujianhanyu/foursquared.eclair,rihtak/foursquared,ckarademir/foursquared,thenewnewbie/foursquared.eclair,yusuf-shalahuddin/foursquared,psvijayk/foursquared,NarikSmouke228/foursquared,sonyraj/foursquared,varunprathap/foursquared,artificiallight92/foursquared,nluetkemeyer/foursquared.eclair,hardikamal/foursquared,aasaandinesh/foursquared.eclair,mansourifatimaezzahraa/foursquared.eclair,ewugreensignal/foursquared.eclair,omondiy/foursquared.eclair,savelees/foursquared.eclair,ragesh91/foursquared,Archenemy-xiatian/foursquared,ksrpraneeth/foursquared,azai91/foursquared.eclair,osiloke/foursquared,srikanthguduru/foursquared.eclair,thtak/foursquared.eclair,vsvankhede/foursquared,kitencx/foursquared,shrikantzarekar/foursquared.eclair,akhilesh9205/foursquared,wenkeyang/foursquared,osiloke/foursquared,xytrams/foursquared.eclair,abdallahynajar/foursquared,thtak/foursquared,ragesh91/foursquared,gokultaka/foursquared,tamzi/foursquared.eclair,ekospinach/foursquared.eclair,ekospinach/foursquared,rguindon/raymondeguindon-foursquared,yusuf-shalahuddin/foursquared.eclair,murat8505/foursquared.eclair,since2014/foursquared,coersum01/foursquared,sbagadi/foursquared,kiruthikak/foursquared,loganj/foursquared,izBasit/foursquared.eclair,BinodAryal/foursquared,BinodAryal/foursquared,prashantkumar0509/foursquared,santoshmehta82/foursquared,smallperson/foursquared,forevervhuo/foursquared.eclair,jamesmartins/foursquared.eclair,foobarprime/foursquared,nasvil/foursquared.eclair,paulodiogo/foursquared.eclair,tianyong2/foursquared,tianyong2/foursquared,MarginC/foursquared,bancool/foursquared,abou78180/foursquared,sbolisetty/foursquared.eclair,ragesh91/foursquared.eclair,MarginC/foursquared,martinx/martinxus-foursquared,kolawoletech/foursquared,nluetkemeyer/foursquared.eclair,psvijayk/foursquared.eclair,shivasrinath/foursquared,karthikkumar12/foursquared.eclair,ramaraokotu/foursquared.eclair,gtostock/foursquared.eclair,donka-s27/foursquared,waasilzamri/foursquared,NarikSmouke228/foursquared.eclair,lenkyun/foursquared,sibendu/foursquared,haithemhamzaoui/foursquared.eclair,rguindon/raymondeguindon-foursquared,shrikantzarekar/foursquared,cairenjie1985/foursquared,wenkeyang/foursquared.eclair,Archenemy-xiatian/foursquared,ckarademir/foursquared.eclair,haithemhamzaoui/foursquared,cairenjie1985/foursquared,votinhaooo/foursquared,Zebronaft/foursquared.eclair,Mutai/foursquared,jotish/foursquared.eclair,RahulRavindren/foursquared.eclair,rahul18cool/foursquared.eclair,nehalok/foursquared,navesdad/foursquared.eclair,sibendu/foursquared.eclair,AnthonyCAS/foursquared.eclair,nextzy/foursquared,murat8505/foursquared,EphraimKigamba/foursquared,RahulRavindren/foursquared,nara-l/foursquared,sandeip-yadav/foursquared.eclair,savelees/foursquared,tyzhaoqi/foursquared,martadewi/foursquared.eclair,psvijayk/foursquared,nextzy/foursquared,daya-shankar/foursquared,osiloke/foursquared,mikehowson/foursquared,dreamapps786/foursquared,azai91/foursquared.eclair,ramaraokotu/foursquared.eclair,thtak/foursquared,rahulnagar8/foursquared,nextzy/foursquared.eclair,bancool/foursquared.eclair,fatihcelik/foursquared,sandeip-yadav/foursquared.eclair,xzamirx/foursquared.eclair,izBasit/foursquared,jotish/foursquared,itzmesayooj/foursquared,lxz2014/foursquared.eclair,since2014/foursquared.eclair,navesdad/foursquared,ayndev/foursquared,votinhaooo/foursquared.eclair,coersum01/foursquared,ACCTFORGH/foursquared.eclair,hejie/foursquared.eclair,Archenemy-xiatian/foursquared.eclair,varunprathap/foursquared,edwinsnao/foursquared.eclair,ragesh91/foursquared,foobarprime/foursquared,tahainfocreator/foursquared,jamesmartins/foursquared,MarginC/foursquared,tahainfocreator/foursquared,abedmaatalla/foursquared.eclair,kolawoletech/foursquared.eclair,sovaa/foursquared,ming0627/foursquared,gtostock/foursquared,sathiamour/foursquared,dreamapps786/foursquared.eclair,smakeit/foursquared.eclair,donka-s27/foursquared.eclair,tahainfocreator/foursquared.eclair,donka-s27/foursquared,akhilesh9205/foursquared,ming0627/foursquared,sandeip-yadav/foursquared,kolawoletech/foursquared.eclair,632840804/foursquared.eclair,shivasrinath/foursquared,izBasit/foursquared.eclair,summerzhao/foursquared,daya-shankar/foursquared.eclair,EphraimKigamba/foursquared,suman4674/foursquared.eclair,wenkeyang/foursquared,aasaandinesh/foursquared,yusuf-shalahuddin/foursquared,malathicode/foursquared,shivasrinath/foursquared.eclair,thenewnewbie/foursquared,daya-shankar/foursquared,bubao/foursquared,jamesmartins/foursquared.eclair,CoderJackyHuang/foursquared.eclair,abou78180/foursquared.eclair,mansourifatimaezzahraa/foursquared,wenkeyang/foursquared.eclair,nextzy/foursquared,forevervhuo/foursquared.eclair,RameshBhupathi/foursquared,smakeit/foursquared.eclair,kitencx/foursquared,mikehowson/foursquared.eclair,azai91/foursquared,tamzi/foursquared,codingz/foursquared,pratikjk/foursquared,RameshBhupathi/foursquared,mansourifatimaezzahraa/foursquared.eclair,since2014/foursquared,artificiallight92/foursquared,summerzhao/foursquared.eclair,solubrew/foursquared,aasaandinesh/foursquared,Zebronaft/foursquared,thenewnewbie/foursquared,thtak/foursquared,lxz2014/foursquared,rihtak/foursquared,vsvankhede/foursquared,pratikjk/foursquared.eclair,manisoni28/foursquared,kvnh/foursquared.eclair,navesdad/foursquared,hardikamal/foursquared.eclair,sibendu/foursquared.eclair,varunprathap/foursquared,rihtak/foursquared.eclair,Mutai/foursquared,rguindon/raymondeguindon-foursquared,nextzy/foursquared.eclair,bancool/foursquared,rahul18cool/foursquared,vsvankhede/foursquared,sathiamour/foursquared.eclair,davideuler/foursquared.eclair,loganj/foursquared,malathicode/foursquared.eclair,appoll/foursquared,vsvankhede/foursquared.eclair,gokultaka/foursquared,pratikjk/foursquared,jiveshwar/foursquared.eclair,ACCTFORGH/foursquared,kitencx/foursquared,navesdad/foursquared,rahul18cool/foursquared,fuzhou0099/foursquared.eclair,sathiamour/foursquared,haithemhamzaoui/foursquared,zhmkof/foursquared.eclair,waasilzamri/foursquared.eclair,nasvil/foursquared,abdallahynajar/foursquared.eclair,rihtak/foursquared.eclair,Bishwajet/foursquared,lenkyun/foursquared,abou78180/foursquared,PriteshJain/foursquared,weizp/foursquared,tyzhaoqi/foursquared.eclair,PriteshJain/foursquared,rahulnagar8/foursquared.eclair,sevenOneHero/foursquared.eclair,nehalok/foursquared.eclair,ayndev/foursquared.eclair,martinx/martinxus-foursquared,murat8505/foursquared.eclair,hejie/foursquared,idmouh/foursquared.eclair,pratikjk/foursquared.eclair,davideuler/foursquared,jiveshwar/foursquared.eclair,zhoujianhanyu/foursquared.eclair,suman4674/foursquared,Mutai/foursquared,santoshmehta82/foursquared.eclair,nluetkemeyer/foursquared,bubao/foursquared.eclair,isaiasmercadom/foursquared.eclair,sakethkaparthi/foursquared,4DvAnCeBoY/foursquared.eclair,ksrpraneeth/foursquared,karanVkgp/foursquared,shrikantzarekar/foursquared.eclair,sbolisetty/foursquared,foobarprime/foursquared.eclair,pratikjk/foursquared,cairenjie1985/foursquared,starspace/foursquared.eclair,davideuler/foursquared,xuyunhong/foursquared.eclair,since2014/foursquared.eclair,malathicode/foursquared,solubrew/foursquared.eclair,starspace/foursquared,hunanlike/foursquared.eclair,kvnh/foursquared,ewugreensignal/foursquared,votinhaooo/foursquared.eclair,mansourifatimaezzahraa/foursquared,hardikamal/foursquared.eclair,foobarprime/foursquared.eclair,xytrams/foursquared,karthikkumar12/foursquared,omondiy/foursquared,donka-s27/foursquared,santoshmehta82/foursquared.eclair,sovaa/foursquared.eclair,srikanthguduru/foursquared,gabtni/foursquared,mansourifatimaezzahraa/foursquared,solubrew/foursquared.eclair,4DvAnCeBoY/foursquared,vsvankhede/foursquared.eclair,martadewi/foursquared,osiloke/foursquared.eclair,summerzhao/foursquared.eclair,Mutai/foursquared.eclair,stonyyi/foursquared,4DvAnCeBoY/foursquared.eclair,suripaleru/foursquared.eclair,RameshBhupathi/foursquared.eclair,Zebronaft/foursquared,manisoni28/foursquared,kiruthikak/foursquared.eclair,nehalok/foursquared,suman4674/foursquared,zhoujianhanyu/foursquared,donka-s27/foursquared.eclair,4DvAnCeBoY/foursquared,suman4674/foursquared,tamzi/foursquared.eclair,ming0627/foursquared,isaiasmercadom/foursquared.eclair,tamzi/foursquared,ragesh91/foursquared.eclair,Archenemy-xiatian/foursquared,hardikamal/foursquared,cairenjie1985/foursquared.eclair,coersum01/foursquared.eclair,EphraimKigamba/foursquared.eclair,weizp/foursquared.eclair,suripaleru/foursquared,abedmaatalla/foursquared,hejie/foursquared.eclair,abdallahynajar/foursquared.eclair,smakeit/foursquared,azizjonm/foursquared,mikehowson/foursquared,Zebronaft/foursquared,kiruthikak/foursquared.eclair,PriteshJain/foursquared.eclair,4DvAnCeBoY/foursquared,kolawoletech/foursquared,appoll/foursquared,kolawoletech/foursquared,sovaa/foursquared.eclair,sbagadi/foursquared.eclair,zhmkof/foursquared.eclair,xuyunhong/foursquared,andrewjsauer/foursquared,harajuko/foursquared,sevenOneHero/foursquared.eclair,xuyunhong/foursquared,shivasrinath/foursquared,gabtni/foursquared,malathicode/foursquared.eclair,suripaleru/foursquared,smallperson/foursquared,shrikantzarekar/foursquared,abedmaatalla/foursquared.eclair,sibendu/foursquared,murat8505/foursquared,mypapit/foursquared,itrobertson/foursquared,Bishwajet/foursquared.eclair,hunanlike/foursquared.eclair,ACCTFORGH/foursquared,abou78180/foursquared,xytrams/foursquared.eclair,gabtni/foursquared.eclair,nara-l/foursquared.eclair,Mutai/foursquared.eclair,jamesmartins/foursquared,hejie/foursquared,bubao/foursquared.eclair,waasilzamri/foursquared,santoshmehta82/foursquared,RahulRavindren/foursquared.eclair,sakethkaparthi/foursquared,RahulRavindren/foursquared,smallperson/foursquared.eclair,weizp/foursquared,BinodAryal/foursquared.eclair,yusuf-shalahuddin/foursquared.eclair,hunanlike/foursquared,ksrpraneeth/foursquared.eclair,savelees/foursquared.eclair,sbolisetty/foursquared,manisoni28/foursquared.eclair,RahulRavindren/foursquared,jotish/foursquared,ksrpraneeth/foursquared.eclair,Bishwajet/foursquared,fatihcelik/foursquared.eclair,sandeip-yadav/foursquared,lepinay/foursquared.eclair,dhysf/foursquared.eclair,harajuko/foursquared.eclair,hunanlike/foursquared,akhilesh9205/foursquared.eclair,xzamirx/foursquared.eclair,azai91/foursquared,kvnh/foursquared,Zebronaft/foursquared.eclair,ewugreensignal/foursquared.eclair,edwinsnao/foursquared,stonyyi/foursquared,ramaraokotu/foursquared,martadewi/foursquared,ayndev/foursquared,PriteshJain/foursquared.eclair,hejie/foursquared,solubrew/foursquared,mypapit/foursquared,shrikantzarekar/foursquared,sovaa/foursquared,ekospinach/foursquared,manisoni28/foursquared.eclair,manisoni28/foursquared,karanVkgp/foursquared,tyzhaoqi/foursquared,since2014/foursquared,ramaraokotu/foursquared,wenkeyang/foursquared,jotish/foursquared,azizjonm/foursquared,xuyunhong/foursquared.eclair,sibendu/foursquared,632840804/foursquared.eclair,ekospinach/foursquared.eclair,martadewi/foursquared,ramaraokotu/foursquared,rahul18cool/foursquared,andrewjsauer/foursquared,izBasit/foursquared,sbagadi/foursquared,karthikkumar12/foursquared.eclair,codingz/foursquared.eclair,lepinay/foursquared,mayankz/foursquared,artificiallight92/foursquared.eclair,starspace/foursquared.eclair,xytrams/foursquared,mikehowson/foursquared,kvnh/foursquared.eclair,dhysf/foursquared,artificiallight92/foursquared,codingz/foursquared,suman4674/foursquared.eclair,ckarademir/foursquared,sbolisetty/foursquared.eclair,ming0627/foursquared.eclair,gabtni/foursquared.eclair,srikanthguduru/foursquared,abou78180/foursquared.eclair,tianyong2/foursquared,akhilesh9205/foursquared,shivasrinath/foursquared.eclair,jamesmartins/foursquared,sbagadi/foursquared,prashantkumar0509/foursquared,hunanlike/foursquared,gokultaka/foursquared.eclair,kiruthikak/foursquared,varunprathap/foursquared.eclair,ACCTFORGH/foursquared.eclair,summerzhao/foursquared,rahulnagar8/foursquared.eclair,daya-shankar/foursquared.eclair,harajuko/foursquared,sovaa/foursquared,cairenjie1985/foursquared.eclair,PriteshJain/foursquared,psvijayk/foursquared.eclair,RameshBhupathi/foursquared,sonyraj/foursquared,gokultaka/foursquared.eclair,stonyyi/foursquared.eclair,nara-l/foursquared.eclair,dhysf/foursquared.eclair,paulodiogo/foursquared.eclair,sbagadi/foursquared.eclair,tahainfocreator/foursquared,rihtak/foursquared,prashantkumar0509/foursquared.eclair,jotish/foursquared.eclair,itzmesayooj/foursquared.eclair
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.googlecode.dumpcatcher.logging.Dumpcatcher; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsError; import com.joelapenna.foursquared.maps.BestLocationListener; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.location.Location; import android.location.LocationManager; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import java.lang.Thread.UncaughtExceptionHandler; import java.util.List; /** * @author Joe LaPenna ([email protected]) */ public class Foursquared extends Application { public static final String TAG = "Foursquared"; public static final boolean DEBUG = true; public static final boolean API_DEBUG = false; public static final boolean PARSER_DEBUG = false; public static final boolean USE_DUMPCATCHER = true; public static final boolean DUMPCATCHER_TEST = true; public static final int LAST_LOCATION_UPDATE_THRESHOLD = 1000 * 60 * 60; // Common menu items private static final int MENU_PREFERENCES = -1; private static final int MENU_GROUP_SYSTEM = 20; private Dumpcatcher mDumpcatcher; private LocationListener mLocationListener = new LocationListener(); private SharedPreferences mPrefs; private OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener; private static Foursquare sFoursquare = new Foursquare(); public void onCreate() { mPrefs = PreferenceManager.getDefaultSharedPreferences(this); if (USE_DUMPCATCHER) setupDumpcatcher(); // Set the oauth credentials. sFoursquare.setOAuthConsumerCredentials( // getResources().getString(R.string.oauth_consumer_key), // getResources().getString(R.string.oauth_consumer_secret)); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mOnSharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Preferences.PREFERENCE_PHONE) || key.equals(Preferences.PREFERENCE_PASSWORD)) { Log.d(TAG, key + " preference was changed"); try { loadCredentials(); } catch (FoursquareCredentialsError e) { // pass } } } }; mPrefs.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener); try { loadCredentials(); } catch (FoursquareCredentialsError e) { // We're not doing anything because hopefully our related activities // will handle the failure. This is simply convenience. } } public Location getLastKnownLocation() { return mLocationListener.getLastKnownLocation(); } public LocationListener getLocationListener() { primeLocationListener(); return mLocationListener; } private void setupDumpcatcher() { String client = Preferences.createUniqueId(mPrefs); if (DUMPCATCHER_TEST) { if (DEBUG) Log.d(TAG, "Loading Dumpcatcher TEST"); mDumpcatcher = new Dumpcatcher( // getResources().getString(R.string.test_dumpcatcher_product_key), // getResources().getString(R.string.test_dumpcatcher_secret), // getResources().getString(R.string.test_dumpcatcher_url), client, 5); } else { if (DEBUG) Log.d(TAG, "Loading Dumpcatcher Live"); mDumpcatcher = new Dumpcatcher( // getResources().getString(R.string.dumpcatcher_product_key), // getResources().getString(R.string.dumpcatcher_secret), // getResources().getString(R.string.dumpcatcher_url), client, 5); } UncaughtExceptionHandler handler = mDumpcatcher.createUncaughtExceptionHandler(); // This can hang the app starving android of its ability to properly kill threads. // Thread.setDefaultUncaughtExceptionHandler(handler); Thread.currentThread().setUncaughtExceptionHandler(handler); // TODO(jlapenna): Usage related, async sendCrashes should be pooled together or something. // This is nasty. sendUsage("Started"); } private void loadCredentials() throws FoursquareCredentialsError { if (DEBUG) Log.d(TAG, "loadCredentials()"); String phoneNumber = mPrefs.getString(Preferences.PREFERENCE_PHONE, null); String password = mPrefs.getString(Preferences.PREFERENCE_PASSWORD, null); String oauthToken = mPrefs.getString(Preferences.PREFERENCE_OAUTH_TOKEN, null); String oauthTokenSecret = mPrefs.getString(Preferences.PREFERENCE_OAUTH_TOKEN_SECRET, null); if (TextUtils.isEmpty(phoneNumber) || TextUtils.isEmpty(password) || TextUtils.isEmpty(oauthToken) || TextUtils.isEmpty(oauthTokenSecret)) { throw new FoursquareCredentialsError("Phone number or password not set in preferences."); } sFoursquare.setCredentials(phoneNumber, password); sFoursquare.setOAuthToken(oauthToken, oauthTokenSecret); } private void primeLocationListener() { LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location location = null; List<String> providers = manager.getProviders(true); int providersCount = providers.size(); for (int i = 0; i < providersCount; i++) { location = manager.getLastKnownLocation(providers.get(i)); mLocationListener.getBetterLocation(location); } } private void sendUsage(final String usage) { Thread thread = new Thread(new Runnable() { @Override public void run() { try { NameValuePair[] parameters = { new BasicNameValuePair("tag", "usage"), new BasicNameValuePair("short", usage), }; HttpResponse response = mDumpcatcher.sendCrash(parameters); response.getEntity().consumeContent(); } catch (Exception e) { // no biggie... } } }); thread.start(); } public static void addPreferencesToMenu(Context context, Menu menu) { Intent intent = new Intent(context, PreferenceActivity.class); menu.add(MENU_GROUP_SYSTEM, MENU_PREFERENCES, Menu.NONE, R.string.preferences_label) // .setIcon(android.R.drawable.ic_menu_preferences).setIntent(intent); } public static Foursquare getFoursquare() { return sFoursquare; } /** * Used for the accuracy algorithm getBetterLocation. */ public static class LocationListener extends BestLocationListener { @Override public void onLocationChanged(Location location) { if (DEBUG) Log.d(TAG, "onLocationChanged: " + location); getBetterLocation(location); } } }
src/com/joelapenna/foursquared/Foursquared.java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.googlecode.dumpcatcher.logging.Dumpcatcher; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsError; import com.joelapenna.foursquared.maps.BestLocationListener; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.location.Location; import android.location.LocationManager; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import java.lang.Thread.UncaughtExceptionHandler; import java.util.List; /** * @author Joe LaPenna ([email protected]) */ public class Foursquared extends Application { public static final String TAG = "Foursquared"; public static final boolean DEBUG = true; public static final boolean API_DEBUG = false; public static final boolean PARSER_DEBUG = false; public static final boolean USE_DUMPCATCHER = true; public static final boolean DUMPCATCHER_TEST = true; public static final int LAST_LOCATION_UPDATE_THRESHOLD = 1000 * 60 * 60; // Common menu items private static final int MENU_PREFERENCES = -1; private static final int MENU_GROUP_SYSTEM = 20; private Dumpcatcher mDumpcatcher; private LocationListener mLocationListener = new LocationListener(); private SharedPreferences mPrefs; private OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener; private static Foursquare sFoursquare = new Foursquare(); public void onCreate() { mPrefs = PreferenceManager.getDefaultSharedPreferences(this); if (USE_DUMPCATCHER) setupDumpcatcher(); // Set the oauth credentials. sFoursquare.setOAuthConsumerCredentials( // getResources().getString(R.string.oauth_consumer_key), // getResources().getString(R.string.oauth_consumer_secret)); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mOnSharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Preferences.PREFERENCE_PHONE) || key.equals(Preferences.PREFERENCE_PASSWORD)) { Log.d(TAG, key + " preference was changed"); try { loadCredentials(); } catch (FoursquareCredentialsError e) { // pass } } } }; mPrefs.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener); try { loadCredentials(); } catch (FoursquareCredentialsError e) { // We're not doing anything because hopefully our related activities // will handle the failure. This is simply convenience. } } public Location getLastKnownLocation() { return mLocationListener.getLastKnownLocation(); } public LocationListener getLocationListener() { primeLocationListener(); return mLocationListener; } private void setupDumpcatcher() { String client = Preferences.createUniqueId(mPrefs); if (DUMPCATCHER_TEST) { if (DEBUG) Log.d(TAG, "Loading Dumpcatcher TEST"); mDumpcatcher = new Dumpcatcher( // getResources().getString(R.string.test_dumpcatcher_product_key), // getResources().getString(R.string.test_dumpcatcher_secret), // getResources().getString(R.string.test_dumpcatcher_url), client, 5); } else { if (DEBUG) Log.d(TAG, "Loading Dumpcatcher Live"); mDumpcatcher = new Dumpcatcher( // getResources().getString(R.string.dumpcatcher_product_key), // getResources().getString(R.string.dumpcatcher_secret), // getResources().getString(R.string.dumpcatcher_url), client, 5); } // TODO(jlapenna): Make this work! // This doesn't work. Don't pretend it does. // UncaughtExceptionHandler handler = mDumpcatcher.createUncaughtExceptionHandler(); // Thread.setDefaultUncaughtExceptionHandler(handler); // Thread.currentThread().setUncaughtExceptionHandler(handler); // TODO(jlapenna): Usage related, async sendCrashes should be pooled together or something. // This is nasty. sendUsage("Started"); } private void loadCredentials() throws FoursquareCredentialsError { if (DEBUG) Log.d(TAG, "loadCredentials()"); String phoneNumber = mPrefs.getString(Preferences.PREFERENCE_PHONE, null); String password = mPrefs.getString(Preferences.PREFERENCE_PASSWORD, null); String oauthToken = mPrefs.getString(Preferences.PREFERENCE_OAUTH_TOKEN, null); String oauthTokenSecret = mPrefs.getString(Preferences.PREFERENCE_OAUTH_TOKEN_SECRET, null); if (TextUtils.isEmpty(phoneNumber) || TextUtils.isEmpty(password) || TextUtils.isEmpty(oauthToken) || TextUtils.isEmpty(oauthTokenSecret)) { throw new FoursquareCredentialsError("Phone number or password not set in preferences."); } sFoursquare.setCredentials(phoneNumber, password); sFoursquare.setOAuthToken(oauthToken, oauthTokenSecret); } private void primeLocationListener() { LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location location = null; List<String> providers = manager.getProviders(true); int providersCount = providers.size(); for (int i = 0; i < providersCount; i++) { location = manager.getLastKnownLocation(providers.get(i)); mLocationListener.getBetterLocation(location); } } private void sendUsage(final String usage) { Thread thread = new Thread(new Runnable() { @Override public void run() { try { NameValuePair[] parameters = { new BasicNameValuePair("tag", "usage"), new BasicNameValuePair("short", usage), }; HttpResponse response = mDumpcatcher.sendCrash(parameters); response.getEntity().consumeContent(); } catch (Exception e) { // no biggie... } } }); thread.start(); } public static void addPreferencesToMenu(Context context, Menu menu) { Intent intent = new Intent(context, PreferenceActivity.class); menu.add(MENU_GROUP_SYSTEM, MENU_PREFERENCES, Menu.NONE, R.string.preferences_label) // .setIcon(android.R.drawable.ic_menu_preferences).setIntent(intent); } public static Foursquare getFoursquare() { return sFoursquare; } /** * Used for the accuracy algorithm getBetterLocation. */ public static class LocationListener extends BestLocationListener { @Override public void onLocationChanged(Location location) { if (DEBUG) Log.d(TAG, "onLocationChanged: " + location); getBetterLocation(location); } } }
Don't set the default uncaught exception handler. committer: Joe LaPenna <[email protected]>
src/com/joelapenna/foursquared/Foursquared.java
Don't set the default uncaught exception handler.
<ide><path>rc/com/joelapenna/foursquared/Foursquared.java <ide> getResources().getString(R.string.dumpcatcher_url), client, 5); <ide> } <ide> <del> // TODO(jlapenna): Make this work! <del> // This doesn't work. Don't pretend it does. <del> // UncaughtExceptionHandler handler = mDumpcatcher.createUncaughtExceptionHandler(); <add> UncaughtExceptionHandler handler = mDumpcatcher.createUncaughtExceptionHandler(); <add> // This can hang the app starving android of its ability to properly kill threads. <ide> // Thread.setDefaultUncaughtExceptionHandler(handler); <del> // Thread.currentThread().setUncaughtExceptionHandler(handler); <add> Thread.currentThread().setUncaughtExceptionHandler(handler); <ide> <ide> // TODO(jlapenna): Usage related, async sendCrashes should be pooled together or something. <ide> // This is nasty.
Java
bsd-2-clause
0ade2ea848e2abca29e97d54b72b858b9dfa0018
0
jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu
/* * Copyright (c) 2015, Absolute Performance, Inc. http://www.absolute-performance.com * Copyright (c) 2016, Jack J. Woehr [email protected] * SoftWoehr LLC PO Box 51, Golden CO 80402-0051 http://www.softwoehr.com * 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. * * 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 HOLDER 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 ublu.command; import ublu.db.ResultSetClosure; import ublu.db.ResultSetHelper; import ublu.util.ArgArray; import ublu.util.DataSink; import ublu.util.Generics; import ublu.util.Tuple; import com.ibm.as400.access.AS400SecurityException; import com.ibm.as400.access.ErrorCompletingRequestException; import com.ibm.as400.access.ObjectDoesNotExistException; import com.ibm.as400.access.RequestNotSupportedException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import org.json.JSONException; import ublu.db.Db; /** * Performs result set to result set operations * * @author jwoehr */ public class CmdRs extends Command { { setNameAndDescription("rs", "/0 [--,-rs ~@rs] [-to datasink] [-from datasink] [[-autocommit 0|1] | [-bytes ~@{fieldindex}] | [-close{|db|st} tuplename] | [-commit ~@resultSet] | [-fetchsize numrows] | -insert | [-json ~@db ~@{tablename}] | [-split split_specification] | [-toascii numindices index index ..] | [-metadata]] -from tuplename -to @tuplename : tuples assumed to hold result sets, performs the indicated operation (such as commit, set autocommit mode, set&get fetchsize) out of the 'from' result set into the 'to' result set (splitting if -split is chosen instead of -insert) or closes the result set represented by the ~@tuplename argument to -close (and the statement if -closest and also disconnects db instance if -closedb)"); } /** * Arity-0 ctor */ public CmdRs() { } private int splitTarget; private int[] splitWidths; /** * Return one's-based index of column to split for SPLIT function. * * @return one's-based index of column to split */ protected int getSplitTarget() { return splitTarget; } /** * Set one's-based index of column to split for SPLIT function. * * @param splitTarget one's-based index of column to split */ protected void setSplitTarget(int splitTarget) { this.splitTarget = splitTarget; } /** * Return array of widths into which to split column. * * @return array of widths into which to split column. */ protected int[] getSplitWidths() { return splitWidths; } /** * Set array of widths into which to split column. * * @param splitWidths array of widths into which to split column. */ protected void setSplitWidths(int[] splitWidths) { this.splitWidths = splitWidths; } /** * The functions this command knows */ protected enum FUNCTIONS { /** * Do nothing. */ NULL, /** * Get raw bytes from field */ BYTES, /** * Set the autocommit mode for result sets */ AUTOCOMMIT, /** * Set fetchsize for result sets and/or report the fetchsize (only * report if size &lt;= 0). */ FETCHSIZE, /** * Commit a result set */ COMMIT, /** * Insert the source result set into the dest result set. */ INSERT, /** * Insert the source result set into the dest result set splitting one * (char/byte) column into multiple columns. */ SPLIT, /** * Close a result set, deleting the tuple. */ CLOSE, /** * Close a result set and the statement that originated it, deleting the * tuple. */ CLOSEST, /** * Close a result set, the statement that originated it, and disconnect * the underlying database instance, deleting the tuple. */ CLOSEDB, /** * Dump the result set as JSON */ JSON, /** * Get the result set metadata */ METADATA } /** * The function this pass through the command is going to perform */ protected FUNCTIONS function; /** * Get the function this pass through the command is going to perform. * * @return the function this pass through the command is going to perform */ public FUNCTIONS getFunction() { return function; } /** * Set the function this pass through the command is going to perform. * * @param function the function this pass through the command is going to * perform */ public final void setFunction(FUNCTIONS function) { this.function = function; } /** * Operate on result sets * * @param argArray the args to the interpreter * @return what's left of the args */ public ArgArray rs(ArgArray argArray) { ResultSetHelper.CONVERSION conversion = null; Generics.IndexList charConversionIndexList = null; int rowsToFetch = 0; String commitTupleName = ""; boolean autoCommitValue = true; Db myDb = null; ResultSetClosure myRs = null; String tableName = null; Integer fieldindex = null; while (argArray.hasDashCommand()) { String dashCommand = argArray.parseDashCommand(); switch (dashCommand) { case "-to": setDataDestfromArgArray(argArray); break; case "-from": setDataSrcfromArgArray(argArray); break; case "--": case "-rs": myRs = argArray.nextTupleOrPop().value(ResultSetClosure.class); break; case "-autocommit": setFunction(FUNCTIONS.AUTOCOMMIT); autoCommitValue = argArray.nextInt() == 0; break; case "bytes": setFunction(FUNCTIONS.BYTES); fieldindex = argArray.nextIntMaybeQuotationTuplePopString(); break; case "-close": myRs = argArray.nextTupleOrPop().value(ResultSetClosure.class); setFunction(FUNCTIONS.CLOSE); break; case "-closedb": myRs = argArray.nextTupleOrPop().value(ResultSetClosure.class); setFunction(FUNCTIONS.CLOSEDB); break; case "-closest": myRs = argArray.nextTupleOrPop().value(ResultSetClosure.class); setFunction(FUNCTIONS.CLOSEST); break; case "-commit": setFunction(FUNCTIONS.COMMIT); commitTupleName = argArray.next(); break; case "-fetchsize": setFunction(FUNCTIONS.FETCHSIZE); rowsToFetch = argArray.nextInt(); break; case "-insert": setFunction(FUNCTIONS.INSERT); break; case "-json": setFunction(FUNCTIONS.JSON); myDb = argArray.nextTupleOrPop().value(Db.class); tableName = argArray.nextMaybeQuotationTuplePopString(); break; case "-metadata": setFunction(FUNCTIONS.METADATA); break; case "-split": setFunction(FUNCTIONS.SPLIT); setSplitTarget(argArray.nextInt()); setSplitWidths(argArray.parseIntArray()); break; case "-toascii": conversion = ResultSetHelper.CONVERSION.TOASCII; charConversionIndexList = new Generics.IndexList(); charConversionIndexList.addAll(argArray.parseIntArray()); break; default: unknownDashCommand(dashCommand); } } if (havingUnknownDashCommand()) { setCommandResult(COMMANDRESULT.FAILURE); } else { ResultSetClosure srcResultSetClosure; ResultSetClosure destResultSetClosure; switch (getFunction()) { case AUTOCOMMIT: try { setAutoCommit(getDataSrc(), autoCommitValue); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Exception setting autocommit mode in CmdRs for source result set", ex); setCommandResult(COMMANDRESULT.FAILURE); } try { setAutoCommit(getDataDest(), autoCommitValue); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Exception setting autocommit mode in CmdRs for destination result set", ex); setCommandResult(COMMANDRESULT.FAILURE); } break; case BYTES: if (myRs == null) { getLogger().log(Level.SEVERE, "Tuple not found for -bytes in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } else { try { put(myRs.getResultSet().getBytes(fieldindex)); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Could not get or put bytes result set for column index " + fieldindex + " in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case CLOSE: if (myRs == null) { getLogger().log(Level.SEVERE, "Tuple not found for -close in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } else { try { myRs.closeRS(); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Could not close result set from tuple in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case CLOSEDB: if (myRs == null) { getLogger().log(Level.SEVERE, "Tuple not found for -closedb in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } else { try { myRs.close(); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Could not close result set from tuple in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case CLOSEST: if (myRs == null) { getLogger().log(Level.SEVERE, "Tuple not found for -closest in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } else { try { myRs.closeRS().closeStatement(); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Could not close result set from tuple in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case COMMIT: try { commit(commitTupleName); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Error committing result set from tuple " + commitTupleName, ex); setCommandResult(COMMANDRESULT.FAILURE); } break; case FETCHSIZE: try { setFetchSize(getDataSrc(), rowsToFetch); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Exception setting autocommit mode in CmdRs for source result set", ex); setCommandResult(COMMANDRESULT.FAILURE); } try { setFetchSize(getDataDest(), rowsToFetch); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Exception setting autocommit mode in CmdRs for destination result set", ex); setCommandResult(COMMANDRESULT.FAILURE); } break; case INSERT: if (getDataDest() == null | getDataSrc() == null) { getLogger().log(Level.SEVERE, "Missing data source or data dest in rs command"); setCommandResult(COMMANDRESULT.FAILURE); } else if (!getDataDest().getType().equals(DataSink.SINKTYPE.TUPLE) || !getDataSrc().getType().equals(DataSink.SINKTYPE.TUPLE)) { getLogger().log(Level.SEVERE, "Source dest or data dest in rs command not a tuple"); setCommandResult(COMMANDRESULT.FAILURE); } else { try { srcResultSetClosure = ResultSetClosure.class.cast(getTuple(getDataSrc().getName()).getValue()); destResultSetClosure = ResultSetClosure.class.cast(getTuple(getDataDest().getName()).getValue()); if (srcResultSetClosure == null || destResultSetClosure == null) { getLogger().log(Level.SEVERE, "Null instead of result set for one or both of source and/or destination in rs"); setCommandResult(COMMANDRESULT.FAILURE); } else { ResultSet srcResultSet = srcResultSetClosure.getResultSet(); ResultSet destResultSet = destResultSetClosure.getResultSet(); ResultSetHelper rsh = new ResultSetHelper(srcResultSet, destResultSet, charConversionIndexList, conversion); rsh.updateInsertingTable(); } } catch (SQLException ex) { getLogger().log(Level.SEVERE, "SQL exception in command rs", ex); setCommandResult(COMMANDRESULT.FAILURE); } catch (ClassCastException ex) { getLogger().log(Level.SEVERE, "Either the source or destination in command rs was not a result set", ex); setCommandResult(COMMANDRESULT.FAILURE); } catch (UnsupportedEncodingException ex) { getLogger().log(Level.SEVERE, "Character set conversion failed", ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case JSON: if (myRs != null && myDb != null && tableName != null) { try { put(myRs.toJSON(myDb, tableName)); } catch (JSONException | SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Exception converting or putting JSON in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case SPLIT: if (getDataDest() == null | getDataSrc() == null) { getLogger().log(Level.SEVERE, "Missing data source or data dest in rs command"); setCommandResult(COMMANDRESULT.FAILURE); break; } else if (!getDataDest().getType().equals(DataSink.SINKTYPE.TUPLE) || !getDataSrc().getType().equals(DataSink.SINKTYPE.TUPLE)) { getLogger().log(Level.SEVERE, "Source dest or data dest in rs command not a tuple"); setCommandResult(COMMANDRESULT.FAILURE); } else { try { srcResultSetClosure = ResultSetClosure.class.cast(getTuple(getDataSrc().getName()).getValue()); destResultSetClosure = ResultSetClosure.class.cast(getTuple(getDataDest().getName()).getValue()); if (srcResultSetClosure == null || destResultSetClosure == null) { getLogger().log(Level.SEVERE, "Null instead of result set for one or both of source and/or destination in rs"); setCommandResult(COMMANDRESULT.FAILURE); } else { ResultSet srcResultSet = srcResultSetClosure.getResultSet(); ResultSet destResultSet = destResultSetClosure.getResultSet(); ResultSetHelper rsh = new ResultSetHelper(srcResultSet, destResultSet, charConversionIndexList, conversion); rsh.updateSplittingInsertingTable(getSplitTarget(), getSplitWidths()); } } catch (SQLException ex) { getLogger().log(Level.SEVERE, "SQL exception in command rs", ex); setCommandResult(COMMANDRESULT.FAILURE); } catch (ClassCastException ex) { getLogger().log(Level.SEVERE, "Either the source or destination in command rs was not a result set", ex); setCommandResult(COMMANDRESULT.FAILURE); } catch (UnsupportedEncodingException ex) { getLogger().log(Level.SEVERE, "Charcter set conversion failed", ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case METADATA: if (getDataSrc() == null) { getLogger().log(Level.SEVERE, "Missing data source in rs -metadata command"); setCommandResult(COMMANDRESULT.FAILURE); break; } try { srcResultSetClosure = ResultSetClosure.class.cast(getTuple(getDataSrc().getName()).getValue()); put(srcResultSetClosure.getResultSet().getMetaData()); } catch (SQLException | RequestNotSupportedException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "Exception getting or putting result set metadata", ex); setCommandResult(COMMANDRESULT.FAILURE); } catch (ClassCastException ex) { getLogger().log(Level.SEVERE, "Source command rs -metadata was not a result set", ex); setCommandResult(COMMANDRESULT.FAILURE); } break; } } return argArray; } private void setAutoCommit(DataSink ds, boolean ac) throws SQLException { Tuple autoCommitTuple; Object hopefullyAResultSetClosure; if (ds.getType() == DataSink.SINKTYPE.TUPLE) { autoCommitTuple = getTuple(getDataSrc().getName()); if (autoCommitTuple == null) { getLogger().log(Level.WARNING, "Tuple {0} not found", getDataSrc().getName()); } else { hopefullyAResultSetClosure = autoCommitTuple.getValue(); if (hopefullyAResultSetClosure instanceof ResultSetClosure) { ResultSetClosure.class .cast(hopefullyAResultSetClosure).setAutoCommit(ac); } else { getLogger().log(Level.WARNING, "Source tuple {0} is not a ResultSetClosure", autoCommitTuple.getKey()); } } } else { getLogger().log(Level.WARNING, "DataSink {0} is not a Tuple", ds.getName()); } } private void commit(String commitTupleName) throws SQLException { Tuple commitTuple; Object hopefullyAResultSetClosure; commitTuple = getTuple(commitTupleName); if (commitTuple == null) { getLogger().log(Level.WARNING, "Tuple {0} not found", commitTupleName); } else { hopefullyAResultSetClosure = commitTuple.getValue(); if (hopefullyAResultSetClosure instanceof ResultSetClosure) { ResultSetClosure.class .cast(hopefullyAResultSetClosure).commit(); } else { getLogger().log(Level.WARNING, "Source tuple {0} is not a ResultSetClosure", commitTuple.getKey()); } } } private void setFetchSize(DataSink ds, int fetchSize) throws SQLException { Tuple fetchSizeTuple; Object hopefullyAResultSetClosure; if (ds.getType() == DataSink.SINKTYPE.TUPLE) { fetchSizeTuple = getTuple(getDataSrc().getName()); if (fetchSizeTuple == null) { getLogger().log(Level.WARNING, "Tuple {0} not found", getDataSrc().getName()); } else { hopefullyAResultSetClosure = fetchSizeTuple.getValue(); if (hopefullyAResultSetClosure instanceof ResultSetClosure) { ResultSetClosure rsc = ResultSetClosure.class .cast(hopefullyAResultSetClosure); if (fetchSize > 0) { rsc.setFetchSize(fetchSize); } getLogger().log(Level.INFO, "Fetch size for result set in tuple {0} is {1}", new Object[]{fetchSizeTuple.getKey(), rsc.getResultSet().getFetchSize()}); } else { getLogger().log(Level.WARNING, "Source tuple {0} is not a ResultSetClosure", fetchSizeTuple.getKey()); } } } else { getLogger().log(Level.WARNING, "DataSink {0} is not a Tuple", ds.getName()); } } @Override public void reinit() { super.reinit(); setFunction(FUNCTIONS.NULL); setSplitTarget(0); // not strictly necessary since -split instances setSplitWidths(null); // not strictly necessary since -split instances } @Override public ArgArray cmd(ArgArray args) { reinit(); return rs(args); } @Override public COMMANDRESULT getResult() { return getCommandResult(); } }
src/ublu/command/CmdRs.java
/* * Copyright (c) 2015, Absolute Performance, Inc. http://www.absolute-performance.com * Copyright (c) 2016, Jack J. Woehr [email protected] * SoftWoehr LLC PO Box 51, Golden CO 80402-0051 http://www.softwoehr.com * 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. * * 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 HOLDER 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 ublu.command; import ublu.db.ResultSetClosure; import ublu.db.ResultSetHelper; import ublu.util.ArgArray; import ublu.util.DataSink; import ublu.util.Generics; import ublu.util.Tuple; import com.ibm.as400.access.AS400SecurityException; import com.ibm.as400.access.ErrorCompletingRequestException; import com.ibm.as400.access.ObjectDoesNotExistException; import com.ibm.as400.access.RequestNotSupportedException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import org.json.JSONException; import ublu.db.Db; /** * Performs result set to result set operations * * @author jwoehr */ public class CmdRs extends Command { { setNameAndDescription("rs", "/0 [--,-rs ~@rs] [-to datasink] [-from datasink] [[-autocommit 0|1] | [-bytes ~@{fieldindex}] | [-close{|db|st} tuplename] | [-commit ~@resultSet] | [-fetchsize numrows] | -insert | [-json ~@db ~@{tablename}] | [-split split_specification] | [-toascii numindices index index ..] | [-metadata]] -from tuplename -to @tuplename : tuples assumed to hold result sets, performs the indicated operation (such as commit, set autocommit mode, set&get fetchsize) out of the 'from' result set into the 'to' result set (splitting if -split is chosen instead of -insert) or closes the result set represented by the ~@tuplename argument to -close (and the statement if -closest and also disconnects db instance if -closedb)"); } /** * Arity-0 ctor */ public CmdRs() { } private int splitTarget; private int[] splitWidths; /** * Return one's-based index of column to split for SPLIT function. * * @return one's-based index of column to split */ protected int getSplitTarget() { return splitTarget; } /** * Set one's-based index of column to split for SPLIT function. * * @param splitTarget one's-based index of column to split */ protected void setSplitTarget(int splitTarget) { this.splitTarget = splitTarget; } /** * Return array of widths into which to split column. * * @return array of widths into which to split column. */ protected int[] getSplitWidths() { return splitWidths; } /** * Set array of widths into which to split column. * * @param splitWidths array of widths into which to split column. */ protected void setSplitWidths(int[] splitWidths) { this.splitWidths = splitWidths; } /** * The functions this command knows */ protected enum FUNCTIONS { /** * Do nothing. */ NULL, /** * Get raw bytes from field */ BYTES, /** * Set the autocommit mode for result sets */ AUTOCOMMIT, /** * Set fetchsize for result sets and/or report the fetchsize (only * report if size &lt;= 0). */ FETCHSIZE, /** * Commit a result set */ COMMIT, /** * Insert the source result set into the dest result set. */ INSERT, /** * Insert the source result set into the dest result set splitting one * (char/byte) column into multiple columns. */ SPLIT, /** * Close a result set, deleting the tuple. */ CLOSE, /** * Close a result set and the statement that originated it, deleting the * tuple. */ CLOSEST, /** * Close a result set, the statement that originated it, and disconnect * the underlying database instance, deleting the tuple. */ CLOSEDB, /** * Dump the result set as JSON */ JSON, /** * Get the result set metadata */ METADATA } /** * The function this pass through the command is going to perform */ protected FUNCTIONS function; /** * Get the function this pass through the command is going to perform. * * @return the function this pass through the command is going to perform */ public FUNCTIONS getFunction() { return function; } /** * Set the function this pass through the command is going to perform. * * @param function the function this pass through the command is going to * perform */ public final void setFunction(FUNCTIONS function) { this.function = function; } /** * Operate on result sets * * @param argArray the args to the interpreter * @return what's left of the args */ public ArgArray rs(ArgArray argArray) { ResultSetHelper.CONVERSION conversion = null; Generics.IndexList charConversionIndexList = null; int rowsToFetch = 0; String commitTupleName = ""; boolean autoCommitValue = true; Db myDb = null; ResultSetClosure myRs = null; String tableName = null; while (argArray.hasDashCommand()) { String dashCommand = argArray.parseDashCommand(); switch (dashCommand) { case "-to": setDataDestfromArgArray(argArray); break; case "-from": setDataSrcfromArgArray(argArray); break; case "--": case "-rs": myRs = argArray.nextTupleOrPop().value(ResultSetClosure.class); break; case "-autocommit": setFunction(FUNCTIONS.AUTOCOMMIT); autoCommitValue = argArray.nextInt() == 0; break; case "-close": myRs = argArray.nextTupleOrPop().value(ResultSetClosure.class); setFunction(FUNCTIONS.CLOSE); break; case "-closedb": myRs = argArray.nextTupleOrPop().value(ResultSetClosure.class); setFunction(FUNCTIONS.CLOSEDB); break; case "-closest": myRs = argArray.nextTupleOrPop().value(ResultSetClosure.class); setFunction(FUNCTIONS.CLOSEST); break; case "-commit": setFunction(FUNCTIONS.COMMIT); commitTupleName = argArray.next(); break; case "-fetchsize": setFunction(FUNCTIONS.FETCHSIZE); rowsToFetch = argArray.nextInt(); break; case "-insert": setFunction(FUNCTIONS.INSERT); break; case "-json": setFunction(FUNCTIONS.JSON); myDb = argArray.nextTupleOrPop().value(Db.class); tableName = argArray.nextMaybeQuotationTuplePopString(); break; case "-metadata": setFunction(FUNCTIONS.METADATA); break; case "-split": setFunction(FUNCTIONS.SPLIT); setSplitTarget(argArray.nextInt()); setSplitWidths(argArray.parseIntArray()); break; case "-toascii": conversion = ResultSetHelper.CONVERSION.TOASCII; charConversionIndexList = new Generics.IndexList(); charConversionIndexList.addAll(argArray.parseIntArray()); break; default: unknownDashCommand(dashCommand); } } if (havingUnknownDashCommand()) { setCommandResult(COMMANDRESULT.FAILURE); } else { ResultSetClosure srcResultSetClosure; ResultSetClosure destResultSetClosure; switch (getFunction()) { case AUTOCOMMIT: try { setAutoCommit(getDataSrc(), autoCommitValue); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Exception setting autocommit mode in CmdRs for source result set", ex); setCommandResult(COMMANDRESULT.FAILURE); } try { setAutoCommit(getDataDest(), autoCommitValue); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Exception setting autocommit mode in CmdRs for destination result set", ex); setCommandResult(COMMANDRESULT.FAILURE); } break; case CLOSE: if (myRs == null) { getLogger().log(Level.SEVERE, "Tuple not found for -close in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } else { try { myRs.closeRS(); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Could not close result set from tuple in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case CLOSEDB: if (myRs == null) { getLogger().log(Level.SEVERE, "Tuple not found for -closedb in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } else { try { myRs.close(); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Could not close result set from tuple in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case CLOSEST: if (myRs == null) { getLogger().log(Level.SEVERE, "Tuple not found for -closest in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } else { try { myRs.closeRS().closeStatement(); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Could not close result set from tuple in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case COMMIT: try { commit(commitTupleName); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Error committing result set from tuple " + commitTupleName, ex); setCommandResult(COMMANDRESULT.FAILURE); } break; case FETCHSIZE: try { setFetchSize(getDataSrc(), rowsToFetch); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Exception setting autocommit mode in CmdRs for source result set", ex); setCommandResult(COMMANDRESULT.FAILURE); } try { setFetchSize(getDataDest(), rowsToFetch); } catch (SQLException ex) { getLogger().log(Level.SEVERE, "Exception setting autocommit mode in CmdRs for destination result set", ex); setCommandResult(COMMANDRESULT.FAILURE); } break; case INSERT: if (getDataDest() == null | getDataSrc() == null) { getLogger().log(Level.SEVERE, "Missing data source or data dest in rs command"); setCommandResult(COMMANDRESULT.FAILURE); } else if (!getDataDest().getType().equals(DataSink.SINKTYPE.TUPLE) || !getDataSrc().getType().equals(DataSink.SINKTYPE.TUPLE)) { getLogger().log(Level.SEVERE, "Source dest or data dest in rs command not a tuple"); setCommandResult(COMMANDRESULT.FAILURE); } else { try { srcResultSetClosure = ResultSetClosure.class.cast(getTuple(getDataSrc().getName()).getValue()); destResultSetClosure = ResultSetClosure.class.cast(getTuple(getDataDest().getName()).getValue()); if (srcResultSetClosure == null || destResultSetClosure == null) { getLogger().log(Level.SEVERE, "Null instead of result set for one or both of source and/or destination in rs"); setCommandResult(COMMANDRESULT.FAILURE); } else { ResultSet srcResultSet = srcResultSetClosure.getResultSet(); ResultSet destResultSet = destResultSetClosure.getResultSet(); ResultSetHelper rsh = new ResultSetHelper(srcResultSet, destResultSet, charConversionIndexList, conversion); rsh.updateInsertingTable(); } } catch (SQLException ex) { getLogger().log(Level.SEVERE, "SQL exception in command rs", ex); setCommandResult(COMMANDRESULT.FAILURE); } catch (ClassCastException ex) { getLogger().log(Level.SEVERE, "Either the source or destination in command rs was not a result set", ex); setCommandResult(COMMANDRESULT.FAILURE); } catch (UnsupportedEncodingException ex) { getLogger().log(Level.SEVERE, "Character set conversion failed", ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case JSON: if (myRs != null && myDb != null && tableName != null) { try { put(myRs.toJSON(myDb, tableName)); } catch (JSONException | SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Exception converting or putting JSON in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case SPLIT: if (getDataDest() == null | getDataSrc() == null) { getLogger().log(Level.SEVERE, "Missing data source or data dest in rs command"); setCommandResult(COMMANDRESULT.FAILURE); break; } else if (!getDataDest().getType().equals(DataSink.SINKTYPE.TUPLE) || !getDataSrc().getType().equals(DataSink.SINKTYPE.TUPLE)) { getLogger().log(Level.SEVERE, "Source dest or data dest in rs command not a tuple"); setCommandResult(COMMANDRESULT.FAILURE); } else { try { srcResultSetClosure = ResultSetClosure.class.cast(getTuple(getDataSrc().getName()).getValue()); destResultSetClosure = ResultSetClosure.class.cast(getTuple(getDataDest().getName()).getValue()); if (srcResultSetClosure == null || destResultSetClosure == null) { getLogger().log(Level.SEVERE, "Null instead of result set for one or both of source and/or destination in rs"); setCommandResult(COMMANDRESULT.FAILURE); } else { ResultSet srcResultSet = srcResultSetClosure.getResultSet(); ResultSet destResultSet = destResultSetClosure.getResultSet(); ResultSetHelper rsh = new ResultSetHelper(srcResultSet, destResultSet, charConversionIndexList, conversion); rsh.updateSplittingInsertingTable(getSplitTarget(), getSplitWidths()); } } catch (SQLException ex) { getLogger().log(Level.SEVERE, "SQL exception in command rs", ex); setCommandResult(COMMANDRESULT.FAILURE); } catch (ClassCastException ex) { getLogger().log(Level.SEVERE, "Either the source or destination in command rs was not a result set", ex); setCommandResult(COMMANDRESULT.FAILURE); } catch (UnsupportedEncodingException ex) { getLogger().log(Level.SEVERE, "Charcter set conversion failed", ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case METADATA: if (getDataSrc() == null) { getLogger().log(Level.SEVERE, "Missing data source in rs -metadata command"); setCommandResult(COMMANDRESULT.FAILURE); break; } try { srcResultSetClosure = ResultSetClosure.class.cast(getTuple(getDataSrc().getName()).getValue()); put(srcResultSetClosure.getResultSet().getMetaData()); } catch (SQLException | RequestNotSupportedException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "Exception getting or putting result set metadata", ex); setCommandResult(COMMANDRESULT.FAILURE); } catch (ClassCastException ex) { getLogger().log(Level.SEVERE, "Source command rs -metadata was not a result set", ex); setCommandResult(COMMANDRESULT.FAILURE); } break; } } return argArray; } private void setAutoCommit(DataSink ds, boolean ac) throws SQLException { Tuple autoCommitTuple; Object hopefullyAResultSetClosure; if (ds.getType() == DataSink.SINKTYPE.TUPLE) { autoCommitTuple = getTuple(getDataSrc().getName()); if (autoCommitTuple == null) { getLogger().log(Level.WARNING, "Tuple {0} not found", getDataSrc().getName()); } else { hopefullyAResultSetClosure = autoCommitTuple.getValue(); if (hopefullyAResultSetClosure instanceof ResultSetClosure) { ResultSetClosure.class .cast(hopefullyAResultSetClosure).setAutoCommit(ac); } else { getLogger().log(Level.WARNING, "Source tuple {0} is not a ResultSetClosure", autoCommitTuple.getKey()); } } } else { getLogger().log(Level.WARNING, "DataSink {0} is not a Tuple", ds.getName()); } } private void commit(String commitTupleName) throws SQLException { Tuple commitTuple; Object hopefullyAResultSetClosure; commitTuple = getTuple(commitTupleName); if (commitTuple == null) { getLogger().log(Level.WARNING, "Tuple {0} not found", commitTupleName); } else { hopefullyAResultSetClosure = commitTuple.getValue(); if (hopefullyAResultSetClosure instanceof ResultSetClosure) { ResultSetClosure.class .cast(hopefullyAResultSetClosure).commit(); } else { getLogger().log(Level.WARNING, "Source tuple {0} is not a ResultSetClosure", commitTuple.getKey()); } } } private void setFetchSize(DataSink ds, int fetchSize) throws SQLException { Tuple fetchSizeTuple; Object hopefullyAResultSetClosure; if (ds.getType() == DataSink.SINKTYPE.TUPLE) { fetchSizeTuple = getTuple(getDataSrc().getName()); if (fetchSizeTuple == null) { getLogger().log(Level.WARNING, "Tuple {0} not found", getDataSrc().getName()); } else { hopefullyAResultSetClosure = fetchSizeTuple.getValue(); if (hopefullyAResultSetClosure instanceof ResultSetClosure) { ResultSetClosure rsc = ResultSetClosure.class .cast(hopefullyAResultSetClosure); if (fetchSize > 0) { rsc.setFetchSize(fetchSize); } getLogger().log(Level.INFO, "Fetch size for result set in tuple {0} is {1}", new Object[]{fetchSizeTuple.getKey(), rsc.getResultSet().getFetchSize()}); } else { getLogger().log(Level.WARNING, "Source tuple {0} is not a ResultSetClosure", fetchSizeTuple.getKey()); } } } else { getLogger().log(Level.WARNING, "DataSink {0} is not a Tuple", ds.getName()); } } @Override public void reinit() { super.reinit(); setFunction(FUNCTIONS.NULL); setSplitTarget(0); // not strictly necessary since -split instances setSplitWidths(null); // not strictly necessary since -split instances } @Override public ArgArray cmd(ArgArray args) { reinit(); return rs(args); } @Override public COMMANDRESULT getResult() { return getCommandResult(); } }
CmdRs -bytes
src/ublu/command/CmdRs.java
CmdRs -bytes
<ide><path>rc/ublu/command/CmdRs.java <ide> Db myDb = null; <ide> ResultSetClosure myRs = null; <ide> String tableName = null; <add> Integer fieldindex = null; <ide> while (argArray.hasDashCommand()) { <ide> String dashCommand = argArray.parseDashCommand(); <ide> switch (dashCommand) { <ide> case "-autocommit": <ide> setFunction(FUNCTIONS.AUTOCOMMIT); <ide> autoCommitValue = argArray.nextInt() == 0; <add> break; <add> case "bytes": <add> setFunction(FUNCTIONS.BYTES); <add> fieldindex = argArray.nextIntMaybeQuotationTuplePopString(); <ide> break; <ide> case "-close": <ide> myRs = argArray.nextTupleOrPop().value(ResultSetClosure.class); <ide> } <ide> break; <ide> <add> case BYTES: <add> if (myRs == null) { <add> getLogger().log(Level.SEVERE, "Tuple not found for -bytes in {0}", getNameAndDescription()); <add> setCommandResult(COMMANDRESULT.FAILURE); <add> } else { <add> try { <add> put(myRs.getResultSet().getBytes(fieldindex)); <add> } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { <add> getLogger().log(Level.SEVERE, "Could not get or put bytes result set for column index " + fieldindex + " in " + getNameAndDescription(), ex); <add> setCommandResult(COMMANDRESULT.FAILURE); <add> } <add> } <add> break; <add> <ide> case CLOSE: <ide> if (myRs == null) { <ide> getLogger().log(Level.SEVERE, "Tuple not found for -close in {0}", getNameAndDescription()); <ide> } <ide> } <ide> break; <add> <ide> case SPLIT: <ide> if (getDataDest() == null | getDataSrc() == null) { <ide> getLogger().log(Level.SEVERE, "Missing data source or data dest in rs command");
Java
mit
6ee14c4ebe34e1695584a73614e0288b0dac8779
0
RGaldamez/ArbolBJava
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package arbolbjava; /** * * @author RickAg */ public class Tree { private TreeNode root; public Tree(TreeNode root) { this.root = root; } public TreeNode getRoot() { return root; } public void setRoot(TreeNode root) { this.root = root; } public void insert(int key, TreeNode Node) { if (Node.getFather() == null && Node.isLeaf()) { if (!Node.isFull()) { if (Node.leftEmpty() && Node.rightEmpty()) { Node.setLeftKey(key); } else if (!Node.leftEmpty() && Node.rightEmpty()) { Node.setRightKey(key); } order(Node); } else { int key1 = Node.getLeftKey(); int key2 = Node.getRightKey(); int key3 = key; TreeNode leftTemp, rightTemp; if (key3 < key1) { leftTemp = new TreeNode(key3, Node); rightTemp = new TreeNode(key2, Node); Node = new TreeNode(key1); leftTemp.setFather(Node); rightTemp.setFather(Node); Node.setLeftBranch(leftTemp); Node.setRightBranch(rightTemp); } else if (key3 > key2) { leftTemp = new TreeNode(key1, Node); rightTemp = new TreeNode(key, Node); Node = new TreeNode(key2); leftTemp.setFather(Node); rightTemp.setFather(Node); Node.setLeftBranch(leftTemp); Node.setRightBranch(rightTemp); } else { leftTemp = new TreeNode(key1, Node); rightTemp = new TreeNode(key2, Node); Node = new TreeNode(key); leftTemp.setFather(Node); rightTemp.setFather(Node); Node.setLeftBranch(leftTemp); Node.setRightBranch(rightTemp); } } } else if (Node.getFather() == null && !Node.isLeaf()) { int leftKey = Node.getLeftKey(); int rightKey = Node.getRightKey(); if (key < leftKey) { insert(key, Node.getLeftBranch()); } else if (key > leftKey && key < rightKey) { insert(key, Node.getMiddleBranch()); } else if (key > rightKey && Node.getRightBranch() != null) { insert(key, Node.getRightBranch()); } else if (key > rightKey && Node.getRightBranch() == null) { insert(key, Node.getMiddleBranch()); } } else { if (Node.isLeaf() && !Node.isFull()) { Node.setRightKey(key); order(Node); } else if (!Node.isLeaf()) { if (Node.rightEmpty()) { if (key < Node.getLeftKey()) { insert(key, Node.getLeftBranch()); } else { insert(key, Node.getMiddleBranch()); } } else { if (key < Node.getLeftKey()) { insert(key, Node.getLeftBranch()); } else if (Node.getLeftKey() < key && key > Node.getRightKey()) { insert(key, Node.getMiddleBranch()); } else { insert(key, Node.getRightBranch()); } } } else if (Node.isLeaf() && Node.isFull() && !Node.getFather().isFull()) { setRelations(null, root); if (Node == Node.getFather().getLeftBranch()){ promote(Node, key,true,false); }else if (Node == Node.getFather().getMiddleBranch()){ promote(Node, key,false,true); } }else if (Node.isLeaf() && Node.isFull() && Node.getFather().isFull()){ if (Node == Node.getFather().getLeftBranch()){ }else if (Node == Node.getFather().getMiddleBranch()){ }else if (Node == Node.getFather().getRightBranch()){ } } } } public void order(TreeNode node) { int left = node.getLeftKey(); int right = node.getRightKey(); if (left > right) { node.setLeftKey(right); node.setRightKey(left); } } public void setRelations(TreeNode father, TreeNode child) { if (father == null) { if (father.getLeftBranch() != null) { setRelations(child, child.getLeftBranch()); } if (father.getMiddleBranch() != null) { setRelations(child, child.getMiddleBranch()); } if (father.getRightBranch() != null) { setRelations(child, child.getRightBranch()); } } else if (father != null && !father.isLeaf()) { if (father.getLeftBranch() != null) { setRelations(child, child.getLeftBranch()); } if (father.getMiddleBranch() != null) { setRelations(child, child.getMiddleBranch()); } if (father.getRightBranch() != null) { setRelations(child, child.getRightBranch()); } } child.setFather(father); } public void promote(TreeNode node, int key3, boolean first, boolean second) { int key1 = node.getLeftKey(); int key2 = node.getRightKey(); int keyToLeft= -1; int keyToRight = -1; int toRise = -1; TreeNode leftNode = new TreeNode(); TreeNode rightNode = new TreeNode(); if (key3 < key1) { //key3 menor leftNode = new TreeNode(key3); rightNode = new TreeNode(key2); toRise = key1; keyToLeft = key3; keyToRight = key2; } else if ( key1 < key3 && key3 < key2 ) { //key3 en medio leftNode = new TreeNode(key1); rightNode = new TreeNode(key2); toRise = key3; keyToLeft = key1; keyToRight = key2; int fatherLeft; } else if (key2 < key3 ) { //key3 mayor leftNode = new TreeNode(key1); rightNode = new TreeNode(key3); toRise = key2; keyToLeft = key1; keyToRight = key3; } if (first){ node.getFather().setRightKey(node.getFather().getLeftKey()); node.getFather().setLeftKey(toRise); node.getFather().setLeftBranch(new TreeNode(keyToLeft)); node.getFather().setRightBranch(node.getFather().getMiddleBranch()); node.getFather().setMiddleBranch(new TreeNode(keyToRight)); } if (second){ node.getFather().setRightKey(toRise); node.getFather().setMiddleBranch(new TreeNode(keyToLeft)); node.getFather().setRightBranch(new TreeNode(keyToRight)); } setRelations(null,root); } public void promoteRR(TreeNode father, int key, boolean first, boolean second, boolean third) { int fatherLeft = father.getLeftKey(); int fatherRight = father.getRightKey(); int sonLeft = -1; int sonRight = -1; TreeNode tempFather; TreeNode tempFirstBorn; TreeNode tempSecondBorn; TreeNode tempGrandson1; TreeNode tempGrandson2; TreeNode tempGrandson3; TreeNode tempGrandson4; tempFather = new TreeNode(fatherLeft); tempFirstBorn = new TreeNode(sonLeft); tempSecondBorn = new TreeNode(fatherRight); tempGrandson1 = new TreeNode(); tempGrandson2 = new TreeNode(); tempGrandson3 = father.getMiddleBranch(); tempGrandson4 = father.getRightBranch(); tempGrandson1.setFather(tempFirstBorn); tempGrandson2.setFather(tempFirstBorn); tempGrandson3.setFather(tempSecondBorn); tempGrandson4.setFather(tempSecondBorn); tempFirstBorn.setLeftBranch(tempGrandson1); tempFirstBorn.setMiddleBranch(tempGrandson2); tempFirstBorn.setFather(tempFather); tempSecondBorn.setLeftBranch(tempGrandson3); tempSecondBorn.setMiddleBranch(tempGrandson4); tempSecondBorn.setFather(tempFather); tempFather.setFather(father.getFather()); father = tempFather; } public void promoteR(TreeNode father, int key, boolean first, boolean second, boolean third){ int sonLeft = father.getLeftKey(); int sonRight = father.getRightKey(); int grandSonLeft; int grandSonRight; int bottomLeft; int bottomRight; int toRise; int toRiseAgain; TreeNode tempFather; TreeNode firstSon; TreeNode secondSon; TreeNode grandSon1; TreeNode grandSon2; TreeNode grandSon3; if (first){ grandSonLeft = father.getLeftBranch().getLeftKey(); grandSonRight = father.getLeftBranch().getRightKey(); if (key < grandSonLeft){ toRise = grandSonLeft; bottomLeft = key; bottomRight = grandSonRight; }else if (grandSonLeft < key && key < grandSonRight){ toRise = key; bottomLeft = key; bottomRight = grandSonRight; }else{ toRise = grandSonRight; bottomLeft = key; bottomRight = grandSonRight; } } if (second){ grandSonLeft = father.getMiddleBranch().getLeftKey(); grandSonRight = father.getMiddleBranch().getRightKey(); if (key < grandSonLeft){ toRise = grandSonLeft; }else if (grandSonLeft < key && key < grandSonRight){ toRise = key; }else{ toRise = grandSonRight; } } if (third){ grandSonLeft = father.getRightBranch().getLeftKey(); grandSonRight = father.getRightBranch().getRightKey(); if (key < grandSonLeft){ toRise = grandSonLeft; }else if (grandSonLeft < key && key < grandSonRight){ toRise = key; }else{ toRise = grandSonRight; } } } }
src/arbolbjava/Tree.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package arbolbjava; /** * * @author RickAg */ public class Tree { private TreeNode root; public Tree(TreeNode root) { this.root = root; } public TreeNode getRoot() { return root; } public void setRoot(TreeNode root) { this.root = root; } public void insert(int key, TreeNode Node) { if (Node.getFather() == null && Node.isLeaf()) { if (!Node.isFull()) { if (Node.leftEmpty() && Node.rightEmpty()) { Node.setLeftKey(key); } else if (!Node.leftEmpty() && Node.rightEmpty()) { Node.setRightKey(key); } order(Node); } else { int key1 = Node.getLeftKey(); int key2 = Node.getRightKey(); int key3 = key; TreeNode leftTemp, rightTemp; if (key3 < key1) { leftTemp = new TreeNode(key3, Node); rightTemp = new TreeNode(key2, Node); Node = new TreeNode(key1); leftTemp.setFather(Node); rightTemp.setFather(Node); Node.setLeftBranch(leftTemp); Node.setRightBranch(rightTemp); } else if (key3 > key2) { leftTemp = new TreeNode(key1, Node); rightTemp = new TreeNode(key, Node); Node = new TreeNode(key2); leftTemp.setFather(Node); rightTemp.setFather(Node); Node.setLeftBranch(leftTemp); Node.setRightBranch(rightTemp); } else { leftTemp = new TreeNode(key1, Node); rightTemp = new TreeNode(key2, Node); Node = new TreeNode(key); leftTemp.setFather(Node); rightTemp.setFather(Node); Node.setLeftBranch(leftTemp); Node.setRightBranch(rightTemp); } } } else if (Node.getFather() == null && !Node.isLeaf()) { int leftKey = Node.getLeftKey(); int rightKey = Node.getRightKey(); if (key < leftKey) { insert(key, Node.getLeftBranch()); } else if (key > leftKey && key < rightKey) { insert(key, Node.getMiddleBranch()); } else if (key > rightKey && Node.getRightBranch() != null) { insert(key, Node.getRightBranch()); } else if (key > rightKey && Node.getRightBranch() == null) { insert(key, Node.getMiddleBranch()); } } else { if (Node.isLeaf() && !Node.isFull()) { Node.setRightKey(key); order(Node); } else if (!Node.isLeaf()) { if (Node.rightEmpty()) { if (key < Node.getLeftKey()) { insert(key, Node.getLeftBranch()); } else { insert(key, Node.getMiddleBranch()); } } else { if (key < Node.getLeftKey()) { insert(key, Node.getLeftBranch()); } else if (Node.getLeftKey() < key && key > Node.getRightKey()) { insert(key, Node.getMiddleBranch()); } else { insert(key, Node.getRightBranch()); } } } else if (Node.isLeaf() && Node.isFull()) { //split promote setRelations(null, root); } } } public void order(TreeNode node) { int left = node.getLeftKey(); int right = node.getRightKey(); if (left > right) { node.setLeftKey(right); node.setRightKey(left); } } public void setRelations(TreeNode father, TreeNode child) { if (father == null) { if (father.getLeftBranch() != null) { setRelations(child, child.getLeftBranch()); } if (father.getMiddleBranch() != null) { setRelations(child, child.getMiddleBranch()); } if (father.getRightBranch() != null) { setRelations(child, child.getRightBranch()); } } else if (father != null && !father.isLeaf()) { if (father.getLeftBranch() != null) { setRelations(child, child.getLeftBranch()); } if (father.getMiddleBranch() != null) { setRelations(child, child.getMiddleBranch()); } if (father.getRightBranch() != null) { setRelations(child, child.getRightBranch()); } } else { child.setFather(father); } } public void promote(TreeNode node, int key3) { int key1 = node.getLeftKey(); int key2 = node.getRightKey(); int toRise = -1; TreeNode leftNode = new TreeNode(); TreeNode rightNode = new TreeNode(); if (key3 < key1) { //key3 menor leftNode = new TreeNode(key3); rightNode = new TreeNode(key2); toRise = key1; } else if (key1 < key3 && key3 < key2) { //key3 en medio leftNode = new TreeNode(key1); rightNode = new TreeNode(key2); toRise = key3; } else if (key2 < key3) { //key3 mayor leftNode = new TreeNode(key1); rightNode = new TreeNode(key3); toRise = key2; } if (node.getFather() == null) { //uy papa } else { if (node.getFather().rightEmpty()) { if (node.getFather().getMiddleBranch().rightEmpty()) { node.getFather().getMiddleBranch().setRightKey(leftNode.getLeftKey()); order(node.getFather().getMiddleBranch()); } else { /*int newkey1 = node.getFather().getLeftKey(); int newkey2 = node.getFather().getRightKey(); int toRiseAgain; if (toRise < newkey1) { } else if (toRise > newkey1 && toRise < newkey2) { } else if (toRise > newkey2) { }*/ } if (node.getFather().getRightBranch() != null && node.getFather().getRightBranch().rightEmpty()) { node.getFather().getRightBranch().setRightKey(rightNode.getLeftKey()); order(node.getFather().getRightBranch()); } else { /*int newkey1 = node.getFather().getLeftKey(); int newkey2 = node.getFather().getRightKey(); int toRiseAgain; if (toRise < newkey1) { } else if (toRise > newkey1 && toRise < newkey2) { } else if (toRise > newkey2) { }*/ } } else { } } } public void promoteRR(TreeNode father, int key, boolean first, boolean second, boolean third) { int fatherLeft = father.getLeftKey(); int fatherRight = father.getRightKey(); int sonLeft = -1; int sonRight = -1; TreeNode tempFather; TreeNode tempFirstBorn; TreeNode tempSecondBorn; TreeNode tempGrandson1; TreeNode tempGrandson2; TreeNode tempGrandson3; TreeNode tempGrandson4; tempFather = new TreeNode(fatherLeft); tempFirstBorn = new TreeNode(sonLeft); tempSecondBorn = new TreeNode(fatherRight); tempGrandson1 = new TreeNode(); tempGrandson2 = new TreeNode(); tempGrandson3 = father.getMiddleBranch(); tempGrandson4 = father.getRightBranch(); tempGrandson1.setFather(tempFirstBorn); tempGrandson2.setFather(tempFirstBorn); tempGrandson3.setFather(tempSecondBorn); tempGrandson4.setFather(tempSecondBorn); tempFirstBorn.setLeftBranch(tempGrandson1); tempFirstBorn.setMiddleBranch(tempGrandson2); tempFirstBorn.setFather(tempFather); tempSecondBorn.setLeftBranch(tempGrandson3); tempSecondBorn.setMiddleBranch(tempGrandson4); tempSecondBorn.setFather(tempFather); tempFather.setFather(father.getFather()); father = tempFather; } public void promoteR(TreeNode father, int key, boolean first, boolean second, boolean third){ int sonLeft = father.getLeftKey(); int sonRight = father.getRightKey(); int grandSonLeft; int grandSonRight; int toRise; int toRiseAgain; TreeNode tempFather; TreeNode firstSon; TreeNode secondSon; TreeNode grandSon1; TreeNode grandSon2; TreeNode grandSon3; if (first){ grandSonLeft = father.getLeftBranch().getLeftKey(); grandSonRight = father.getLeftBranch().getRightKey(); if (key < grandSonLeft){ toRise = grandSonLeft; }else if (grandSonLeft < key && key < grandSonRight){ toRise = key; }else{ toRise = grandSonRight; } } if (second){ grandSonLeft = father.getMiddleBranch().getLeftKey(); grandSonRight = father.getMiddleBranch().getRightKey(); if (key < grandSonLeft){ toRise = grandSonLeft; }else if (grandSonLeft < key && key < grandSonRight){ toRise = key; }else{ toRise = grandSonRight; } } if (third){ grandSonLeft = father.getRightBranch().getLeftKey(); grandSonRight = father.getRightBranch().getRightKey(); if (key < grandSonLeft){ toRise = grandSonLeft; }else if (grandSonLeft < key && key < grandSonRight){ toRise = key; }else{ toRise = grandSonRight; } } } }
Trabajando en el doble promote
src/arbolbjava/Tree.java
Trabajando en el doble promote
<ide><path>rc/arbolbjava/Tree.java <ide> insert(key, Node.getRightBranch()); <ide> } <ide> } <del> } else if (Node.isLeaf() && Node.isFull()) { <del> //split promote <add> } else if (Node.isLeaf() && Node.isFull() && !Node.getFather().isFull()) { <ide> setRelations(null, root); <add> if (Node == Node.getFather().getLeftBranch()){ <add> promote(Node, key,true,false); <add> }else if (Node == Node.getFather().getMiddleBranch()){ <add> promote(Node, key,false,true); <add> } <add> <add> }else if (Node.isLeaf() && Node.isFull() && Node.getFather().isFull()){ <add> if (Node == Node.getFather().getLeftBranch()){ <add> <add> }else if (Node == Node.getFather().getMiddleBranch()){ <add> <add> }else if (Node == Node.getFather().getRightBranch()){ <add> <add> } <ide> } <ide> } <ide> <ide> if (father.getRightBranch() != null) { <ide> setRelations(child, child.getRightBranch()); <ide> } <del> } else { <del> child.setFather(father); <del> } <del> } <del> <del> public void promote(TreeNode node, int key3) { <add> } <add> child.setFather(father); <add> } <add> <add> public void promote(TreeNode node, int key3, boolean first, boolean second) { <ide> int key1 = node.getLeftKey(); <ide> int key2 = node.getRightKey(); <add> int keyToLeft= -1; <add> int keyToRight = -1; <ide> int toRise = -1; <ide> TreeNode leftNode = new TreeNode(); <ide> TreeNode rightNode = new TreeNode(); <ide> leftNode = new TreeNode(key3); <ide> rightNode = new TreeNode(key2); <ide> toRise = key1; <del> <del> } else if (key1 < key3 && key3 < key2) { <add> keyToLeft = key3; <add> keyToRight = key2; <add> <add> <add> } else if ( key1 < key3 && key3 < key2 ) { <ide> //key3 en medio <ide> leftNode = new TreeNode(key1); <ide> rightNode = new TreeNode(key2); <ide> toRise = key3; <del> <del> } else if (key2 < key3) { <add> keyToLeft = key1; <add> keyToRight = key2; <add> int fatherLeft; <add> <add> } else if (key2 < key3 ) { <ide> //key3 mayor <ide> leftNode = new TreeNode(key1); <ide> rightNode = new TreeNode(key3); <ide> toRise = key2; <del> } <del> <del> if (node.getFather() == null) { <del> //uy papa <del> } else { <del> if (node.getFather().rightEmpty()) { <del> if (node.getFather().getMiddleBranch().rightEmpty()) { <del> node.getFather().getMiddleBranch().setRightKey(leftNode.getLeftKey()); <del> order(node.getFather().getMiddleBranch()); <del> } else { <del> /*int newkey1 = node.getFather().getLeftKey(); <del> int newkey2 = node.getFather().getRightKey(); <del> int toRiseAgain; <del> <del> if (toRise < newkey1) { <del> <del> } else if (toRise > newkey1 && toRise < newkey2) { <del> <del> } else if (toRise > newkey2) { <del> <del> }*/ <del> <del> } <del> if (node.getFather().getRightBranch() != null && node.getFather().getRightBranch().rightEmpty()) { <del> node.getFather().getRightBranch().setRightKey(rightNode.getLeftKey()); <del> order(node.getFather().getRightBranch()); <del> } else { <del> <del> /*int newkey1 = node.getFather().getLeftKey(); <del> int newkey2 = node.getFather().getRightKey(); <del> int toRiseAgain; <del> <del> if (toRise < newkey1) { <del> <del> } else if (toRise > newkey1 && toRise < newkey2) { <del> <del> } else if (toRise > newkey2) { <del> <del> }*/ <del> } <del> } else { <del> <del> } <del> } <del> <add> keyToLeft = key1; <add> keyToRight = key3; <add> } <add> <add> if (first){ <add> node.getFather().setRightKey(node.getFather().getLeftKey()); <add> node.getFather().setLeftKey(toRise); <add> node.getFather().setLeftBranch(new TreeNode(keyToLeft)); <add> node.getFather().setRightBranch(node.getFather().getMiddleBranch()); <add> node.getFather().setMiddleBranch(new TreeNode(keyToRight)); <add> } <add> if (second){ <add> node.getFather().setRightKey(toRise); <add> node.getFather().setMiddleBranch(new TreeNode(keyToLeft)); <add> node.getFather().setRightBranch(new TreeNode(keyToRight)); <add> } <add> setRelations(null,root); <ide> } <ide> <ide> public void promoteRR(TreeNode father, int key, boolean first, boolean second, boolean third) { <ide> int sonRight = father.getRightKey(); <ide> int grandSonLeft; <ide> int grandSonRight; <add> int bottomLeft; <add> int bottomRight; <ide> int toRise; <ide> int toRiseAgain; <ide> TreeNode tempFather; <ide> <ide> if (key < grandSonLeft){ <ide> toRise = grandSonLeft; <add> bottomLeft = key; <add> bottomRight = grandSonRight; <add> <ide> }else if (grandSonLeft < key && key < grandSonRight){ <ide> toRise = key; <add> bottomLeft = key; <add> bottomRight = grandSonRight; <add> <ide> }else{ <ide> toRise = grandSonRight; <add> bottomLeft = key; <add> bottomRight = grandSonRight; <add> <ide> } <ide> } <ide> if (second){
Java
apache-2.0
95c2ed85f6d58fec55a7399ea2b4548097f2b867
0
mpouttuclarke/cdap,mpouttuclarke/cdap,caskdata/cdap,hsaputra/cdap,caskdata/cdap,hsaputra/cdap,caskdata/cdap,chtyim/cdap,mpouttuclarke/cdap,anthcp/cdap,chtyim/cdap,caskdata/cdap,hsaputra/cdap,anthcp/cdap,anthcp/cdap,mpouttuclarke/cdap,chtyim/cdap,chtyim/cdap,mpouttuclarke/cdap,anthcp/cdap,chtyim/cdap,anthcp/cdap,hsaputra/cdap,caskdata/cdap,chtyim/cdap,caskdata/cdap,hsaputra/cdap
/* * Copyright 2012-2013 Continuuity,Inc. All Rights Reserved. */ package com.continuuity.app.services; import com.continuuity.common.conf.CConfiguration; import com.continuuity.common.conf.Constants; import com.continuuity.common.utils.Copyright; import com.continuuity.common.utils.UsageException; import com.continuuity.internal.app.BufferFileInputStream; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Client for interacting with Local Reactor's app-fabric service to perform the following operations: * a) Deploy app * b) Start/Stop/Status of flow, procedure or map reduce job * c) Promote app to cloud * d) Scale number of flowlet instances * <p/> * Usage: * ReactorClient client = new ReactorClient(); * client.execute(args, CConfiguration.create()); */ public final class ReactorClient { /** * For debugging purposes, should only be set to true in unit tests. * When true, program will print the stack trace after the usage. */ public static boolean debug = false; private static final String DEVELOPER_ACCOUNT_ID = Constants.DEVELOPER_ACCOUNT_ID; private static final Set<String> AVAILABLE_COMMANDS = Sets.newHashSet("deploy", "stop", "start", "help", "promote", "status", "scale", "delete"); private static final String ARCHIVE_LONG_OPT_ARG = "archive"; private static final String APPLICATION_LONG_OPT_ARG = "application"; private static final String PROCEDURE_LONG_OPT_ARG = "procedure"; private static final String FLOW_LONG_OPT_ARG = "flow"; private static final String FLOWLET_LONG_OPT_ARG = "flowlet"; private static final String FLOWLET_INSTANCES_LONG_OPT_ARG = "instances"; private static final String MAPREDUCE_LONG_OPT_ARG = "mapreduce"; private static final String HOSTNAME_LONG_OPT_ARG = "host"; private static final String APIKEY_LONG_OPT_ARG = "apikey"; private static final String DEBUG_LONG_OPT_ARG = "debug"; private String resource; private String application; private String procedure; private String flow; private String flowlet; private short flowletInstances; private String mapReduce; private String hostname; private String authToken; private String command; private CConfiguration configuration; String getCommand() { return command; } /** * Prints the usage information and throws a UsageException if error is true. */ private void usage(boolean error) { PrintStream out; if (error) { out = System.err; } else { out = System.out; } Copyright.print(out); out.println("Usage:"); out.println(" reactor-client deploy --archive <filename>"); out.println(" reactor-client start --application <id> ( --flow <id> | --procedure <id> | --mapreduce <id>)"); out.println(" reactor-client stop --application <id> ( --flow <id> | --procedure <id> | --mapreduce <id>)"); out.println(" reactor-client status --application <id> ( --flow <id> | --procedure <id> | --mapreduce <id>)"); out.println(" reactor-client scale --application <id> --flow <id> --flowlet <id> --instances <number>"); out.println(" reactor-client promote --application <id> --host <hostname> --apikey <key>"); out.println(" reactor-client delete --application <id>"); out.println(" reactor-client help"); out.println("Options:"); out.println(" --archive <filename> \t Archive containing the application."); out.println(" --application <id> \t Application Id."); out.println(" --flow <id> \t\t Flow id of the application."); out.println(" --procedure <id> \t Procedure of in the application."); out.println(" --mapreduce <id> \t MapReduce job of in the application."); out.println(" --host <hostname> \t Hostname to push the application to."); out.println(" --apikey <key> \t Apikey of the account."); out.flush(); if (error) { throw new UsageException(); } } /** * Prints an error message followed by the usage information. * * @param errorMessage the error message */ private void usage(String errorMessage) { if (errorMessage != null) { System.err.println("Error: " + errorMessage); } usage(true); } /** * Executes the configured operation */ private void executeInternal() throws TException, InterruptedException, AppFabricServiceException, IOException { Preconditions.checkNotNull(command, "App client is not configured to run"); Preconditions.checkNotNull(configuration, "App client configuration is not set"); String address = "localhost"; int port = configuration.getInt(Constants.CFG_APP_FABRIC_SERVER_PORT, Constants.DEFAULT_APP_FABRIC_SERVER_PORT); TTransport transport = null; TProtocol protocol; try { transport = new TFramedTransport(new TSocket(address, port)); protocol = new TBinaryProtocol(transport); transport.open(); AppFabricService.Client client = new AppFabricService.Client(protocol); if ("deploy".equals(command)) { System.out.println("Deploying the app..."); deploy(client); } if ("delete".equals(command)) { System.out.println("Deleting the app..."); AuthToken dummyAuthToken = new AuthToken("ReactorClient"); client.removeApplication(dummyAuthToken, new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, "", 1)); System.out.println("Deleted."); } if ("start".equals(command)) { System.out.println("Starting..."); AuthToken dummyAuthToken = new AuthToken("ReactorClient"); FlowIdentifier identifier; if (flow != null) { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, flow, 1); identifier.setType(EntityType.FLOW); System.out.println(String.format("Starting flow %s for application %s ", flow, application)); } else if (mapReduce != null) { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, mapReduce, 1); identifier.setType(EntityType.MAPREDUCE); System.out.println(String.format("Starting mapreduce job %s for application %s ", mapReduce, application)); } else { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, procedure, 1); identifier.setType(EntityType.QUERY); System.out.println(String.format("Starting procedure %s for application %s ", procedure, application)); } client.start(dummyAuthToken, new FlowDescriptor(identifier, ImmutableMap.<String, String>of())); System.out.println("Started "); return; } if ("stop".equals(command)) { System.out.println("Stopping..."); AuthToken dummyAuthToken = new AuthToken("ReactorClient"); FlowIdentifier identifier; if (flow != null) { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, flow, 1); identifier.setType(EntityType.FLOW); System.out.println(String.format("Stopping flow %s for application %s ", flow, application)); } else if (mapReduce != null) { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, mapReduce, 1); identifier.setType(EntityType.MAPREDUCE); System.out.println(String.format("Killing mapreduce job %s for application %s ", mapReduce, application)); } else { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, procedure, 1); identifier.setType(EntityType.QUERY); System.out.println(String.format("Stopping procedure %s for application %s ", procedure, application)); } client.stop(dummyAuthToken, identifier); System.out.println("Stopped "); return; } if ("scale".equals(command)) { System.out.println("Scaling..."); AuthToken dummyAuthToken = new AuthToken("ReactorClient"); FlowIdentifier identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, flow, 1); identifier.setType(EntityType.FLOW); System.out.println(String.format("Changing number of flowlet instances for flowlet %s " + "in flow %s of application %s ", flowlet, flow, application)); client.setInstances(dummyAuthToken, identifier, flowlet, flowletInstances); System.out.println("The number of flowlet instances has been changed."); return; } if ("promote".equals(command)) { System.out.println("Promoting to the cloud..."); ResourceIdentifier identifier = new ResourceIdentifier(DEVELOPER_ACCOUNT_ID, application, "noresource", 1); boolean status = client.promote(new AuthToken(authToken), identifier, hostname); if (status) { System.out.println("Promoted to cloud"); } else { System.out.println("Promote to cloud failed"); } } if ("status".equals(command)) { AuthToken dummyAuthToken = new AuthToken("ReactorClient"); FlowIdentifier identifier; if (flow != null) { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, flow, 1); identifier.setType(EntityType.FLOW); System.out.println(String.format("Getting status for flow %s in application %s ", flow, application)); } else { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, procedure, 1); identifier.setType(EntityType.QUERY); System.out.println(String.format("Getting status for procedure %s in application %s ", flow, application)); } FlowStatus flowStatus = client.status(dummyAuthToken, identifier); Preconditions.checkNotNull(flowStatus, "Problem getting the status the application"); System.out.println(String.format("Status: %s", flowStatus.toString())); } } finally { transport.close(); } } /** * Parses the provided command. */ String parseArguments(String[] args, CConfiguration config) { configuration = config; if (args.length == 0) { // command line arguments are missing usage(true); // usage method throws new UsageException() when called with true! } command = args[0]; if ("help".equals(command)) { usage(false); return "help"; } if (!AVAILABLE_COMMANDS.contains(command)) { usage(false); System.out.println(String.format("Unsupported command: %s", command)); return "help"; } CommandLineParser commandLineParser = new GnuParser(); Options options = new Options(); options.addOption("a", APPLICATION_LONG_OPT_ARG, true, "Application Id."); options.addOption("r", ARCHIVE_LONG_OPT_ARG, true, "Archive that contains the application."); options.addOption("p", PROCEDURE_LONG_OPT_ARG, true, "Procedure Id."); options.addOption("h", HOSTNAME_LONG_OPT_ARG, true, "Hostname to push the application to."); options.addOption("k", APIKEY_LONG_OPT_ARG, true, "Apikey of the account."); options.addOption("f", FLOW_LONG_OPT_ARG, true, "Flow Id."); options.addOption("l", FLOWLET_LONG_OPT_ARG, true, "Flowlet Id."); options.addOption("i", FLOWLET_INSTANCES_LONG_OPT_ARG, true, "Flowlet Instances."); options.addOption("m", MAPREDUCE_LONG_OPT_ARG, true, "MapReduce job Id."); options.addOption("d", DEBUG_LONG_OPT_ARG, false, "Debug"); try { CommandLine commandLine = commandLineParser.parse(options, Arrays.copyOfRange(args, 1, args.length)); debug = commandLine.getOptionValue(DEBUG_LONG_OPT_ARG) == null ? false : true; //Check if the appropriate args are passed in for each of the commands if ("deploy".equals(command)) { Preconditions.checkArgument(commandLine.hasOption(ARCHIVE_LONG_OPT_ARG), "deploy command should have archive argument"); resource = commandLine.getOptionValue(ARCHIVE_LONG_OPT_ARG); } else if ("delete".equals(command)) { Preconditions.checkArgument(commandLine.hasOption(APPLICATION_LONG_OPT_ARG), "status command should have " + "application argument"); application = commandLine.getOptionValue(APPLICATION_LONG_OPT_ARG); } else if ("start".equals(command)) { Preconditions.checkArgument(commandLine.hasOption(APPLICATION_LONG_OPT_ARG), "status command should have " + "application argument"); Preconditions.checkArgument(commandLine.hasOption(PROCEDURE_LONG_OPT_ARG) || commandLine.hasOption(FLOW_LONG_OPT_ARG) || commandLine.hasOption(MAPREDUCE_LONG_OPT_ARG), "start command should have procedure or flow or mapreduce argument"); application = commandLine.getOptionValue(APPLICATION_LONG_OPT_ARG); procedure = commandLine.getOptionValue(PROCEDURE_LONG_OPT_ARG); flow = commandLine.getOptionValue(FLOW_LONG_OPT_ARG); mapReduce = commandLine.getOptionValue(MAPREDUCE_LONG_OPT_ARG); } else if ("stop".equals(command)) { Preconditions.checkArgument(commandLine.hasOption(APPLICATION_LONG_OPT_ARG), "status command should have " + "application argument"); Preconditions.checkArgument(commandLine.hasOption(PROCEDURE_LONG_OPT_ARG) || commandLine.hasOption(FLOW_LONG_OPT_ARG) || commandLine.hasOption(MAPREDUCE_LONG_OPT_ARG), "stop command should have procedure or flow or mapreduce argument"); application = commandLine.getOptionValue(APPLICATION_LONG_OPT_ARG); procedure = commandLine.getOptionValue(PROCEDURE_LONG_OPT_ARG); flow = commandLine.getOptionValue(FLOW_LONG_OPT_ARG); mapReduce = commandLine.getOptionValue(MAPREDUCE_LONG_OPT_ARG); } else if ("status".equals(command)) { Preconditions.checkArgument(commandLine.hasOption(APPLICATION_LONG_OPT_ARG), "status command should have " + "application argument"); Preconditions.checkArgument(commandLine.hasOption(PROCEDURE_LONG_OPT_ARG) || commandLine.hasOption(FLOW_LONG_OPT_ARG) || commandLine.hasOption(MAPREDUCE_LONG_OPT_ARG), "status command should have procedure or flow or mapreduce argument"); application = commandLine.getOptionValue(APPLICATION_LONG_OPT_ARG); procedure = commandLine.getOptionValue(PROCEDURE_LONG_OPT_ARG); flow = commandLine.getOptionValue(FLOW_LONG_OPT_ARG); mapReduce = commandLine.getOptionValue(MAPREDUCE_LONG_OPT_ARG); } else if ("scale".equals(command)) { Preconditions.checkArgument(commandLine.hasOption(APPLICATION_LONG_OPT_ARG), "status command should have " + "application argument"); Preconditions.checkArgument(commandLine.hasOption(FLOW_LONG_OPT_ARG), "status command should have flow argument"); Preconditions.checkArgument(commandLine.hasOption(FLOWLET_LONG_OPT_ARG), "status command should have flowlet argument"); Preconditions.checkArgument(commandLine.hasOption(FLOWLET_INSTANCES_LONG_OPT_ARG), "status command should have number of flowlet instances argument"); application = commandLine.getOptionValue(APPLICATION_LONG_OPT_ARG); flow = commandLine.getOptionValue(FLOW_LONG_OPT_ARG); flowlet = commandLine.getOptionValue(FLOWLET_LONG_OPT_ARG); flowletInstances = Short.parseShort(commandLine.getOptionValue(FLOWLET_INSTANCES_LONG_OPT_ARG)); Preconditions.checkArgument(flowletInstances > 0, "number of flowlet instances needs to be greater than 0"); } else if ("promote".equals(command)) { Preconditions.checkArgument(commandLine.hasOption(HOSTNAME_LONG_OPT_ARG), "promote command should have" + "vpc argument"); Preconditions.checkArgument(commandLine.hasOption(APIKEY_LONG_OPT_ARG), "promote command should " + "have auth token argument"); Preconditions.checkArgument(commandLine.hasOption(APPLICATION_LONG_OPT_ARG), "promote command should have" + " application argument"); hostname = commandLine.getOptionValue(HOSTNAME_LONG_OPT_ARG); authToken = commandLine.getOptionValue(APIKEY_LONG_OPT_ARG); application = commandLine.getOptionValue(APPLICATION_LONG_OPT_ARG); } } catch (ParseException e) { usage(e.getMessage()); } catch (IllegalArgumentException e) { usage(e.getMessage()); } return command; } /** * This is actually the main method for this client, but in order to make it testable, * instead of exiting in case of error it returns null, whereas in case of success it * returns the executed command. * * @param args the command line arguments of the main method * @param config The configuration of the gateway * @return null in case of error, a String representing the executed command * in case of success */ String execute(String[] args, CConfiguration config) { String command; try { command = parseArguments(args, config); } catch (UsageException e) { if (debug) { // this is mainly for debugging the unit test System.err.println("Exception for arguments: " + Arrays.toString(args) + ". Exception: " + e); e.printStackTrace(System.err); } return null; } try { executeInternal(); } catch (Exception e) { System.err.println(String.format("Caught Exception while running %s ", command)); System.err.println(String.format("Error: %s", e.getMessage())); return null; } return command; } public static void main(String[] args) throws TException, AppFabricServiceException { // create a config and load the gateway properties CConfiguration config = CConfiguration.create(); // create a data client and run it with the given arguments ReactorClient instance = new ReactorClient(); String value = instance.execute(args, config); // exit with error in case fails if (value == null) { System.exit(1); } } private void deploy(AppFabricService.Client client) throws IOException, TException, AppFabricServiceException, InterruptedException { File file = new File(resource); AuthToken dummyAuthToken = new AuthToken("ReactorClient"); System.out.println(String.format("Deploying... :%s", resource)); ResourceIdentifier identifier = client.init(dummyAuthToken, new ResourceInfo(DEVELOPER_ACCOUNT_ID, "", file.getName(), (int) file.getTotalSpace(), file.lastModified())); Preconditions.checkNotNull(identifier, "Resource identifier is null"); BufferFileInputStream is = new BufferFileInputStream(file.getAbsolutePath(), 100 * 1024); try { while (true) { byte[] toSubmit = is.read(); if (toSubmit.length == 0) { break; } client.chunk(dummyAuthToken, identifier, ByteBuffer.wrap(toSubmit)); } } finally { is.close(); } client.deploy(dummyAuthToken, identifier); TimeUnit.SECONDS.sleep(5); DeploymentStatus status = client.dstatus(dummyAuthToken, identifier); if (DeployStatus.DEPLOYED.getCode() == status.getOverall()) { System.out.println("Deployed"); } else if (DeployStatus.FAILED.getCode() == status.getOverall()) { System.out.println(String.format("Deployment failed: %s. Check Reactor log file for more details.", DeployStatus.FAILED.getMessage())); } else { System.out.println("Deployment taking more than 5 seconds. Please check the Reactor Dashboard for status"); } return; } }
app-fabric/src/main/java/com/continuuity/app/services/ReactorClient.java
/* * Copyright 2012-2013 Continuuity,Inc. All Rights Reserved. */ package com.continuuity.app.services; import com.continuuity.common.conf.CConfiguration; import com.continuuity.common.conf.Constants; import com.continuuity.common.utils.Copyright; import com.continuuity.common.utils.UsageException; import com.continuuity.internal.app.BufferFileInputStream; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Client for interacting with Local Reactor's app-fabric service to perform the following operations: * a) Deploy app * b) Start/Stop/Status of flow, procedure or map reduce job * c) Promote app to cloud * d) Scale number of flowlet instances * <p/> * Usage: * ReactorClient client = new ReactorClient(); * client.execute(args, CConfiguration.create()); */ public final class ReactorClient { /** * For debugging purposes, should only be set to true in unit tests. * When true, program will print the stack trace after the usage. */ public static boolean debug = false; private static final String DEVELOPER_ACCOUNT_ID = Constants.DEVELOPER_ACCOUNT_ID; private static final Set<String> AVAILABLE_COMMANDS = Sets.newHashSet("deploy", "stop", "start", "help", "promote", "status", "scale", "delete"); private static final String ARCHIVE_LONG_OPT_ARG = "archive"; private static final String APPLICATION_LONG_OPT_ARG = "application"; private static final String PROCEDURE_LONG_OPT_ARG = "procedure"; private static final String FLOW_LONG_OPT_ARG = "flow"; private static final String FLOWLET_LONG_OPT_ARG = "flowlet"; private static final String FLOWLET_INSTANCES_LONG_OPT_ARG = "instances"; private static final String MAPREDUCE_LONG_OPT_ARG = "mapreduce"; private static final String HOSTNAME_LONG_OPT_ARG = "host"; private static final String APIKEY_LONG_OPT_ARG = "apikey"; private static final String DEBUG_LONG_OPT_ARG = "debug"; private String resource; private String application; private String procedure; private String flow; private String flowlet; private short flowletInstances; private String mapReduce; private String hostname; private String authToken; private String command; private CConfiguration configuration; String getCommand() { return command; } /** * Prints the usage information and throws a UsageException if error is true. */ private void usage(boolean error) { PrintStream out; if (error) { out = System.err; } else { out = System.out; } Copyright.print(out); out.println("Usage:"); out.println(" reactor-client deploy --archive <filename>"); out.println(" reactor-client start --application <id> ( --flow <id> | --procedure <id> | --mapreduce <id>)"); out.println(" reactor-client stop --application <id> ( --flow <id> | --procedure <id> | --mapreduce <id>)"); out.println(" reactor-client status --application <id> ( --flow <id> | --procedure <id> | --mapreduce <id>)"); out.println(" reactor-client scale --application <id> --flow <id> --flowlet <id> --instances <number>"); out.println(" reactor-client promote --application <id> --host <hostname> --apikey <key>"); out.println(" reactor-client delete --application <id>"); out.println(" reactor-client help"); out.println("Options:"); out.println(" --archive <filename> \t Archive containing the application."); out.println(" --application <id> \t Application Id."); out.println(" --flow <id> \t\t Flow id of the application."); out.println(" --procedure <id> \t Procedure of in the application."); out.println(" --mapreduce <id> \t MapReduce job of in the application."); out.println(" --host <hostname> \t Hostname to push the application to."); out.println(" --apikey <key> \t Apikey of the account."); if (error) { throw new UsageException(); } } /** * Prints an error message followed by the usage information. * * @param errorMessage the error message */ private void usage(String errorMessage) { if (errorMessage != null) { System.err.println("Error: " + errorMessage); } usage(true); } /** * Executes the configured operation */ private void executeInternal() throws TException, InterruptedException, AppFabricServiceException, IOException { Preconditions.checkNotNull(command, "App client is not configured to run"); Preconditions.checkNotNull(configuration, "App client configuration is not set"); String address = "localhost"; int port = configuration.getInt(Constants.CFG_APP_FABRIC_SERVER_PORT, Constants.DEFAULT_APP_FABRIC_SERVER_PORT); TTransport transport = null; TProtocol protocol; try { transport = new TFramedTransport(new TSocket(address, port)); protocol = new TBinaryProtocol(transport); transport.open(); AppFabricService.Client client = new AppFabricService.Client(protocol); if ("deploy".equals(command)) { System.out.println("Deploying the app..."); deploy(client); } if ("delete".equals(command)) { System.out.println("Deleting the app..."); AuthToken dummyAuthToken = new AuthToken("ReactorClient"); client.removeApplication(dummyAuthToken, new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, "", 1)); System.out.println("Deleted."); } if ("start".equals(command)) { System.out.println("Starting..."); AuthToken dummyAuthToken = new AuthToken("ReactorClient"); FlowIdentifier identifier; if (flow != null) { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, flow, 1); identifier.setType(EntityType.FLOW); System.out.println(String.format("Starting flow %s for application %s ", flow, application)); } else if (mapReduce != null) { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, mapReduce, 1); identifier.setType(EntityType.MAPREDUCE); System.out.println(String.format("Starting mapreduce job %s for application %s ", mapReduce, application)); } else { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, procedure, 1); identifier.setType(EntityType.QUERY); System.out.println(String.format("Starting procedure %s for application %s ", procedure, application)); } client.start(dummyAuthToken, new FlowDescriptor(identifier, ImmutableMap.<String, String>of())); System.out.println("Started "); return; } if ("stop".equals(command)) { System.out.println("Stopping..."); AuthToken dummyAuthToken = new AuthToken("ReactorClient"); FlowIdentifier identifier; if (flow != null) { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, flow, 1); identifier.setType(EntityType.FLOW); System.out.println(String.format("Stopping flow %s for application %s ", flow, application)); } else if (mapReduce != null) { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, mapReduce, 1); identifier.setType(EntityType.MAPREDUCE); System.out.println(String.format("Killing mapreduce job %s for application %s ", mapReduce, application)); } else { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, procedure, 1); identifier.setType(EntityType.QUERY); System.out.println(String.format("Stopping procedure %s for application %s ", procedure, application)); } client.stop(dummyAuthToken, identifier); System.out.println("Stopped "); return; } if ("scale".equals(command)) { System.out.println("Scaling..."); AuthToken dummyAuthToken = new AuthToken("ReactorClient"); FlowIdentifier identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, flow, 1); identifier.setType(EntityType.FLOW); System.out.println(String.format("Changing number of flowlet instances for flowlet %s " + "in flow %s of application %s ", flowlet, flow, application)); client.setInstances(dummyAuthToken, identifier, flowlet, flowletInstances); System.out.println("The number of flowlet instances has been changed."); return; } if ("promote".equals(command)) { System.out.println("Promoting to the cloud..."); ResourceIdentifier identifier = new ResourceIdentifier(DEVELOPER_ACCOUNT_ID, application, "noresource", 1); boolean status = client.promote(new AuthToken(authToken), identifier, hostname); if (status) { System.out.println("Promoted to cloud"); } else { System.out.println("Promote to cloud failed"); } } if ("status".equals(command)) { AuthToken dummyAuthToken = new AuthToken("ReactorClient"); FlowIdentifier identifier; if (flow != null) { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, flow, 1); identifier.setType(EntityType.FLOW); System.out.println(String.format("Getting status for flow %s in application %s ", flow, application)); } else { identifier = new FlowIdentifier(DEVELOPER_ACCOUNT_ID, application, procedure, 1); identifier.setType(EntityType.QUERY); System.out.println(String.format("Getting status for procedure %s in application %s ", flow, application)); } FlowStatus flowStatus = client.status(dummyAuthToken, identifier); Preconditions.checkNotNull(flowStatus, "Problem getting the status the application"); System.out.println(String.format("Status: %s", flowStatus.toString())); } } finally { transport.close(); } } /** * Parses the provided command. */ String parseArguments(String[] args, CConfiguration config) { configuration = config; if (args.length == 0) { // command line arguments are missing usage(true); // usage method throws new UsageException() when called with true! } command = args[0]; if ("help".equals(command)) { usage(false); return "help"; } if (!AVAILABLE_COMMANDS.contains(command)) { usage(true); System.out.println(String.format("Unsupported command: %s", command)); return "help"; } CommandLineParser commandLineParser = new GnuParser(); Options options = new Options(); options.addOption("a", APPLICATION_LONG_OPT_ARG, true, "Application Id."); options.addOption("r", ARCHIVE_LONG_OPT_ARG, true, "Archive that contains the application."); options.addOption("p", PROCEDURE_LONG_OPT_ARG, true, "Procedure Id."); options.addOption("h", HOSTNAME_LONG_OPT_ARG, true, "Hostname to push the application to."); options.addOption("k", APIKEY_LONG_OPT_ARG, true, "Apikey of the account."); options.addOption("f", FLOW_LONG_OPT_ARG, true, "Flow Id."); options.addOption("l", FLOWLET_LONG_OPT_ARG, true, "Flowlet Id."); options.addOption("i", FLOWLET_INSTANCES_LONG_OPT_ARG, true, "Flowlet Instances."); options.addOption("m", MAPREDUCE_LONG_OPT_ARG, true, "MapReduce job Id."); options.addOption("d", DEBUG_LONG_OPT_ARG, false, "Debug"); try { CommandLine commandLine = commandLineParser.parse(options, Arrays.copyOfRange(args, 1, args.length)); debug = commandLine.getOptionValue(DEBUG_LONG_OPT_ARG) == null ? false : true; //Check if the appropriate args are passed in for each of the commands if ("deploy".equals(command)) { Preconditions.checkArgument(commandLine.hasOption(ARCHIVE_LONG_OPT_ARG), "deploy command should have archive argument"); resource = commandLine.getOptionValue(ARCHIVE_LONG_OPT_ARG); } else if ("delete".equals(command)) { Preconditions.checkArgument(commandLine.hasOption(APPLICATION_LONG_OPT_ARG), "status command should have " + "application argument"); application = commandLine.getOptionValue(APPLICATION_LONG_OPT_ARG); } else if ("start".equals(command)) { Preconditions.checkArgument(commandLine.hasOption(APPLICATION_LONG_OPT_ARG), "status command should have " + "application argument"); Preconditions.checkArgument(commandLine.hasOption(PROCEDURE_LONG_OPT_ARG) || commandLine.hasOption(FLOW_LONG_OPT_ARG) || commandLine.hasOption(MAPREDUCE_LONG_OPT_ARG), "start command should have procedure or flow or mapreduce argument"); application = commandLine.getOptionValue(APPLICATION_LONG_OPT_ARG); procedure = commandLine.getOptionValue(PROCEDURE_LONG_OPT_ARG); flow = commandLine.getOptionValue(FLOW_LONG_OPT_ARG); mapReduce = commandLine.getOptionValue(MAPREDUCE_LONG_OPT_ARG); } else if ("stop".equals(command)) { Preconditions.checkArgument(commandLine.hasOption(APPLICATION_LONG_OPT_ARG), "status command should have " + "application argument"); Preconditions.checkArgument(commandLine.hasOption(PROCEDURE_LONG_OPT_ARG) || commandLine.hasOption(FLOW_LONG_OPT_ARG) || commandLine.hasOption(MAPREDUCE_LONG_OPT_ARG), "stop command should have procedure or flow or mapreduce argument"); application = commandLine.getOptionValue(APPLICATION_LONG_OPT_ARG); procedure = commandLine.getOptionValue(PROCEDURE_LONG_OPT_ARG); flow = commandLine.getOptionValue(FLOW_LONG_OPT_ARG); mapReduce = commandLine.getOptionValue(MAPREDUCE_LONG_OPT_ARG); } else if ("status".equals(command)) { Preconditions.checkArgument(commandLine.hasOption(APPLICATION_LONG_OPT_ARG), "status command should have " + "application argument"); Preconditions.checkArgument(commandLine.hasOption(PROCEDURE_LONG_OPT_ARG) || commandLine.hasOption(FLOW_LONG_OPT_ARG) || commandLine.hasOption(MAPREDUCE_LONG_OPT_ARG), "status command should have procedure or flow or mapreduce argument"); application = commandLine.getOptionValue(APPLICATION_LONG_OPT_ARG); procedure = commandLine.getOptionValue(PROCEDURE_LONG_OPT_ARG); flow = commandLine.getOptionValue(FLOW_LONG_OPT_ARG); mapReduce = commandLine.getOptionValue(MAPREDUCE_LONG_OPT_ARG); } else if ("scale".equals(command)) { Preconditions.checkArgument(commandLine.hasOption(APPLICATION_LONG_OPT_ARG), "status command should have " + "application argument"); Preconditions.checkArgument(commandLine.hasOption(FLOW_LONG_OPT_ARG), "status command should have flow argument"); Preconditions.checkArgument(commandLine.hasOption(FLOWLET_LONG_OPT_ARG), "status command should have flowlet argument"); Preconditions.checkArgument(commandLine.hasOption(FLOWLET_INSTANCES_LONG_OPT_ARG), "status command should have number of flowlet instances argument"); application = commandLine.getOptionValue(APPLICATION_LONG_OPT_ARG); flow = commandLine.getOptionValue(FLOW_LONG_OPT_ARG); flowlet = commandLine.getOptionValue(FLOWLET_LONG_OPT_ARG); flowletInstances = Short.parseShort(commandLine.getOptionValue(FLOWLET_INSTANCES_LONG_OPT_ARG)); Preconditions.checkArgument(flowletInstances > 0, "number of flowlet instances needs to be greater than 0"); } else if ("promote".equals(command)) { Preconditions.checkArgument(commandLine.hasOption(HOSTNAME_LONG_OPT_ARG), "promote command should have" + "vpc argument"); Preconditions.checkArgument(commandLine.hasOption(APIKEY_LONG_OPT_ARG), "promote command should " + "have auth token argument"); Preconditions.checkArgument(commandLine.hasOption(APPLICATION_LONG_OPT_ARG), "promote command should have" + " application argument"); hostname = commandLine.getOptionValue(HOSTNAME_LONG_OPT_ARG); authToken = commandLine.getOptionValue(APIKEY_LONG_OPT_ARG); application = commandLine.getOptionValue(APPLICATION_LONG_OPT_ARG); } } catch (ParseException e) { usage(e.getMessage()); } catch (IllegalArgumentException e) { usage(e.getMessage()); } return command; } /** * This is actually the main method for this client, but in order to make it testable, * instead of exiting in case of error it returns null, whereas in case of success it * returns the executed command. * * @param args the command line arguments of the main method * @param config The configuration of the gateway * @return null in case of error, a String representing the executed command * in case of success */ String execute(String[] args, CConfiguration config) { String command; try { command = parseArguments(args, config); } catch (UsageException e) { if (debug) { // this is mainly for debugging the unit test System.err.println("Exception for arguments: " + Arrays.toString(args) + ". Exception: " + e); e.printStackTrace(System.err); } return null; } try { executeInternal(); } catch (Exception e) { System.err.println(String.format("Caught Exception while running %s ", command)); System.err.println(String.format("Error: %s", e.getMessage())); return null; } return command; } public static void main(String[] args) throws TException, AppFabricServiceException { // create a config and load the gateway properties CConfiguration config = CConfiguration.create(); // create a data client and run it with the given arguments ReactorClient instance = new ReactorClient(); String value = instance.execute(args, config); // exit with error in case fails if (value == null) { System.exit(1); } } private void deploy(AppFabricService.Client client) throws IOException, TException, AppFabricServiceException, InterruptedException { File file = new File(resource); AuthToken dummyAuthToken = new AuthToken("ReactorClient"); System.out.println(String.format("Deploying... :%s", resource)); ResourceIdentifier identifier = client.init(dummyAuthToken, new ResourceInfo(DEVELOPER_ACCOUNT_ID, "", file.getName(), (int) file.getTotalSpace(), file.lastModified())); Preconditions.checkNotNull(identifier, "Resource identifier is null"); BufferFileInputStream is = new BufferFileInputStream(file.getAbsolutePath(), 100 * 1024); try { while (true) { byte[] toSubmit = is.read(); if (toSubmit.length == 0) { break; } client.chunk(dummyAuthToken, identifier, ByteBuffer.wrap(toSubmit)); } } finally { is.close(); } client.deploy(dummyAuthToken, identifier); TimeUnit.SECONDS.sleep(5); DeploymentStatus status = client.dstatus(dummyAuthToken, identifier); if (DeployStatus.DEPLOYED.getCode() == status.getOverall()) { System.out.println("Deployed"); } else if (DeployStatus.FAILED.getCode() == status.getOverall()) { System.out.println(String.format("Deployment failed: %s. Check Reactor log file for more details.", DeployStatus.FAILED.getMessage())); } else { System.out.println("Deployment taking more than 5 seconds. Please check the Reactor Dashboard for status"); } return; } }
Port reactor client flush changes to release-1.6.0
app-fabric/src/main/java/com/continuuity/app/services/ReactorClient.java
Port reactor client flush changes to release-1.6.0
<ide><path>pp-fabric/src/main/java/com/continuuity/app/services/ReactorClient.java <ide> out.println(" --mapreduce <id> \t MapReduce job of in the application."); <ide> out.println(" --host <hostname> \t Hostname to push the application to."); <ide> out.println(" --apikey <key> \t Apikey of the account."); <add> out.flush(); <ide> if (error) { <ide> throw new UsageException(); <ide> } <ide> } <ide> <ide> if (!AVAILABLE_COMMANDS.contains(command)) { <del> usage(true); <add> usage(false); <ide> System.out.println(String.format("Unsupported command: %s", command)); <ide> return "help"; <ide> }
Java
mit
2495976ac56c131ed4299ec30341de48d9eae404
0
kenzierocks/SpongeCommon,ryantheleach/SpongeCommon,clienthax/SpongeCommon,SpongePowered/SpongeCommon,modwizcode/SpongeCommon,sanman00/SpongeCommon,SpongePowered/Sponge,SpongePowered/Sponge,kashike/SpongeCommon,ryantheleach/SpongeCommon,JBYoshi/SpongeCommon,Grinch/SpongeCommon,DDoS/SpongeCommon,modwizcode/SpongeCommon,sanman00/SpongeCommon,RTLSponge/SpongeCommon,hsyyid/SpongeCommon,JBYoshi/SpongeCommon,kenzierocks/SpongeCommon,DDoS/SpongeCommon,hsyyid/SpongeCommon,Grinch/SpongeCommon,SpongePowered/Sponge,SpongePowered/SpongeCommon,clienthax/SpongeCommon,RTLSponge/SpongeCommon,kashike/SpongeCommon
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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 org.spongepowered.common.mixin.core.block.tiles; import static com.google.common.base.Preconditions.checkNotNull; import net.minecraft.block.BlockJukebox; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemRecord; import org.spongepowered.api.block.tileentity.Jukebox; import org.spongepowered.api.data.manipulator.DataManipulator; import org.spongepowered.api.data.manipulator.mutable.RepresentedItemData; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import java.util.List; import java.util.Optional; @Mixin(BlockJukebox.TileEntityJukebox.class) public abstract class MixinTileEntityJukebox extends MixinTileEntity implements Jukebox { @Shadow public abstract net.minecraft.item.ItemStack getRecord(); @Shadow public abstract void setRecord(net.minecraft.item.ItemStack recordStack); @Override public void playRecord() { if (getRecord() != null) { this.worldObj.playAuxSFXAtEntity(null, 1005, this.pos, Item.getIdFromItem(getRecord().getItem())); } } @Override public void ejectRecord() { IBlockState block = this.worldObj.getBlockState(this.pos); if (block.getBlock() == Blocks.jukebox) { ((BlockJukebox) block.getBlock()).dropRecord(this.worldObj, this.pos, block); this.worldObj.setBlockState(this.pos, block.withProperty(BlockJukebox.HAS_RECORD, false), 2); } } @Override public void insertRecord(ItemStack record) { net.minecraft.item.ItemStack itemStack = (net.minecraft.item.ItemStack) checkNotNull(record, "record"); if (!(itemStack.getItem() instanceof ItemRecord)) { return; } IBlockState block = this.worldObj.getBlockState(this.pos); if (block.getBlock() == Blocks.jukebox) { // Don't use BlockJukebox#insertRecord - it looses item data this.setRecord(itemStack); this.worldObj.setBlockState(this.pos, block.withProperty(BlockJukebox.HAS_RECORD, true), 2); } } @Override public void supplyVanillaManipulators(List<DataManipulator<?, ?>> manipulators) { super.supplyVanillaManipulators(manipulators); Optional<RepresentedItemData> recordItemData = get(RepresentedItemData.class); if (recordItemData.isPresent()) { manipulators.add(recordItemData.get()); } } }
src/main/java/org/spongepowered/common/mixin/core/block/tiles/MixinTileEntityJukebox.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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 org.spongepowered.common.mixin.core.block.tiles; import static com.google.common.base.Preconditions.checkNotNull; import net.minecraft.block.BlockJukebox; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemRecord; import org.spongepowered.api.block.tileentity.Jukebox; import org.spongepowered.api.data.manipulator.DataManipulator; import org.spongepowered.api.data.manipulator.mutable.RepresentedItemData; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import java.util.List; import java.util.Optional; @Mixin(BlockJukebox.TileEntityJukebox.class) public abstract class MixinTileEntityJukebox extends MixinTileEntity implements Jukebox { @Shadow public abstract net.minecraft.item.ItemStack getRecord(); @Shadow public abstract void setRecord(net.minecraft.item.ItemStack recordStack); @Override public void playRecord() { if (getRecord() != null) { this.worldObj.playAuxSFXAtEntity(null, 1005, this.pos, Item.getIdFromItem(getRecord().getItem())); } } @Override public void ejectRecord() { IBlockState block = this.worldObj.getBlockState(this.pos); if (block.getBlock() == Blocks.jukebox) { ((BlockJukebox) block.getBlock()).dropRecord(this.worldObj, this.pos, block); this.worldObj.setBlockState(this.pos, block.withProperty(BlockJukebox.HAS_RECORD, false), 2); } } @Override public void insertRecord(ItemStack record) { net.minecraft.item.ItemStack itemStack = (net.minecraft.item.ItemStack) checkNotNull(record, "record"); if (!(itemStack.getItem() instanceof ItemRecord)) { return; } IBlockState block = this.worldObj.getBlockState(this.pos); if (block.getBlock() == Blocks.jukebox) { ((BlockJukebox) block.getBlock()).insertRecord(this.worldObj, this.pos, block, itemStack); } } @Override public void supplyVanillaManipulators(List<DataManipulator<?, ?>> manipulators) { super.supplyVanillaManipulators(manipulators); Optional<RepresentedItemData> recordItemData = get(RepresentedItemData.class); if (recordItemData.isPresent()) { manipulators.add(recordItemData.get()); } } }
Fix inserting record into jukebox not keeping itemstack data
src/main/java/org/spongepowered/common/mixin/core/block/tiles/MixinTileEntityJukebox.java
Fix inserting record into jukebox not keeping itemstack data
<ide><path>rc/main/java/org/spongepowered/common/mixin/core/block/tiles/MixinTileEntityJukebox.java <ide> } <ide> IBlockState block = this.worldObj.getBlockState(this.pos); <ide> if (block.getBlock() == Blocks.jukebox) { <del> ((BlockJukebox) block.getBlock()).insertRecord(this.worldObj, this.pos, block, itemStack); <add> // Don't use BlockJukebox#insertRecord - it looses item data <add> this.setRecord(itemStack); <add> this.worldObj.setBlockState(this.pos, block.withProperty(BlockJukebox.HAS_RECORD, true), 2); <ide> } <ide> } <ide>
Java
apache-2.0
a33ebe9ca4aee1274bff80e547af204a5cdb5715
0
rangadi/beam,manuzhang/incubator-beam,markflyhigh/incubator-beam,chamikaramj/beam,dhananjaypatkar/DataflowJavaSDK,apache/beam,manuzhang/beam,apache/beam,rangadi/beam,jbonofre/beam,charlesccychen/beam,xsm110/Apache-Beam,dhananjaypatkar/DataflowJavaSDK,wtanaka/beam,lukecwik/incubator-beam,rangadi/beam,xsm110/Apache-Beam,lukecwik/incubator-beam,apache/beam,lukecwik/incubator-beam,lukecwik/incubator-beam,vikkyrk/incubator-beam,charlesccychen/beam,smarthi/DataflowJavaSDK,wangyum/beam,smarthi/DataflowJavaSDK,markflyhigh/incubator-beam,RyanSkraba/beam,joshualitt/incubator-beam,lukecwik/incubator-beam,chamikaramj/beam,rangadi/incubator-beam,josauder/AOP_incubator_beam,staslev/incubator-beam,tgroh/incubator-beam,dhalperi/incubator-beam,yk5/beam,yk5/beam,jasonkuster/beam,tweise/incubator-beam,staslev/beam,vikkyrk/incubator-beam,tgroh/beam,amitsela/incubator-beam,amarouni/incubator-beam,rangadi/incubator-beam,RyanSkraba/beam,amarouni/incubator-beam,charlesccychen/incubator-beam,peihe/incubator-beam,chamikaramj/beam,chamikaramj/beam,jbonofre/incubator-beam,wangyum/beam,sureshjosh/DataflowJavaSDK,robertwb/incubator-beam,eljefe6a/incubator-beam,sammcveety/DataflowJavaSDK,robertwb/incubator-beam,wtanaka/beam,staslev/incubator-beam,PieterDM/DataflowJavaSDK,chamikaramj/beam,rangadi/beam,ravwojdyla/incubator-beam,jasonkuster/beam,amitsela/beam,chamikaramj/beam,charlesccychen/beam,tgroh/beam,joshualitt/incubator-beam,jasonkuster/incubator-beam,robertwb/incubator-beam,dhalperi/incubator-beam,ahartley39/DataflowJavaSDK,markflyhigh/incubator-beam,markflyhigh/incubator-beam,tgroh/incubator-beam,charlesccychen/beam,lukecwik/incubator-beam,apache/beam,tweise/incubator-beam,charlesccychen/beam,lukecwik/incubator-beam,tyagihas/DataflowJavaSDK,jbonofre/incubator-beam,tgroh/beam,joshualitt/DataflowJavaSDK,apache/beam,apache/beam,sureshjosh/DataflowJavaSDK,RyanSkraba/beam,wtanaka/beam,RyanSkraba/beam,manuzhang/beam,robertwb/incubator-beam,prabeesh/DataflowJavaSDK,chamikaramj/beam,apache/beam,tweise/beam,vikkyrk/incubator-beam,prabeesh/DataflowJavaSDK,elibixby/DataflowJavaSDK,Test-Betta-Inc/musical-umbrella,charlesccychen/beam,manuzhang/incubator-beam,apache/beam,apache/beam,jbonofre/beam,sammcveety/DataflowJavaSDK,robertwb/incubator-beam,tgroh/beam,markflyhigh/incubator-beam,wangyum/beam,robertwb/incubator-beam,elibixby/DataflowJavaSDK,charlesccychen/incubator-beam,apache/beam,yk5/beam,iemejia/incubator-beam,staslev/beam,robertwb/incubator-beam,josauder/AOP_incubator_beam,dhalperi/beam,rangadi/beam,jasonkuster/incubator-beam,apache/beam,rangadi/beam,tweise/beam,nevillelyh/DataflowJavaSDK,Test-Betta-Inc/musical-umbrella,PieterDM/DataflowJavaSDK,rangadi/incubator-beam,RyanSkraba/beam,chamikaramj/incubator-beam,dhalperi/beam,peihe/incubator-beam,amitsela/beam,sammcveety/incubator-beam,joshualitt/DataflowJavaSDK,eljefe6a/incubator-beam,amitsela/beam,markflyhigh/incubator-beam,peihe/DataflowJavaSDK,sammcveety/incubator-beam,robertwb/incubator-beam,mxm/incubator-beam,tyagihas/DataflowJavaSDK,amitsela/incubator-beam,chamikaramj/beam,eljefe6a/incubator-beam,jbonofre/beam,manuzhang/beam,lukecwik/incubator-beam,chamikaramj/incubator-beam,peihe/DataflowJavaSDK,staslev/beam,charlesccychen/beam,charlesccychen/incubator-beam,markflyhigh/incubator-beam,sammcveety/incubator-beam,RyanSkraba/beam,lukecwik/incubator-beam,chamikaramj/beam,jbonofre/beam,jasonkuster/beam,chamikaramj/beam,ravwojdyla/incubator-beam,ahartley39/DataflowJavaSDK,robertwb/incubator-beam,iemejia/incubator-beam,robertwb/incubator-beam,ravwojdyla/incubator-beam,peihe/incubator-beam,lukecwik/incubator-beam,xsm110/Apache-Beam,dhalperi/beam,RyanSkraba/beam,wangyum/beam,rangadi/beam,mxm/incubator-beam
/******************************************************************************* * Copyright (C) 2015 Google 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 com.google.cloud.dataflow.sdk.util.common.worker; import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.util.common.Counter; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for the {@link Counter} API. */ @RunWith(JUnit4.class) public class StateSamplerTest { public static long getCounterLongValue(CounterSet counters, String name) { @SuppressWarnings("unchecked") Counter<Long> counter = (Counter<Long>) counters.getExistingCounter(name); return counter.getAggregate(); } @Test public void basicTest() throws InterruptedException { CounterSet counters = new CounterSet(); long periodMs = 50; StateSampler stateSampler = new StateSampler("test-", counters.getAddCounterMutator(), periodMs); int state1 = stateSampler.stateForName("1"); int state2 = stateSampler.stateForName("2"); try (StateSampler.ScopedState s1 = stateSampler.scopedState(state1)) { assert s1 != null; Thread.sleep(2 * periodMs); } try (StateSampler.ScopedState s2 = stateSampler.scopedState(state2)) { assert s2 != null; Thread.sleep(3 * periodMs); } long s1 = getCounterLongValue(counters, "test-1-msecs"); long s2 = getCounterLongValue(counters, "test-2-msecs"); long toleranceMs = periodMs; assertTrue(s1 + s2 >= 4 * periodMs - toleranceMs); assertTrue(s1 + s2 <= 10 * periodMs + toleranceMs); stateSampler.close(); } @Test public void nestingTest() throws InterruptedException { CounterSet counters = new CounterSet(); long periodMs = 50; StateSampler stateSampler = new StateSampler("test-", counters.getAddCounterMutator(), periodMs); int state1 = stateSampler.stateForName("1"); int state2 = stateSampler.stateForName("2"); int state3 = stateSampler.stateForName("3"); try (StateSampler.ScopedState s1 = stateSampler.scopedState(state1)) { assert s1 != null; Thread.sleep(2 * periodMs); try (StateSampler.ScopedState s2 = stateSampler.scopedState(state2)) { assert s2 != null; Thread.sleep(2 * periodMs); try (StateSampler.ScopedState s3 = stateSampler.scopedState(state3)) { assert s3 != null; Thread.sleep(2 * periodMs); } Thread.sleep(periodMs); } Thread.sleep(periodMs); } long s1 = getCounterLongValue(counters, "test-1-msecs"); long s2 = getCounterLongValue(counters, "test-2-msecs"); long s3 = getCounterLongValue(counters, "test-3-msecs"); long toleranceMs = periodMs; assertTrue(s1 + s2 + s3 >= 4 * periodMs - toleranceMs); assertTrue(s1 + s2 + s3 <= 16 * periodMs + toleranceMs); stateSampler.close(); } @Test public void nonScopedTest() throws InterruptedException { CounterSet counters = new CounterSet(); long periodMs = 50; StateSampler stateSampler = new StateSampler("test-", counters.getAddCounterMutator(), periodMs); int state1 = stateSampler.stateForName("1"); int previousState = stateSampler.setState(state1); Thread.sleep(2 * periodMs); stateSampler.setState(previousState); long tolerance = periodMs; long s = getCounterLongValue(counters, "test-1-msecs"); assertTrue(s >= periodMs - tolerance); assertTrue(s <= 4 * periodMs + tolerance); stateSampler.close(); } }
sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSamplerTest.java
/******************************************************************************* * Copyright (C) 2015 Google 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 com.google.cloud.dataflow.sdk.util.common.worker; import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.util.common.Counter; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for the {@link Counter} API. */ @RunWith(JUnit4.class) public class StateSamplerTest { public static long getCounterLongValue(CounterSet counters, String name) { Counter<Long> counter = (Counter<Long>) counters.getExistingCounter(name); return counter.getAggregate(); } @Test public void basicTest() throws InterruptedException { CounterSet counters = new CounterSet(); long periodMs = 50; StateSampler stateSampler = new StateSampler("test-", counters.getAddCounterMutator(), periodMs); int state1 = stateSampler.stateForName("1"); int state2 = stateSampler.stateForName("2"); try (StateSampler.ScopedState s1 = stateSampler.scopedState(state1)) { assert s1 != null; Thread.sleep(2 * periodMs); } try (StateSampler.ScopedState s2 = stateSampler.scopedState(state2)) { assert s2 != null; Thread.sleep(3 * periodMs); } long s1 = getCounterLongValue(counters, "test-1-msecs"); long s2 = getCounterLongValue(counters, "test-2-msecs"); System.out.println("basic s1: " + s1); System.out.println("basic s2: " + s2); long toleranceMs = periodMs; assertTrue(s1 + s2 >= 4 * periodMs - toleranceMs); assertTrue(s1 + s2 <= 10 * periodMs + toleranceMs); } @Test public void nestingTest() throws InterruptedException { CounterSet counters = new CounterSet(); long periodMs = 50; StateSampler stateSampler = new StateSampler("test-", counters.getAddCounterMutator(), periodMs); int state1 = stateSampler.stateForName("1"); int state2 = stateSampler.stateForName("2"); int state3 = stateSampler.stateForName("3"); try (StateSampler.ScopedState s1 = stateSampler.scopedState(state1)) { assert s1 != null; Thread.sleep(2 * periodMs); try (StateSampler.ScopedState s2 = stateSampler.scopedState(state2)) { assert s2 != null; Thread.sleep(2 * periodMs); try (StateSampler.ScopedState s3 = stateSampler.scopedState(state3)) { assert s3 != null; Thread.sleep(2 * periodMs); } Thread.sleep(periodMs); } Thread.sleep(periodMs); } long s1 = getCounterLongValue(counters, "test-1-msecs"); long s2 = getCounterLongValue(counters, "test-2-msecs"); long s3 = getCounterLongValue(counters, "test-3-msecs"); System.out.println("s1: " + s1); System.out.println("s2: " + s2); System.out.println("s3: " + s3); long toleranceMs = periodMs; assertTrue(s1 + s2 + s3 >= 4 * periodMs - toleranceMs); assertTrue(s1 + s2 + s3 <= 16 * periodMs + toleranceMs); } @Test public void nonScopedTest() throws InterruptedException { CounterSet counters = new CounterSet(); long periodMs = 50; StateSampler stateSampler = new StateSampler("test-", counters.getAddCounterMutator(), periodMs); int state1 = stateSampler.stateForName("1"); int previousState = stateSampler.setState(state1); Thread.sleep(2 * periodMs); stateSampler.setState(previousState); long tolerance = periodMs; long s = getCounterLongValue(counters, "test-1-msecs"); System.out.println("s: " + s); assertTrue(s >= periodMs - tolerance); assertTrue(s <= 4 * periodMs + tolerance); } }
Remove System.out.println from StateSamplerTest ----Release Notes---- [] ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=99079456
sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSamplerTest.java
Remove System.out.println from StateSamplerTest
<ide><path>dk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSamplerTest.java <ide> @RunWith(JUnit4.class) <ide> public class StateSamplerTest { <ide> public static long getCounterLongValue(CounterSet counters, String name) { <add> @SuppressWarnings("unchecked") <ide> Counter<Long> counter = (Counter<Long>) counters.getExistingCounter(name); <ide> return counter.getAggregate(); <ide> } <ide> long s1 = getCounterLongValue(counters, "test-1-msecs"); <ide> long s2 = getCounterLongValue(counters, "test-2-msecs"); <ide> <del> System.out.println("basic s1: " + s1); <del> System.out.println("basic s2: " + s2); <del> <ide> long toleranceMs = periodMs; <ide> assertTrue(s1 + s2 >= 4 * periodMs - toleranceMs); <ide> assertTrue(s1 + s2 <= 10 * periodMs + toleranceMs); <add> <add> stateSampler.close(); <ide> } <ide> <ide> @Test <ide> long s2 = getCounterLongValue(counters, "test-2-msecs"); <ide> long s3 = getCounterLongValue(counters, "test-3-msecs"); <ide> <del> System.out.println("s1: " + s1); <del> System.out.println("s2: " + s2); <del> System.out.println("s3: " + s3); <del> <ide> long toleranceMs = periodMs; <ide> assertTrue(s1 + s2 + s3 >= 4 * periodMs - toleranceMs); <ide> assertTrue(s1 + s2 + s3 <= 16 * periodMs + toleranceMs); <add> <add> stateSampler.close(); <ide> } <ide> <ide> @Test <ide> stateSampler.setState(previousState); <ide> long tolerance = periodMs; <ide> long s = getCounterLongValue(counters, "test-1-msecs"); <del> System.out.println("s: " + s); <add> <ide> assertTrue(s >= periodMs - tolerance); <ide> assertTrue(s <= 4 * periodMs + tolerance); <add> <add> stateSampler.close(); <ide> } <ide> }
JavaScript
apache-2.0
7a68171ef865c852cbbbb77c15dfd7c32a162986
0
imurchie/hb-workshop,imurchie/hb-workshop
var fs = require('fs'); module.exports = function (config) { // Use ENV vars on Travis and sauce.json locally to get credentials if (!process.env.SAUCE_USERNAME) { if (!fs.existsSync('sauce.json')) { console.log('Create a sauce.json with your credentials based on the sauce-sample.json file.'); process.exit(1); } else { process.env.SAUCE_USERNAME = require('./sauce').username; process.env.SAUCE_ACCESS_KEY = require('./sauce').accessKey; } } // Browsers to run on Sauce Labs var customLaunchers = { 'SL_Chrome': { base: 'SauceLabs', platform: 'Windows 7', browserName: 'chrome', version: '35' }, 'SL_IOS_SAFARI': { base: 'SauceLabs', platform: 'OS X 10.10', browserName: 'iphone', version: '7.1' }, 'SL_IE': { base: 'SauceLabs', browserName: 'internet explorer', version: '9' } }; config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'src/**/*.js', 'test/**/*.js' ], // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'saucelabs'], // web server port port: 9876, colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, sauceLabs: { testName: 'HackBright Karma and Sauce Labs demo', }, captureTimeout: 120000, customLaunchers: customLaunchers, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: Object.keys(customLaunchers), singleRun: true }); };
sauce.karma.conf.js
var fs = require('fs'); module.exports = function (config) { // Use ENV vars on Travis and sauce.json locally to get credentials if (!process.env.SAUCE_USERNAME) { if (!fs.existsSync('sauce.json')) { console.log('Create a sauce.json with your credentials based on the sauce-sample.json file.'); process.exit(1); } else { process.env.SAUCE_USERNAME = require('./sauce').username; process.env.SAUCE_ACCESS_KEY = require('./sauce').accessKey; } } // Browsers to run on Sauce Labs var customLaunchers = { 'SL_Chrome': { base: 'SauceLabs', browserName: 'chrome' }, 'SL_IE': { base: 'SauceLabs', browserName: 'internet explorer', version: '9' } }; config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'src/**/*.js', 'test/**/*.js' ], // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'saucelabs'], // web server port port: 9876, colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, sauceLabs: { testName: 'HackBright Karma and Sauce Labs demo' }, captureTimeout: 120000, customLaunchers: customLaunchers, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: Object.keys(customLaunchers), singleRun: true }); };
Add ios safari
sauce.karma.conf.js
Add ios safari
<ide><path>auce.karma.conf.js <ide> var customLaunchers = { <ide> 'SL_Chrome': { <ide> base: 'SauceLabs', <del> browserName: 'chrome' <add> platform: 'Windows 7', <add> browserName: 'chrome', <add> version: '35' <add> }, <add> 'SL_IOS_SAFARI': { <add> base: 'SauceLabs', <add> platform: 'OS X 10.10', <add> browserName: 'iphone', <add> version: '7.1' <ide> }, <ide> 'SL_IE': { <ide> base: 'SauceLabs', <ide> logLevel: config.LOG_INFO, <ide> <ide> sauceLabs: { <del> testName: 'HackBright Karma and Sauce Labs demo' <add> testName: 'HackBright Karma and Sauce Labs demo', <ide> }, <ide> captureTimeout: 120000, <ide> customLaunchers: customLaunchers,
Java
apache-2.0
e193bde7d75273a3272f264c42514f49a691658f
0
eayun/ovirt-engine,walteryang47/ovirt-engine,walteryang47/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,halober/ovirt-engine,halober/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,eayun/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,halober/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,halober/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine
package org.ovirt.engine.core.bll; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.bll.utils.PermissionSubject; import org.ovirt.engine.core.bll.utils.VmDeviceUtils; import org.ovirt.engine.core.common.VdcObjectType; import org.ovirt.engine.core.common.action.AttachDettachVmDiskParameters; import org.ovirt.engine.core.common.action.CloneVmParameters; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.businessentities.Disk; import org.ovirt.engine.core.common.businessentities.DiskImage; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.VmDevice; import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType; import org.ovirt.engine.core.common.businessentities.VmStatic; import org.ovirt.engine.core.common.businessentities.VmWatchdog; import org.ovirt.engine.core.common.errors.VdcBllMessages; import org.ovirt.engine.core.common.locks.LockingGroup; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryReturnValue; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.utils.VmDeviceType; import org.ovirt.engine.core.compat.Guid; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; @DisableInPrepareMode @LockIdNameAttribute(isReleaseAtEndOfExecute = false) @NonTransactiveCommandAttribute(forceCompensation = true) public class CloneVmCommand<T extends CloneVmParameters> extends AddVmAndCloneImageCommand<T> { private Collection<DiskImage> diskImagesFromConfiguration; private Guid oldVmId; private VM vm; private VM sourceVm; public CloneVmCommand(T parameters) { super(parameters); oldVmId = getParameters().getVmId(); setVmName(getParameters().getVm().getName()); // init the parameters only at first instantiation (not subsequent for end action) if (Guid.isNullOrEmpty(parameters.getNewVmGuid())) { setupParameters(); } } @Override protected void logErrorOneOrMoreActiveDomainsAreMissing() { log.errorFormat("Can not found any default active domain for one of the disks of snapshot with id : {0}", oldVmId); } @Override protected Guid getStoragePoolIdFromSourceImageContainer() { return getVm().getStoragePoolId(); } @Override protected Map<String, Pair<String, String>> getSharedLocks() { Map<String, Pair<String, String>> locks = new HashMap<>(); for (DiskImage image: getImagesToCheckDestinationStorageDomains()) { locks.put(image.getId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.DISK, getDiskSharedLockMessage())); } locks.put(getSourceVmFromDb().getId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_BEING_CLONED)); return locks; } protected Collection<DiskImage> getDiskImagesFromConfiguration() { VdcQueryReturnValue vdcReturnValue = getBackend().runInternalQuery( VdcQueryType.GetAllDisksByVmId, new IdQueryParameters(oldVmId)); List<Disk> loadedImages = vdcReturnValue.getReturnValue() != null ? (List<Disk>) vdcReturnValue.getReturnValue() : new ArrayList<Disk>(); if (diskImagesFromConfiguration == null) { diskImagesFromConfiguration = ImagesHandler.filterImageDisks(loadedImages, false, true, true); } return diskImagesFromConfiguration; } @Override public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); jobProperties.put(VdcObjectType.VM.name().toLowerCase(), StringUtils.defaultString(getParameters().getNewName())); } return jobProperties; } @Override protected Guid getSourceVmId() { return oldVmId; } protected VM getVmFromConfiguration() { return getVm(); } protected VM getSourceVmFromDb() { if (sourceVm == null) { sourceVm = getVmDAO().get(oldVmId); } return sourceVm; } @Override public VM getVm() { if (vm == null) { vm = getVmDAO().get(oldVmId); VmDeviceUtils.setVmDevices(vm.getStaticData()); VmHandler.updateDisksFromDb(vm); VmHandler.updateVmGuestAgentVersion(vm); VmHandler.updateNetworkInterfacesFromDb(vm); VmHandler.updateVmInitFromDB(vm.getStaticData(), true); vm.setName(getParameters().getNewName()); vm.setId(getVmId()); } return vm; } private void fillDisksToParameters() { for (Disk image : getDiskImagesFromConfiguration()) { diskInfoDestinationMap.put(image.getId(), (DiskImage) image); } getParameters().setDiskInfoDestinationMap(diskInfoDestinationMap); } @Override protected void endSuccessfully() { super.endSuccessfully(); attachDisks(); } private void attachDisks() { VdcQueryReturnValue vdcReturnValue = getBackend().runInternalQuery( VdcQueryType.GetAllDisksByVmId, new IdQueryParameters(oldVmId)); List<Disk> loadedImages = vdcReturnValue.getReturnValue() != null ? (List<Disk>) vdcReturnValue.getReturnValue() : new ArrayList<Disk>(); for (Disk disk : loadedImages) { if (disk.getDiskStorageType() == Disk.DiskStorageType.LUN || disk.isShareable()) { attachDisk(disk); } } } private void attachDisk(Disk disk) { getBackend().runInternalAction( VdcActionType.AttachDiskToVm, new AttachDettachVmDiskParameters( getParameters().getNewVmGuid(), disk.getId(), disk.getPlugged(), disk.getReadOnly() ) ); } private void setupParameters() { setVmId(Guid.newGuid()); VM vmToClone = getVm(); getParameters().setNewVmGuid(getVmId()); getParameters().setVm(vmToClone); List<VmDevice> devices = getVmDeviceDao().getVmDeviceByVmId(oldVmId); getParameters().setSoundDeviceEnabled(containsDeviceWithType(devices, VmDeviceGeneralType.SOUND)); getParameters().setConsoleEnabled(containsDeviceWithType(devices, VmDeviceGeneralType.CONSOLE)); getParameters().setVirtioScsiEnabled(containsDeviceWithType(devices, VmDeviceGeneralType.CONTROLLER, VmDeviceType.VIRTIOSCSI)); getParameters().setBalloonEnabled(containsDeviceWithType(devices, VmDeviceGeneralType.BALLOON)); VdcQueryReturnValue watchdogs = getBackend().runInternalQuery(VdcQueryType.GetWatchdog, new IdQueryParameters(oldVmId)); if (!((List<VmWatchdog>) watchdogs.getReturnValue()).isEmpty()) { VmWatchdog watchdog = ((List<VmWatchdog>) watchdogs.getReturnValue()).iterator().next(); getParameters().setUpdateWatchdog(true); getParameters().setWatchdog(watchdog); } fillDisksToParameters(); } private boolean containsDeviceWithType(List<VmDevice> devices, VmDeviceGeneralType generalType, VmDeviceType deviceType) { for (VmDevice device : devices) { if (device.getType() == generalType) { if (deviceType == null || (deviceType.getName() != null && deviceType.getName().equals(device.getDevice()))) { return true; } } } return false; } private boolean containsDeviceWithType(List<VmDevice> devices, VmDeviceGeneralType type) { return containsDeviceWithType(devices, type, null); } @Override public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = new ArrayList<>(); permissionList.add(new PermissionSubject(getParameters().getVmId(), VdcObjectType.VM, getActionType().getActionGroup())); return permissionList; } @Override protected boolean canDoAction() { if (!(getSourceVmFromDb().getStatus() == VMStatus.Suspended || getSourceVmFromDb().isDown())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN); } return super.canDoAction(); } @Override protected void updateOriginalTemplate(VmStatic vmStatic) { vmStatic.setOriginalTemplateGuid(getVm().getOriginalTemplateGuid()); vmStatic.setOriginalTemplateName(getVm().getOriginalTemplateName()); } }
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/CloneVmCommand.java
package org.ovirt.engine.core.bll; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.bll.utils.PermissionSubject; import org.ovirt.engine.core.bll.utils.VmDeviceUtils; import org.ovirt.engine.core.common.VdcObjectType; import org.ovirt.engine.core.common.action.AttachDettachVmDiskParameters; import org.ovirt.engine.core.common.action.CloneVmParameters; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.businessentities.Disk; import org.ovirt.engine.core.common.businessentities.DiskImage; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.VmDevice; import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType; import org.ovirt.engine.core.common.businessentities.VmStatic; import org.ovirt.engine.core.common.businessentities.VmWatchdog; import org.ovirt.engine.core.common.errors.VdcBllMessages; import org.ovirt.engine.core.common.locks.LockingGroup; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryReturnValue; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.utils.VmDeviceType; import org.ovirt.engine.core.compat.Guid; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; @DisableInPrepareMode @LockIdNameAttribute(isReleaseAtEndOfExecute = false) @NonTransactiveCommandAttribute(forceCompensation = true) public class CloneVmCommand<T extends CloneVmParameters> extends AddVmAndCloneImageCommand<T> { private Collection<DiskImage> diskImagesFromConfiguration; private Guid oldVmId; private VM vm; private VM sourceVm; public CloneVmCommand(T parameters) { super(parameters); oldVmId = getParameters().getVmId(); setVmName(getParameters().getVm().getName()); // init the parameters only at first instantiation (not subsequent for end action) if (Guid.isNullOrEmpty(parameters.getNewVmGuid())) { setupParameters(); } } @Override protected void logErrorOneOrMoreActiveDomainsAreMissing() { log.errorFormat("Can not found any default active domain for one of the disks of snapshot with id : {0}", oldVmId); } @Override protected Guid getStoragePoolIdFromSourceImageContainer() { return getVm().getStoragePoolId(); } @Override protected Map<String, Pair<String, String>> getSharedLocks() { Map<String, Pair<String, String>> locks = new HashMap<>(); for (DiskImage image: getImagesToCheckDestinationStorageDomains()) { locks.put(image.getId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.DISK, getDiskSharedLockMessage())); } locks.put(getSourceVmFromDb().getId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_BEING_CLONED)); return locks; } protected Collection<DiskImage> getDiskImagesFromConfiguration() { VdcQueryReturnValue vdcReturnValue = getBackend().runInternalQuery( VdcQueryType.GetAllDisksByVmId, new IdQueryParameters(oldVmId)); List<Disk> loadedImages = vdcReturnValue.getReturnValue() != null ? (List<Disk>) vdcReturnValue.getReturnValue() : new ArrayList<Disk>(); if (diskImagesFromConfiguration == null) { diskImagesFromConfiguration = ImagesHandler.filterImageDisks(loadedImages, false, true, true); } return diskImagesFromConfiguration; } @Override public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); jobProperties.put(VdcObjectType.VM.name().toLowerCase(), StringUtils.defaultString(getParameters().getNewName())); } return jobProperties; } @Override protected Guid getSourceVmId() { return oldVmId; } protected VM getVmFromConfiguration() { return getVm(); } protected VM getSourceVmFromDb() { if (sourceVm == null) { sourceVm = getVmDAO().get(oldVmId); } return sourceVm; } @Override public VM getVm() { if (vm == null) { vm = getVmDAO().get(oldVmId); VmDeviceUtils.setVmDevices(vm.getStaticData()); VmHandler.updateDisksFromDb(vm); VmHandler.updateVmGuestAgentVersion(vm); VmHandler.updateNetworkInterfacesFromDb(vm); VmHandler.updateVmInitFromDB(vm.getStaticData(), true); vm.setName(getParameters().getNewName()); vm.setId(getVmId()); } return vm; } private void fillDisksToParameters() { for (Disk image : getDiskImagesFromConfiguration()) { diskInfoDestinationMap.put(image.getId(), (DiskImage) image); } getParameters().setDiskInfoDestinationMap(diskInfoDestinationMap); } @Override protected void endSuccessfully() { super.endSuccessfully(); attachDisks(); } private void attachDisks() { VdcQueryReturnValue vdcReturnValue = getBackend().runInternalQuery( VdcQueryType.GetAllDisksByVmId, new IdQueryParameters(oldVmId)); List<Disk> loadedImages = vdcReturnValue.getReturnValue() != null ? (List<Disk>) vdcReturnValue.getReturnValue() : new ArrayList<Disk>(); for (Disk disk : loadedImages) { if (disk.getDiskStorageType() == Disk.DiskStorageType.LUN || disk.isShareable()) { attachDisk(disk); } } } private void attachDisk(Disk disk) { getBackend().runInternalAction( VdcActionType.AttachDiskToVm, new AttachDettachVmDiskParameters( getParameters().getNewVmGuid(), disk.getId(), disk.getPlugged(), disk.getReadOnly() ) ); } private void setupParameters() { setVmId(Guid.newGuid()); VM vmToClone = getVm(); getParameters().setNewVmGuid(getVmId()); getParameters().setVm(vmToClone); List<VmDevice> devices = getVmDeviceDao().getVmDeviceByVmId(oldVmId); getParameters().setSoundDeviceEnabled(containsDeviceWithType(devices, VmDeviceGeneralType.SOUND)); getParameters().setConsoleEnabled(containsDeviceWithType(devices, VmDeviceGeneralType.CONSOLE)); getParameters().setVirtioScsiEnabled(containsDeviceWithType(devices, VmDeviceGeneralType.CONTROLLER, VmDeviceType.VIRTIOSCSI)); getParameters().setBalloonEnabled(containsDeviceWithType(devices, VmDeviceGeneralType.BALLOON)); VdcQueryReturnValue watchdogs = getBackend().runInternalQuery(VdcQueryType.GetWatchdog, new IdQueryParameters(oldVmId)); if (!((List<VmWatchdog>) watchdogs.getReturnValue()).isEmpty()) { VmWatchdog watchdog = ((List<VmWatchdog>) watchdogs.getReturnValue()).iterator().next(); getParameters().setUpdateWatchdog(true); getParameters().setWatchdog(watchdog); } fillDisksToParameters(); } private boolean containsDeviceWithType(List<VmDevice> devices, VmDeviceGeneralType generalType, VmDeviceType deviceType) { for (VmDevice device : devices) { if (device.getType() == generalType) { if (deviceType == null || deviceType.equals(device.getDevice())) { return true; } } } return false; } private boolean containsDeviceWithType(List<VmDevice> devices, VmDeviceGeneralType type) { return containsDeviceWithType(devices, type, null); } @Override public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = new ArrayList<>(); permissionList.add(new PermissionSubject(getParameters().getVmId(), VdcObjectType.VM, getActionType().getActionGroup())); return permissionList; } @Override protected boolean canDoAction() { if (!(getSourceVmFromDb().getStatus() == VMStatus.Suspended || getSourceVmFromDb().isDown())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN); } return super.canDoAction(); } @Override protected void updateOriginalTemplate(VmStatic vmStatic) { vmStatic.setOriginalTemplateGuid(getVm().getOriginalTemplateGuid()); vmStatic.setOriginalTemplateName(getVm().getOriginalTemplateName()); } }
engine: Fixed findbugs issue It was a comparision of VmDeviceType and String using the equals which did never pass. Fixed by correctly comparing the Strings Change-Id: If587c985360b54a5fed6e72dbee2bf9c21487a33 Signed-off-by: Tomas Jelinek <[email protected]>
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/CloneVmCommand.java
engine: Fixed findbugs issue
<ide><path>ackend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/CloneVmCommand.java <ide> private boolean containsDeviceWithType(List<VmDevice> devices, VmDeviceGeneralType generalType, VmDeviceType deviceType) { <ide> for (VmDevice device : devices) { <ide> if (device.getType() == generalType) { <del> if (deviceType == null || deviceType.equals(device.getDevice())) { <add> if (deviceType == null || (deviceType.getName() != null && deviceType.getName().equals(device.getDevice()))) { <ide> return true; <ide> } <ide> }
Java
agpl-3.0
42704ea13c780802ad82b0350d1d3a7e413b1db6
0
opencadc/core,opencadc/core
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2016. (c) 2016. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * $Revision: 5 $ * ************************************************************************ */ package ca.nrc.cadc.xml; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.MissingResourceException; import org.apache.log4j.Logger; import org.jdom2.DefaultJDOMFactory; import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.JDOMFactory; import org.jdom2.input.SAXBuilder; import org.jdom2.input.sax.DefaultSAXHandlerFactory; import org.jdom2.input.sax.SAXHandlerFactory; import org.jdom2.input.sax.XMLReaderJDOMFactory; import org.jdom2.input.sax.XMLReaderSAX2Factory; /** * XmlUtil class for use with JDOM-2. * @author pdowler * */ public class XmlUtil { private static Logger log = Logger.getLogger(XmlUtil.class); public static final String PARSER = "org.apache.xerces.parsers.SAXParser"; private static final String GRAMMAR_POOL = "org.apache.xerces.parsers.XMLGrammarCachingConfiguration"; /** * Deprecated convenience method. * * @param reader * @return * @throws JDOMException * @throws IOException * @deprecated */ public static Document validateXML(Reader reader) throws JDOMException, IOException { return buildDocument(reader, null); } /** * Deprecated convenience method. * * @param reader * @param schemaMap * @return * @throws JDOMException * @throws IOException * @deprecated */ public static Document validateXML(Reader reader, Map<String, String> schemaMap) throws JDOMException, IOException { return buildDocument(reader, schemaMap); } /** * Convenience: build an XML Document from string without schema validation. * * @param xml * @return document * @throws IOException * @throws JDOMException */ public static Document buildDocument(String xml) throws JDOMException, IOException { return buildDocument(new StringReader(xml)); } /** * Convenience: build an XML document with schema validation against a single * schema. * * @param xml * @param schemaNamespace * @param schemaResourceFileName * @return document * @throws IOException * @throws JDOMException */ public static Document buildDocument(String xml, String schemaNamespace, String schemaResourceFileName) throws IOException, JDOMException { if (schemaNamespace == null || schemaResourceFileName == null) throw new IllegalArgumentException("schemaNamespace and schemaResourceFileName cannot be null"); Map<String, String> map = new HashMap<String, String>(); map.put(schemaNamespace, getResourceUrlString(schemaResourceFileName, XmlUtil.class)); return buildDocument(new StringReader(xml), map); } /** * Convenience: build an XML Document without schema validation. * * @param istream * @return document * @throws IOException * @throws JDOMException */ public static Document buildDocument(InputStream istream) throws JDOMException, IOException { return buildDocument(new InputStreamReader(istream), null); } /** * Convenience: build an XML Document without schema validation. * * @param reader * @return document * @throws IOException * @throws JDOMException */ public static Document buildDocument(Reader reader) throws JDOMException, IOException { return buildDocument(reader, null); } /** * Convenience: build an XML Document without schema validation. * * @param istream * @param schemaMap * @return document * @throws IOException * @throws JDOMException */ public static Document buildDocument(InputStream istream, Map<String, String> schemaMap) throws JDOMException, IOException { return buildDocument(new InputStreamReader(istream), schemaMap); } /** * Build an XML document with schema validation. The schemaMap argument contains * pairs of namespace:location (for each required schema). The normal practice in * OpenCADC libraries is to store schema files inside the jar files of the code * that calls this utility and to use the getResourceUrlString method to find * the URL at runtime. * * @param reader * @param schemaMap namespace:location map, null for no validation * @return document * @throws IOException * @throws JDOMException */ public static Document buildDocument(Reader reader, Map<String, String> schemaMap) throws IOException, JDOMException { SAXBuilder sb = createBuilder(schemaMap); return sb.build(reader); } /** * Create an XML Document builder using a SAX parser. * * @param schemaMap * @return document */ public static SAXBuilder createBuilder(Map<String, String> schemaMap) { boolean validate = (schemaMap != null && !schemaMap.isEmpty()); XMLReaderJDOMFactory rf = new XMLReaderSAX2Factory(validate, PARSER); SAXHandlerFactory sh = new DefaultSAXHandlerFactory(); JDOMFactory jf = new DefaultJDOMFactory(); boolean schemaVal = (schemaMap != null); String schemaResource; String space = " "; StringBuilder sbSchemaLocations = new StringBuilder(); if (schemaVal) { // force local xml and XMLSchema mapping schemaResource = XmlUtil.getResourceUrlString(W3CConstants.XML_SCHEMA, XmlUtil.class); schemaMap.put(W3CConstants.XML_NS_URI.toASCIIString(), schemaResource); schemaResource = XmlUtil.getResourceUrlString(W3CConstants.XSI_SCHEMA, XmlUtil.class); schemaMap.put(W3CConstants.XSI_NS_URI.toASCIIString(), schemaResource); log.debug("schemaMap.size(): " + schemaMap.size()); for (String schemaNSKey : schemaMap.keySet()) { schemaResource = (String) schemaMap.get(schemaNSKey); sbSchemaLocations.append(schemaNSKey).append(space).append(schemaResource).append(space); } // enable xerces grammar caching System.setProperty("org.apache.xerces.xni.parser.XMLParserConfiguration", GRAMMAR_POOL); } SAXBuilder builder = new SAXBuilder(rf, sh, jf); if (schemaVal) { builder.setFeature("http://xml.org/sax/features/validation", true); builder.setFeature("http://apache.org/xml/features/validation/schema", true); if (schemaMap.size() > 0) builder.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", sbSchemaLocations.toString()); } return builder; } /** * Get an URL to a schema file. This implementation finds the schema file using the ClassLoader * that loaded the argument class. * * @param resourceFileName * @param runningClass * @return */ public static String getResourceUrlString(String resourceFileName, Class<?> runningClass) { String rtn = null; URL url = runningClass.getClassLoader().getResource(resourceFileName); if (url == null) throw new MissingResourceException("Resource not found: " + resourceFileName, runningClass.getName(), resourceFileName); rtn = url.toString(); return rtn; } }
cadc-util/src/main/java/ca/nrc/cadc/xml/XmlUtil.java
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2016. (c) 2016. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * $Revision: 5 $ * ************************************************************************ */ package ca.nrc.cadc.xml; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.MissingResourceException; import org.apache.log4j.Logger; import org.jdom2.DefaultJDOMFactory; import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.JDOMFactory; import org.jdom2.input.SAXBuilder; import org.jdom2.input.sax.DefaultSAXHandlerFactory; import org.jdom2.input.sax.SAXHandlerFactory; import org.jdom2.input.sax.XMLReaderJDOMFactory; import org.jdom2.input.sax.XMLReaderSAX2Factory; /** * XmlUtil class for use with JDOM-2. * @author pdowler * */ public class XmlUtil { private static Logger log = Logger.getLogger(XmlUtil.class); public static final String PARSER = "org.apache.xerces.parsers.SAXParser"; private static final String GRAMMAR_POOL = "org.apache.xerces.parsers.XMLGrammarCachingConfiguration"; /** * Deprecated convenience method. * * @param reader * @return * @throws JDOMException * @throws IOException * @deprecated */ public static Document validateXML(Reader reader) throws JDOMException, IOException { return buildDocument(reader, null); } /** * Deprecated convenience method. * * @param reader * @param schemaMap * @return * @throws JDOMException * @throws IOException * @deprecated */ public static Document validateXML(Reader reader, Map<String, String> schemaMap) throws JDOMException, IOException { return buildDocument(reader, schemaMap); } /** * Convenience: build an XML Document from string without schema validation. * * @param xml * @return document * @throws IOException * @throws JDOMException */ public static Document buildDocument(String xml) throws JDOMException, IOException { return buildDocument(new StringReader(xml)); } /** * Convenience: build an XML document with schema validation against a single * schema. * * @param xml * @param schemaNamespace * @param schemaResourceFileName * @return document * @throws IOException * @throws JDOMException */ public static Document buildDocument(String xml, String schemaNamespace, String schemaResourceFileName) throws IOException, JDOMException { if (schemaNamespace == null || schemaResourceFileName == null) throw new IllegalArgumentException("schemaNamespace and schemaResourceFileName cannot be null"); Map<String, String> map = new HashMap<String, String>(); map.put(schemaNamespace, getResourceUrlString(schemaResourceFileName, XmlUtil.class)); return buildDocument(new StringReader(xml), map); } /** * Convenience: build an XML Document without schema validation. * * @param istream * @return document * @throws IOException * @throws JDOMException */ public static Document buildDocument(InputStream istream) throws JDOMException, IOException { return buildDocument(new InputStreamReader(istream), null); } /** * Convenience: build an XML Document without schema validation. * * @param reader * @return document * @throws IOException * @throws JDOMException */ public static Document buildDocument(Reader reader) throws JDOMException, IOException { return buildDocument(reader, null); } /** * Convenience: build an XML Document without schema validation. * * @param istream * @param schemaMap * @return document * @throws IOException * @throws JDOMException */ public static Document buildDocument(InputStream istream, Map<String, String> schemaMap) throws JDOMException, IOException { return buildDocument(new InputStreamReader(istream), schemaMap); } /** * Build an XML document with schema validation. The schemaMap argument contains * pairs of namespace:location (for each required schema). The normal practice in * OpenCADC libraries is to store schema files inside the jar files of the code * that calls this utility and to use the getResourceUrlString method to find * the URL at runtime. * * @param reader * @param schemaMap namespace:location map, null for no validation * @return document * @throws IOException * @throws JDOMException */ public static Document buildDocument(Reader reader, Map<String, String> schemaMap) throws IOException, JDOMException { SAXBuilder sb = createBuilder(schemaMap); return sb.build(reader); } /** * Create an XML Document builder using a SAX parser. * * @param schemaMap * @return document */ public static SAXBuilder createBuilder(Map<String, String> schemaMap) { boolean validate = (schemaMap != null && !schemaMap.isEmpty()); XMLReaderJDOMFactory rf = new XMLReaderSAX2Factory(validate, PARSER); SAXHandlerFactory sh = new DefaultSAXHandlerFactory(); JDOMFactory jf = new DefaultJDOMFactory(); boolean schemaVal = (schemaMap != null); String schemaResource; String space = " "; StringBuilder sbSchemaLocations = new StringBuilder(); if (schemaVal) { log.debug("schemaMap.size(): " + schemaMap.size()); for (String schemaNSKey : schemaMap.keySet()) { schemaResource = (String) schemaMap.get(schemaNSKey); sbSchemaLocations.append(schemaNSKey).append(space).append(schemaResource).append(space); } // xml schemaResource = XmlUtil.getResourceUrlString(W3CConstants.XML_SCHEMA, XmlUtil.class); sbSchemaLocations.append(W3CConstants.XML_NS_URI.toASCIIString()).append(space).append(schemaResource).append(space); // XMLSchema schemaResource = XmlUtil.getResourceUrlString(W3CConstants.XSI_SCHEMA, XmlUtil.class); sbSchemaLocations.append(W3CConstants.XSI_NS_URI.toASCIIString()).append(space).append(schemaResource).append(space); // enable xerces grammar caching System.setProperty("org.apache.xerces.xni.parser.XMLParserConfiguration", GRAMMAR_POOL); } SAXBuilder builder = new SAXBuilder(rf, sh, jf); if (schemaVal) { builder.setFeature("http://xml.org/sax/features/validation", true); builder.setFeature("http://apache.org/xml/features/validation/schema", true); if (schemaMap.size() > 0) builder.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", sbSchemaLocations.toString()); } return builder; } /** * Get an URL to a schema file. This implementation finds the schema file using the ClassLoader * that loaded the argument class. * * @param resourceFileName * @param runningClass * @return */ public static String getResourceUrlString(String resourceFileName, Class<?> runningClass) { String rtn = null; URL url = runningClass.getClassLoader().getResource(resourceFileName); if (url == null) throw new MissingResourceException("Resource not found: " + resourceFileName, runningClass.getName(), resourceFileName); rtn = url.toString(); return rtn; } }
force local copy of xml and XMLSchema xsd
cadc-util/src/main/java/ca/nrc/cadc/xml/XmlUtil.java
force local copy of xml and XMLSchema xsd
<ide><path>adc-util/src/main/java/ca/nrc/cadc/xml/XmlUtil.java <ide> StringBuilder sbSchemaLocations = new StringBuilder(); <ide> if (schemaVal) <ide> { <add> // force local xml and XMLSchema mapping <add> schemaResource = XmlUtil.getResourceUrlString(W3CConstants.XML_SCHEMA, XmlUtil.class); <add> schemaMap.put(W3CConstants.XML_NS_URI.toASCIIString(), schemaResource); <add> schemaResource = XmlUtil.getResourceUrlString(W3CConstants.XSI_SCHEMA, XmlUtil.class); <add> schemaMap.put(W3CConstants.XSI_NS_URI.toASCIIString(), schemaResource); <add> <ide> log.debug("schemaMap.size(): " + schemaMap.size()); <ide> for (String schemaNSKey : schemaMap.keySet()) <ide> { <ide> schemaResource = (String) schemaMap.get(schemaNSKey); <ide> sbSchemaLocations.append(schemaNSKey).append(space).append(schemaResource).append(space); <ide> } <del> // xml <del> schemaResource = XmlUtil.getResourceUrlString(W3CConstants.XML_SCHEMA, XmlUtil.class); <del> sbSchemaLocations.append(W3CConstants.XML_NS_URI.toASCIIString()).append(space).append(schemaResource).append(space); <del> <del> // XMLSchema <del> schemaResource = XmlUtil.getResourceUrlString(W3CConstants.XSI_SCHEMA, XmlUtil.class); <del> sbSchemaLocations.append(W3CConstants.XSI_NS_URI.toASCIIString()).append(space).append(schemaResource).append(space); <del> <ide> // enable xerces grammar caching <ide> System.setProperty("org.apache.xerces.xni.parser.XMLParserConfiguration", GRAMMAR_POOL); <ide> }
Java
apache-2.0
33d66dab953956e8af2102853d4599256b08b7ce
0
camunda-ci/docker-java,docker-java/docker-java,marcust/docker-java,MarcoLotz/docker-java,tourea/docker-java,DICE-UNC/docker-java,rockzeng/docker-java,DICE-UNC/docker-java,rohitkadam19/docker-java,292388900/docker-java,klesgidis/docker-java,llamahunter/docker-java,ollie314/docker-java,ndeloof/docker-java,tejksat/docker-java,292388900/docker-java,carlossg/docker-java,ndeloof/docker-java,vjuranek/docker-java,klesgidis/docker-java,tejksat/docker-java,sabre1041/docker-java,gesellix/docker-java,marcust/docker-java,tschoots/docker-java,jamesmarva/docker-java,tschoots/docker-java,signalfx/docker-java,magnayn/docker-java,metavige/docker-java,MarcoLotz/docker-java,vjuranek/docker-java,llamahunter/docker-java,ollie314/docker-java,gesellix/docker-java,tourea/docker-java,camunda-ci/docker-java,sabre1041/docker-java,docker-java/docker-java,jamesmarva/docker-java,carlossg/docker-java,rockzeng/docker-java,metavige/docker-java,rohitkadam19/docker-java,magnayn/docker-java,signalfx/docker-java
package com.github.dockerjava.core.command; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.InternalServerErrorException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.model.Image; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; /** * Start and stop a single container for testing. */ public class DockerfileFixture implements AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(DockerfileFixture.class); private final DockerClient dockerClient; private String directory; private String repository; private String containerId; public DockerfileFixture(DockerClient dockerClient, String directory) { this.dockerClient = dockerClient; this.directory = directory; } public void open() throws Exception { LOGGER.info("building {}", directory); dockerClient .buildImageCmd(new File("src/test/resources", directory)) .withNoCache() // remove alternatives, cause problems .exec() .close(); Image lastCreatedImage = dockerClient .listImagesCmd() .exec() .get(0); repository = lastCreatedImage .getRepoTags()[0]; LOGGER.info("created {} {}", lastCreatedImage.getId(), repository); containerId = dockerClient .createContainerCmd(lastCreatedImage.getId()) .exec() .getId(); LOGGER.info("starting {}", containerId); dockerClient .startContainerCmd(containerId) .exec(); } @Override public void close() throws Exception { if (containerId != null) { LOGGER.info("removing container {}", containerId); try { dockerClient .removeContainerCmd(containerId) .withForce() // stop too .exec(); } catch (NotFoundException | InternalServerErrorException ignored) { LOGGER.info("ignoring {}", ignored.getMessage()); } containerId = null; } if (repository != null) { LOGGER.info("removing repository {}", repository); try { dockerClient .removeImageCmd(repository) .withForce() .exec(); } catch (InternalServerErrorException e) { LOGGER.info("ignoring {}", e.getMessage()); } repository = null; } } public String getContainerId() { return containerId; } }
src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java
package com.github.dockerjava.core.command; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.InternalServerErrorException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.model.Image; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; /** * Start and stop a single container for testing. */ public class DockerfileFixture implements AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(DockerfileFixture.class); private final DockerClient dockerClient; private String directory; private String repository; private String containerId; public DockerfileFixture(DockerClient dockerClient, String directory) { this.dockerClient = dockerClient; this.directory = directory; } public void open() throws Exception { LOGGER.info("building {}", directory); dockerClient .buildImageCmd(new File("src/test/resources", directory)) .withNoCache() // remove alternatives, cause problems .exec() .close(); Image lastCreatedImage = dockerClient .listImagesCmd() .exec() .get(0); repository = lastCreatedImage .getRepoTags()[0]; LOGGER.info("created {} {}", lastCreatedImage.getId(), repository); containerId = dockerClient .createContainerCmd(lastCreatedImage.getId()) .exec() .getId(); LOGGER.info("starting {}", containerId); dockerClient .startContainerCmd(containerId) .exec(); } @Override public void close() throws Exception { if (containerId != null) { LOGGER.info("removing container {}", containerId); try { dockerClient .removeContainerCmd(containerId) .withForce() // stop too .exec(); } catch (NotFoundException ignored) { LOGGER.info("ignoring {}", ignored.getMessage()); } containerId = null; } if (repository != null) { LOGGER.info("removing repository {}", repository); try { dockerClient .removeImageCmd(repository) .withForce() .exec(); } catch (InternalServerErrorException e) { LOGGER.info("ignoring {}", e.getMessage()); } repository = null; } } public String getContainerId() { return containerId; } }
Ignore error when removing image (e.g. due to brtfs on CircleCI).
src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java
Ignore error when removing image (e.g. due to brtfs on CircleCI).
<ide><path>rc/test/java/com/github/dockerjava/core/command/DockerfileFixture.java <ide> .removeContainerCmd(containerId) <ide> .withForce() // stop too <ide> .exec(); <del> } catch (NotFoundException ignored) { <add> } catch (NotFoundException | InternalServerErrorException ignored) { <ide> LOGGER.info("ignoring {}", ignored.getMessage()); <ide> } <ide> containerId = null;
JavaScript
mit
55559219c9fac7535b82533be748a09a788f93fe
0
martindale/bitcore,bitjson/bitcore,bitjson/bitcore,martindale/bitcore,bitpay/bitcore,bitpay/bitcore,martindale/bitcore,troggy/bitcore-wallet-client,matiu/bitcore-wallet-client,dabura667/bitcore-wallet-client,bitpay/bitcore,bitjson/bitcore,bitpay/bitcore-wallet-client,bitjson/bitcore,nohea/alohacore-wallet-client,bitpay/bitcore,martindale/bitcore
/** @namespace Client.API */ 'use strict'; var _ = require('lodash'); var $ = require('preconditions').singleton(); var util = require('util'); var async = require('async'); var events = require('events'); var Bitcore = require('bitcore-lib'); var sjcl = require('sjcl'); var url = require('url'); var querystring = require('querystring'); var Stringify = require('json-stable-stringify'); var request; if (process && !process.browser) { request = require('request'); } else { request = require('browser-request'); } var Common = require('./common'); var Constants = Common.Constants; var Defaults = Common.Defaults; var Utils = Common.Utils; var PayPro = require('./paypro'); var log = require('./log'); var Credentials = require('./credentials'); var Verifier = require('./verifier'); var Package = require('../package.json'); var ClientError = require('./errors/clienterror'); var Errors = require('./errors/errordefinitions'); var BASE_URL = 'http://localhost:3232/bws/api'; /** * @desc ClientAPI constructor. * * @param {Object} opts * @constructor */ function API(opts) { opts = opts || {}; this.verbose = !!opts.verbose; this.request = opts.request || request; this.baseUrl = opts.baseUrl || BASE_URL; var parsedUrl = url.parse(this.baseUrl); this.basePath = parsedUrl.path; this.baseHost = parsedUrl.protocol + '//' + parsedUrl.host; this.payProHttp = null; // Only for testing this.doNotVerifyPayPro = opts.doNotVerifyPayPro; this.timeout = opts.timeout || 50000; if (this.verbose) { log.setLevel('debug'); } else { log.setLevel('info'); } }; util.inherits(API, events.EventEmitter); API.privateKeyEncryptionOpts = { iter: 10000 }; API.prototype.initNotifications = function(cb) { log.warn('DEPRECATED: use initialize() instead.'); this.initialize({}, cb); }; API.prototype.initialize = function(opts, cb) { $.checkState(this.credentials); var self = this; self._initNotifications(opts); return cb(); }; API.prototype.dispose = function(cb) { var self = this; self._disposeNotifications(); return cb(); }; API.prototype._fetchLatestNotifications = function(interval, cb) { var self = this; cb = cb || function() {}; var opts = { lastNotificationId: self.lastNotificationId, }; if (!self.lastNotificationId) { opts.timeSpan = interval; } self.getNotifications(opts, function(err, notifications) { if (err) { log.warn('Error receiving notifications.'); log.debug(err); return cb(err); } if (notifications.length > 0) { self.lastNotificationId = _.last(notifications).id; } _.each(notifications, function(notification) { self.emit('notification', notification); }); return cb(); }); }; API.prototype._initNotifications = function(opts) { var self = this; opts = opts || {}; var interval = opts.notificationIntervalSeconds || 5; self.notificationsIntervalId = setInterval(function() { self._fetchLatestNotifications(interval, function(err) { if (err) { if (err.code == 'NOT_FOUND' || err.code == 'NOT_AUTHORIZED') { self._disposeNotifications(); } } }); }, interval * 1000); }; API.prototype._disposeNotifications = function() { var self = this; if (self.notificationsIntervalId) { clearInterval(self.notificationsIntervalId); self.notificationsIntervalId = null; } }; /** * Reset notification polling with new interval * @memberof Client.API * @param {Numeric} notificationIntervalSeconds - use 0 to pause notifications */ API.prototype.setNotificationsInterval = function(notificationIntervalSeconds) { var self = this; self._disposeNotifications(); if (notificationIntervalSeconds > 0) { self._initNotifications({ notificationIntervalSeconds: notificationIntervalSeconds }); } }; /** * Encrypt a message * @private * @static * @memberof Client.API * @param {String} message * @param {String} encryptingKey */ API._encryptMessage = function(message, encryptingKey) { if (!message) return null; return Utils.encryptMessage(message, encryptingKey); }; /** * Decrypt a message * @private * @static * @memberof Client.API * @param {String} message * @param {String} encryptingKey */ API._decryptMessage = function(message, encryptingKey) { if (!message) return ''; try { return Utils.decryptMessage(message, encryptingKey); } catch (ex) { return '<ECANNOTDECRYPT>'; } }; /** * Decrypt text fields in transaction proposals * @private * @static * @memberof Client.API * @param {Array} txps * @param {String} encryptingKey */ API.prototype._processTxps = function(txps) { var self = this; if (!txps) return; var encryptingKey = self.credentials.sharedEncryptingKey; _.each([].concat(txps), function(txp) { txp.encryptedMessage = txp.message; txp.message = API._decryptMessage(txp.message, encryptingKey) || null; _.each(txp.actions, function(action) { action.comment = API._decryptMessage(action.comment, encryptingKey); // TODO get copayerName from Credentials -> copayerId to copayerName // action.copayerName = null; }); _.each(txp.outputs, function(output) { output.encryptedMessage = output.message; output.message = API._decryptMessage(output.message, encryptingKey) || null; }); txp.hasUnconfirmedInputs = _.any(txp.inputs, function(input) { return input.confirmations == 0; }); }); }; /** * Parse errors * @private * @static * @memberof Client.API * @param {Object} body */ API._parseError = function(body) { if (_.isString(body)) { try { body = JSON.parse(body); } catch (e) { body = { error: body }; } } var ret; if (body && body.code) { ret = new ClientError(body.code, body.message); } else { ret = { code: 'ERROR', error: body ? body.error : 'There was an unknown error processing the request', }; } log.error(ret); return ret; }; /** * Sign an HTTP request * @private * @static * @memberof Client.API * @param {String} method - The HTTP method * @param {String} url - The URL for the request * @param {Object} args - The arguments in case this is a POST/PUT request * @param {String} privKey - Private key to sign the request */ API._signRequest = function(method, url, args, privKey) { var message = [method.toLowerCase(), url, JSON.stringify(args)].join('|'); return Utils.signMessage(message, privKey); }; /** * Seed from random * * @param {Object} opts * @param {String} opts.network - default 'livenet' */ API.prototype.seedFromRandom = function(opts) { $.checkArgument(arguments.length <= 1, 'DEPRECATED: only 1 argument accepted.'); $.checkArgument(_.isUndefined(opts) || _.isObject(opts), 'DEPRECATED: argument should be an options object.'); opts = opts || {}; this.credentials = Credentials.create(opts.network || 'livenet'); }; /** * Seed from random with mnemonic * * @param {Object} opts * @param {String} opts.network - default 'livenet' * @param {String} opts.passphrase * @param {Number} opts.language - default 'en' * @param {Number} opts.account - default 0 */ API.prototype.seedFromRandomWithMnemonic = function(opts) { $.checkArgument(arguments.length <= 1, 'DEPRECATED: only 1 argument accepted.'); $.checkArgument(_.isUndefined(opts) || _.isObject(opts), 'DEPRECATED: argument should be an options object.'); opts = opts || {}; this.credentials = Credentials.createWithMnemonic(opts.network || 'livenet', opts.passphrase, opts.language || 'en', opts.account || 0); }; API.prototype.getMnemonic = function() { return this.credentials.getMnemonic(); }; API.prototype.mnemonicHasPassphrase = function() { return this.credentials.mnemonicHasPassphrase; }; API.prototype.clearMnemonic = function() { return this.credentials.clearMnemonic(); }; /** * Seed from extended private key * * @param {String} xPrivKey */ API.prototype.seedFromExtendedPrivateKey = function(xPrivKey) { this.credentials = Credentials.fromExtendedPrivateKey(xPrivKey); }; /** * Seed from Mnemonics (language autodetected) * Can throw an error if mnemonic is invalid * * @param {String} BIP39 words * @param {Object} opts * @param {String} opts.network - default 'livenet' * @param {String} opts.passphrase * @param {Number} opts.account - default 0 * @param {String} opts.derivationStrategy - default 'BIP44' */ API.prototype.seedFromMnemonic = function(words, opts) { $.checkArgument(_.isUndefined(opts) || _.isObject(opts), 'DEPRECATED: second argument should be an options object.'); opts = opts || {}; this.credentials = Credentials.fromMnemonic(opts.network || 'livenet', words, opts.passphrase, opts.account || 0, opts.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP44); }; /** * Seed from external wallet public key * * @param {String} xPubKey * @param {String} source - A name identifying the source of the xPrivKey (e.g. ledger, TREZOR, ...) * @param {String} entropySourceHex - A HEX string containing pseudo-random data, that can be deterministically derived from the xPrivKey, and should not be derived from xPubKey. * @param {Object} opts * @param {Number} opts.account - default 0 * @param {String} opts.derivationStrategy - default 'BIP44' */ API.prototype.seedFromExtendedPublicKey = function(xPubKey, source, entropySourceHex, opts) { $.checkArgument(_.isUndefined(opts) || _.isObject(opts)); opts = opts || {}; this.credentials = Credentials.fromExtendedPublicKey(xPubKey, source, entropySourceHex, opts.account || 0, opts.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP44); }; /** * Export wallet * * @param {Object} opts * @param {Boolean} opts.noSign */ API.prototype.export = function(opts) { $.checkState(this.credentials); opts = opts || {}; var output; var c = Credentials.fromObj(this.credentials); if (opts.noSign) { c.setNoSign(); } output = JSON.stringify(c.toObj()); return output; } /** * Import wallet * * @param {Object} str * @param {Object} opts * @param {String} opts.password If the source has the private key encrypted, the password * will be needed for derive credentials fields. */ API.prototype.import = function(str, opts) { opts = opts || {}; try { var credentials = Credentials.fromObj(JSON.parse(str)); this.credentials = credentials; } catch (ex) { throw Errors.INVALID_BACKUP; } }; API.prototype._import = function(cb) { $.checkState(this.credentials); var self = this; // First option, grab wallet info from BWS. self.openWallet(function(err, ret) { // it worked? if (!err) return cb(null, ret); // Is the error other than "copayer was not found"? || or no priv key. if (err.code != 'NOT_AUTHORIZED' || self.isPrivKeyExternal()) return cb(err); //Second option, lets try to add an access log.info('Copayer not found, trying to add access'); self.addAccess({}, function(err) { // it worked? if (!err) self.openWallet(cb); return cb(Errors.WALLET_DOES_NOT_EXIST) }); }); }; /** * Import from Mnemonics (language autodetected) * Can throw an error if mnemonic is invalid * * @param {String} BIP39 words * @param {Object} opts * @param {String} opts.network - default 'livenet' * @param {String} opts.passphrase * @param {Number} opts.account - default 0 * @param {String} opts.derivationStrategy - default 'BIP44' */ API.prototype.importFromMnemonic = function(words, opts, cb) { log.debug('Importing from 12 Words'); opts = opts || {}; try { this.credentials = Credentials.fromMnemonic(opts.network || 'livenet', words, opts.passphrase, opts.account || 0, opts.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP44); } catch (e) { log.info('Mnemonic error:', e); return cb(Errors.INVALID_BACKUP); }; this._import(cb); }; API.prototype.importFromExtendedPrivateKey = function(xPrivKey, cb) { log.debug('Importing from Extended Private Key'); try { this.credentials = Credentials.fromExtendedPrivateKey(xPrivKey); } catch (e) { log.info('xPriv error:', e); return cb(Errors.INVALID_BACKUP); }; this._import(cb); }; /** * Import from Extended Public Key * * @param {String} xPubKey * @param {String} source - A name identifying the source of the xPrivKey * @param {String} entropySourceHex - A HEX string containing pseudo-random data, that can be deterministically derived from the xPrivKey, and should not be derived from xPubKey. * @param {Object} opts * @param {Number} opts.account - default 0 * @param {String} opts.derivationStrategy - default 'BIP44' */ API.prototype.importFromExtendedPublicKey = function(xPubKey, source, entropySourceHex, opts, cb) { $.checkArgument(arguments.length == 5, "DEPRECATED: should receive 5 arguments"); $.checkArgument(_.isUndefined(opts) || _.isObject(opts)); $.shouldBeFunction(cb); opts = opts || {}; log.debug('Importing from Extended Private Key'); try { this.credentials = Credentials.fromExtendedPublicKey(xPubKey, source, entropySourceHex, opts.account || 0, opts.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP44); } catch (e) { log.info('xPriv error:', e); return cb(Errors.INVALID_BACKUP); }; this._import(cb); }; API.prototype.decryptBIP38PrivateKey = function(encryptedPrivateKeyBase58, passphrase, opts, cb) { var Bip38 = require('bip38'); var bip38 = new Bip38(); var privateKeyWif; try { privateKeyWif = bip38.decrypt(encryptedPrivateKeyBase58, passphrase); } catch (ex) { return cb(new Error('Could not decrypt BIP38 private key', ex)); } var privateKey = new Bitcore.PrivateKey(privateKeyWif); var address = privateKey.publicKey.toAddress().toString(); var addrBuff = new Buffer(address, 'ascii'); var actualChecksum = Bitcore.crypto.Hash.sha256sha256(addrBuff).toString('hex').substring(0, 8); var expectedChecksum = Bitcore.encoding.Base58Check.decode(encryptedPrivateKeyBase58).toString('hex').substring(6, 14); if (actualChecksum != expectedChecksum) return cb(new Error('Incorrect passphrase')); return cb(null, privateKeyWif); }; API.prototype.getBalanceFromPrivateKey = function(privateKey, cb) { var self = this; var privateKey = new Bitcore.PrivateKey(privateKey); var address = privateKey.publicKey.toAddress(); self.getUtxos({ addresses: address.toString(), }, function(err, utxos) { if (err) return cb(err); return cb(null, _.sum(utxos, 'satoshis')); }); }; API.prototype.buildTxFromPrivateKey = function(privateKey, destinationAddress, opts, cb) { var self = this; opts = opts || {}; var privateKey = new Bitcore.PrivateKey(privateKey); var address = privateKey.publicKey.toAddress(); async.waterfall([ function(next) { self.getUtxos({ addresses: address.toString(), }, function(err, utxos) { return next(err, utxos); }); }, function(utxos, next) { if (!_.isArray(utxos) || utxos.length == 0) return next(new Error('No utxos found')); var fee = opts.fee || 10000; var amount = _.sum(utxos, 'satoshis') - fee; if (amount <= 0) return next(Errors.INSUFFICIENT_FUNDS); var tx; try { var toAddress = Bitcore.Address.fromString(destinationAddress); tx = new Bitcore.Transaction() .from(utxos) .to(toAddress, amount) .fee(fee) .sign(privateKey); // Make sure the tx can be serialized tx.serialize(); } catch (ex) { log.error('Could not build transaction from private key', ex); return next(Errors.COULD_NOT_BUILD_TRANSACTION); } return next(null, tx); } ], cb); }; /** * Open a wallet and try to complete the public key ring. * * @param {Callback} cb - The callback that handles the response. It returns a flag indicating that the wallet is complete. * @fires API#walletCompleted */ API.prototype.openWallet = function(cb) { $.checkState(this.credentials); var self = this; if (self.credentials.isComplete() && self.credentials.hasWalletInfo()) return cb(null, true); self._doGetRequest('/v2/wallets/?includeExtendedInfo=1', function(err, ret) { if (err) return cb(err); var wallet = ret.wallet; if (wallet.status != 'complete') return cb(); if (self.credentials.walletPrivKey) { if (!Verifier.checkCopayers(self.credentials, wallet.copayers)) { return cb(Errors.SERVER_COMPROMISED); } } else { // this should only happends in AIR-GAPPED flows log.warn('Could not verify copayers key (missing wallet Private Key)'); } // Wallet was not complete. We are completing it. self.credentials.addPublicKeyRing(API._extractPublicKeyRing(wallet.copayers)); if (!self.credentials.hasWalletInfo()) { var me = _.find(wallet.copayers, { id: self.credentials.copayerId }); self.credentials.addWalletInfo(wallet.id, wallet.name, wallet.m, wallet.n, null, me.name); } self.emit('walletCompleted', wallet); self._processTxps(ret.pendingTxps); self._processCustomData(ret); return cb(null, ret); }); }; /** * Do an HTTP request * @private * * @param {Object} method * @param {String} url * @param {Object} args * @param {Callback} cb */ API.prototype._doRequest = function(method, url, args, cb) { $.checkState(this.credentials); var reqSignature; var key = args._requestPrivKey || this.credentials.requestPrivKey; if (key) { delete args['_requestPrivKey']; reqSignature = API._signRequest(method, url, args, key); } var absUrl = this.baseUrl + url; var args = { // relUrl: only for testing with `supertest` relUrl: this.basePath + url, headers: { 'x-identity': this.credentials.copayerId, 'x-signature': reqSignature, 'x-client-version': 'bwc-' + Package.version, }, method: method, url: absUrl, body: args, json: true, withCredentials: false, timeout: this.timeout, }; log.debug('Request Args', util.inspect(args, { depth: 10 })); this.request(args, function(err, res, body) { log.debug(util.inspect(body, { depth: 10 })); if (!res) { return cb({ code: 'CONNECTION_ERROR', }); } if (res.statusCode != 200) { if (res.statusCode == 404) return cb({ code: 'NOT_FOUND' }); if (!res.statusCode) return cb({ code: 'CONNECTION_ERROR', }); return cb(API._parseError(body)); } if (body === '{"error":"read ECONNRESET"}') return cb(JSON.parse(body)); return cb(null, body, res.header); }); }; /** * Do a POST request * @private * * @param {String} url * @param {Object} args * @param {Callback} cb */ API.prototype._doPostRequest = function(url, args, cb) { return this._doRequest('post', url, args, cb); }; API.prototype._doPutRequest = function(url, args, cb) { return this._doRequest('put', url, args, cb); }; /** * Do a GET request * @private * * @param {String} url * @param {Callback} cb */ API.prototype._doGetRequest = function(url, cb) { url += url.indexOf('?') > 0 ? '&' : '?'; url += 'r=' + _.random(10000, 99999); return this._doRequest('get', url, {}, cb); }; /** * Do a DELETE request * @private * * @param {String} url * @param {Callback} cb */ API.prototype._doDeleteRequest = function(url, cb) { return this._doRequest('delete', url, {}, cb); }; API._buildSecret = function(walletId, walletPrivKey, network) { if (_.isString(walletPrivKey)) { walletPrivKey = Bitcore.PrivateKey.fromString(walletPrivKey); } var widHex = new Buffer(walletId.replace(/-/g, ''), 'hex'); var widBase58 = new Bitcore.encoding.Base58(widHex).toString(); return _.padRight(widBase58, 22, '0') + walletPrivKey.toWIF() + (network == 'testnet' ? 'T' : 'L'); }; API.parseSecret = function(secret) { $.checkArgument(secret); function split(str, indexes) { var parts = []; indexes.push(str.length); var i = 0; while (i < indexes.length) { parts.push(str.substring(i == 0 ? 0 : indexes[i - 1], indexes[i])); i++; }; return parts; }; try { var secretSplit = split(secret, [22, 74]); var widBase58 = secretSplit[0].replace(/0/g, ''); var widHex = Bitcore.encoding.Base58.decode(widBase58).toString('hex'); var walletId = split(widHex, [8, 12, 16, 20]).join('-'); var walletPrivKey = Bitcore.PrivateKey.fromString(secretSplit[1]); var networkChar = secretSplit[2]; return { walletId: walletId, walletPrivKey: walletPrivKey, network: networkChar == 'T' ? 'testnet' : 'livenet', }; } catch (ex) { throw new Error('Invalid secret'); } }; API.buildTx = function(txp) { var t = new Bitcore.Transaction(); $.checkState(_.contains(_.values(Constants.SCRIPT_TYPES), txp.addressType)); switch (txp.addressType) { case Constants.SCRIPT_TYPES.P2SH: _.each(txp.inputs, function(i) { t.from(i, i.publicKeys, txp.requiredSignatures); }); break; case Constants.SCRIPT_TYPES.P2PKH: t.from(txp.inputs); break; } if (txp.toAddress && txp.amount && !txp.outputs) { t.to(txp.toAddress, txp.amount); } else if (txp.outputs) { _.each(txp.outputs, function(o) { $.checkState(o.script || o.toAddress, 'Output should have either toAddress or script specified'); if (o.script) { t.addOutput(new Bitcore.Transaction.Output({ script: o.script, satoshis: o.amount })); } else { t.to(o.toAddress, o.amount); } }); } if (_.startsWith(txp.version, '1.')) { Bitcore.Transaction.FEE_SECURITY_MARGIN = 1; t.feePerKb(txp.feePerKb); } else { t.fee(txp.fee); } t.change(txp.changeAddress.address); // Shuffle outputs for improved privacy if (t.outputs.length > 1) { var outputOrder = txp.outputOrder; if (!t.getChangeOutput()) { outputOrder = _.dropRight(outputOrder); } $.checkState(t.outputs.length == outputOrder.length); t.sortOutputs(function(outputs) { return _.map(outputOrder, function(i) { return outputs[i]; }); }); } // Validate inputs vs outputs independently of Bitcore var totalInputs = _.reduce(txp.inputs, function(memo, i) { return +i.satoshis + memo; }, 0); var totalOutputs = _.reduce(t.outputs, function(memo, o) { return +o.satoshis + memo; }, 0); $.checkState(totalInputs - totalOutputs >= 0); $.checkState(totalInputs - totalOutputs <= Defaults.MAX_TX_FEE); return t; }; API.signTxp = function(txp, derivedXPrivKey) { //Derive proper key to sign, for each input var privs = []; var derived = {}; var xpriv = new Bitcore.HDPrivateKey(derivedXPrivKey); _.each(txp.inputs, function(i) { if (!derived[i.path]) { derived[i.path] = xpriv.derive(i.path).privateKey; privs.push(derived[i.path]); } }); var t = API.buildTx(txp); var signatures = _.map(privs, function(priv, i) { return t.getSignatures(priv); }); signatures = _.map(_.sortBy(_.flatten(signatures), 'inputIndex'), function(s) { return s.signature.toDER().toString('hex'); }); return signatures; }; API.prototype._signTxp = function(txp) { return API.signTxp(txp, this.credentials.getDerivedXPrivKey()); }; /** * Join * @private * * @param {String} walletId * @param {String} walletPrivKey * @param {String} xPubKey * @param {String} requestPubKey * @param {String} copayerName * @param {Object} Optional args * @param {String} opts.customData * @param {Callback} cb */ API.prototype._doJoinWallet = function(walletId, walletPrivKey, xPubKey, requestPubKey, copayerName, opts, cb) { $.shouldBeFunction(cb); opts = opts || {}; // Adds encrypted walletPrivateKey to CustomData opts.customData = opts.customData || {}; opts.customData.walletPrivKey = walletPrivKey.toString();; var encCustomData = Utils.encryptMessage(JSON.stringify(opts.customData), this.credentials.personalEncryptingKey); var args = { walletId: walletId, name: copayerName, xPubKey: xPubKey, requestPubKey: requestPubKey, customData: encCustomData, }; if (opts.dryRun) args.dryRun = true; if (_.isBoolean(opts.supportBIP44AndP2PKH)) args.supportBIP44AndP2PKH = opts.supportBIP44AndP2PKH; var hash = Utils.getCopayerHash(args.name, args.xPubKey, args.requestPubKey); args.copayerSignature = Utils.signMessage(hash, walletPrivKey); var url = '/v2/wallets/' + walletId + '/copayers'; this._doPostRequest(url, args, function(err, body) { if (err) return cb(err); return cb(null, body.wallet); }); }; /** * Return if wallet is complete */ API.prototype.isComplete = function() { return this.credentials && this.credentials.isComplete(); }; /** * Is private key currently encrypted? (ie, locked) * * @return {Boolean} */ API.prototype.isPrivKeyEncrypted = function() { return this.credentials && this.credentials.isPrivKeyEncrypted(); }; /** * Is private key encryption setup? * * @return {Boolean} */ API.prototype.hasPrivKeyEncrypted = function() { return this.credentials && this.credentials.hasPrivKeyEncrypted(); }; /** * Is private key external? * * @return {Boolean} */ API.prototype.isPrivKeyExternal = function() { return this.credentials && this.credentials.hasExternalSource(); }; /** * Get external wallet source name * * @return {String} */ API.prototype.getPrivKeyExternalSourceName = function() { return this.credentials ? this.credentials.getExternalSourceName() : null; }; /** * unlocks the private key. `lock` need to be called explicity * later to remove the unencrypted private key. * * @param password */ API.prototype.unlock = function(password) { try { this.credentials.unlock(password); } catch (e) { throw new Error('Could not unlock:' + e); } }; /** * Can this credentials sign a transaction? * (Only returns fail on a 'proxy' setup for airgapped operation) * * @return {undefined} */ API.prototype.canSign = function() { return this.credentials && this.credentials.canSign(); }; API._extractPublicKeyRing = function(copayers) { return _.map(copayers, function(copayer) { var pkr = _.pick(copayer, ['xPubKey', 'requestPubKey']); pkr.copayerName = copayer.name; return pkr; }); }; /** * sets up encryption for the extended private key * * @param {String} password Password used to encrypt * @param {Object} opts optional: SJCL options to encrypt (.iter, .salt, etc). * @return {undefined} */ API.prototype.setPrivateKeyEncryption = function(password, opts) { this.credentials.setPrivateKeyEncryption(password, opts || API.privateKeyEncryptionOpts); }; /** * disables encryption for private key. * wallet must be unlocked * */ API.prototype.disablePrivateKeyEncryption = function(password, opts) { return this.credentials.disablePrivateKeyEncryption(); }; /** * Locks private key (removes the unencrypted version and keep only the encrypted) * * @return {undefined} */ API.prototype.lock = function() { this.credentials.lock(); }; /** * Get current fee levels for the specified network * * @param {string} network - 'livenet' (default) or 'testnet' * @param {Callback} cb * @returns {Callback} cb - Returns error or an object with status information */ API.prototype.getFeeLevels = function(network, cb) { var self = this; $.checkArgument(network || _.contains(['livenet', 'testnet'], network)); self._doGetRequest('/v1/feelevels/?network=' + (network || 'livenet'), function(err, result) { if (err) return cb(err); return cb(err, result); }); }; /** * Get service version * * @param {Callback} cb */ API.prototype.getVersion = function(cb) { this._doGetRequest('/v1/version/', cb); }; /** * * Create a wallet. * @param {String} walletName * @param {String} copayerName * @param {Number} m * @param {Number} n * @param {object} opts (optional: advanced options) * @param {string} opts.network - 'livenet' or 'testnet' * @param {String} opts.walletPrivKey - set a walletPrivKey (instead of random) * @param {String} opts.id - set a id for wallet (instead of server given) * @param {String} opts.withMnemonics - generate credentials * @param cb * @return {undefined} */ API.prototype.createWallet = function(walletName, copayerName, m, n, opts, cb) { var self = this; if (opts) $.shouldBeObject(opts); opts = opts || {}; var network = opts.network || 'livenet'; if (!_.contains(['testnet', 'livenet'], network)) return cb(new Error('Invalid network')); if (!self.credentials) { log.info('Generating new keys'); self.seedFromRandom({ network: network }); } else { log.info('Using existing keys'); } if (network != self.credentials.network) { return cb(new Error('Existing keys were created for a different network')); } var walletPrivKey = opts.walletPrivKey || new Bitcore.PrivateKey(); var args = { name: walletName, m: m, n: n, pubKey: (new Bitcore.PrivateKey(walletPrivKey)).toPublicKey().toString(), network: network, id: opts.id, }; self._doPostRequest('/v2/wallets/', args, function(err, body) { if (err) return cb(err); var walletId = body.walletId; self.credentials.addWalletInfo(walletId, walletName, m, n, walletPrivKey.toString(), copayerName); var c = self.credentials; var secret = API._buildSecret(c.walletId, c.walletPrivKey, c.network); self._doJoinWallet(walletId, walletPrivKey, self.credentials.xPubKey, self.credentials.requestPubKey, copayerName, {}, function(err, wallet) { if (err) return cb(err); return cb(null, n > 1 ? secret : null); }); }); }; /** * Join an existent wallet * * @param {String} secret * @param {String} copayerName * @param {Object} opts * @param {Boolean} opts.dryRun[=false] - Simulate wallet join * @param {Callback} cb * @returns {Callback} cb - Returns the wallet */ API.prototype.joinWallet = function(secret, copayerName, opts, cb) { var self = this; if (!cb) { cb = opts; opts = {}; log.warn('DEPRECATED WARN: joinWallet should receive 4 parameters.') } opts = opts || {}; try { var secretData = API.parseSecret(secret); } catch (ex) { return cb(ex); } if (!self.credentials) { self.seedFromRandom({ network: secretData.network }); } self._doJoinWallet(secretData.walletId, secretData.walletPrivKey, self.credentials.xPubKey, self.credentials.requestPubKey, copayerName, { dryRun: !!opts.dryRun, }, function(err, wallet) { if (err) return cb(err); if (!opts.dryRun) { self.credentials.addWalletInfo(wallet.id, wallet.name, wallet.m, wallet.n, secretData.walletPrivKey.toString(), copayerName); } return cb(null, wallet); }); }; /** * Recreates a wallet, given credentials (with wallet id) * * @returns {Callback} cb - Returns the wallet */ API.prototype.recreateWallet = function(cb) { $.checkState(this.credentials); $.checkState(this.credentials.isComplete()); $.checkState(this.credentials.walletPrivKey); //$.checkState(this.credentials.hasWalletInfo()); var self = this; // First: Try to get the wallet with current credentials this.getStatus({ includeExtendedInfo: true }, function(err) { // No error? -> Wallet is ready. if (!err) { log.info('Wallet is already created'); return cb(); }; var walletPrivKey = Bitcore.PrivateKey.fromString(self.credentials.walletPrivKey); var walletId = self.credentials.walletId; var supportBIP44AndP2PKH = self.credentials.derivationStrategy != Constants.DERIVATION_STRATEGIES.BIP45; var args = { name: self.credentials.walletName || 'recovered wallet', m: self.credentials.m, n: self.credentials.n, pubKey: walletPrivKey.toPublicKey().toString(), network: self.credentials.network, id: walletId, supportBIP44AndP2PKH: supportBIP44AndP2PKH, }; self._doPostRequest('/v2/wallets/', args, function(err, body) { if (err) { if (err.code != 'WALLET_ALREADY_EXISTS') return cb(err); return self.addAccess({}, function(err) { if (err) return cb(err); self.openWallet(function(err) { return cb(err); }); }); } if (!walletId) { walletId = body.walletId; } var i = 1; async.each(self.credentials.publicKeyRing, function(item, next) { var name = item.copayerName || ('copayer ' + i++); self._doJoinWallet(walletId, walletPrivKey, item.xPubKey, item.requestPubKey, name, { supportBIP44AndP2PKH: supportBIP44AndP2PKH, }, function(err) { //Ignore error is copayer already in wallet if (err && err.code == 'COPAYER_IN_WALLET') return next(); return next(err); }); }, cb); }); }); }; API.prototype._processCustomData = function(result) { var copayers = result.wallet.copayers; if (!copayers) return; var me = _.find(copayers, { 'id': this.credentials.copayerId }); if (!me || !me.customData) return; var customData; try { customData = JSON.parse(Utils.decryptMessage(me.customData, this.credentials.personalEncryptingKey)); } catch (e) { log.warn('Could not decrypt customData:', me.customData); } if (!customData) return; // Add it to result result.customData = customData; // Update walletPrivateKey if (!this.credentials.walletPrivKey && customData.walletPrivKey) this.credentials.addWalletPrivateKey(customData.walletPrivKey) } /** * Get latest notifications * * @param {object} opts * @param {String} lastNotificationId (optional) - The ID of the last received notification * @param {String} timeSpan (optional) - A time window on which to look for notifications (in seconds) * @returns {Callback} cb - Returns error or an array of notifications */ API.prototype.getNotifications = function(opts, cb) { $.checkState(this.credentials); var self = this; opts = opts || {}; var url = '/v1/notifications/'; if (opts.lastNotificationId) { url += '?notificationId=' + opts.lastNotificationId; } else if (opts.timeSpan) { url += '?timeSpan=' + opts.timeSpan; } self._doGetRequest(url, function(err, result) { if (err) return cb(err); var notifications = _.filter(result, function(notification) { return (notification.creatorId != self.credentials.copayerId); }); return cb(null, notifications); }); }; /** * Get status of the wallet * * @param {object} opts.includeExtendedInfo (optional: query extended status) * @returns {Callback} cb - Returns error or an object with status information */ API.prototype.getStatus = function(opts, cb) { $.checkState(this.credentials); if (!cb) { cb = opts; opts = {}; log.warn('DEPRECATED WARN: getStatus should receive 2 parameters.') } var self = this; opts = opts || {}; self._doGetRequest('/v2/wallets/?includeExtendedInfo=' + (opts.includeExtendedInfo ? '1' : '0'), function(err, result) { if (err) return cb(err); if (result.wallet.status == 'pending') { var c = self.credentials; result.wallet.secret = API._buildSecret(c.walletId, c.walletPrivKey, c.network); } self._processTxps(result.pendingTxps); self._processCustomData(result); return cb(err, result); }); }; /** * Get copayer preferences * * @param {Callback} cb * @return {Callback} cb - Return error or object */ API.prototype.getPreferences = function(cb) { $.checkState(this.credentials && this.credentials.isComplete()); $.checkArgument(cb); var self = this; self._doGetRequest('/v1/preferences/', function(err, preferences) { if (err) return cb(err); return cb(null, preferences); }); }; /** * Save copayer preferences * * @param {Object} preferences * @param {Callback} cb * @return {Callback} cb - Return error or object */ API.prototype.savePreferences = function(preferences, cb) { $.checkState(this.credentials && this.credentials.isComplete()); $.checkArgument(cb); var self = this; self._doPutRequest('/v1/preferences/', preferences, cb); }; API.prototype._computeProposalSignature = function(args) { var hash; if (args.outputs) { $.shouldBeArray(args.outputs); // should match bws server createTx var proposalHeader = { outputs: _.map(args.outputs, function(output) { $.shouldBeNumber(output.amount); return _.pick(output, ['toAddress', 'amount', 'message']); }), message: args.message || null, payProUrl: args.payProUrl || null, }; hash = Utils.getProposalHash(proposalHeader); } else { $.shouldBeNumber(args.amount); hash = Utils.getProposalHash(args.toAddress, args.amount, args.message || null, args.payProUrl || null); } return Utils.signMessage(hash, this.credentials.requestPrivKey); } /** * fetchPayPro * * @param opts.payProUrl URL for paypro request * @returns {Callback} cb - Return error or the parsed payment protocol request * Returns (err,paypro) * paypro.amount * paypro.toAddress * paypro.memo */ API.prototype.fetchPayPro = function(opts, cb) { $.checkArgument(opts) .checkArgument(opts.payProUrl); PayPro.get({ url: opts.payProUrl, http: this.payProHttp, }, function(err, paypro) { if (err) return cb(err || 'Could not fetch PayPro request'); return cb(null, paypro); }); }; /** * Gets list of utxos * * @param {Function} cb * @param {Object} opts * @param {Array} opts.addresses (optional) - List of addresses from where to fetch UTXOs. * @returns {Callback} cb - Return error or the list of utxos */ API.prototype.getUtxos = function(opts, cb) { $.checkState(this.credentials && this.credentials.isComplete()); opts = opts || {}; var url = '/v1/utxos/'; if (opts.addresses) { url += '?' + querystring.stringify({ addresses: [].concat(opts.addresses).join(',') }); } this._doGetRequest(url, cb); }; /** * Send a transaction proposal * * @param {Object} opts * @param {String} opts.toAddress | opts.outputs[].toAddress * @param {Number} opts.amount | opts.outputs[].amount * @param {String} opts.message | opts.outputs[].message * @param {string} opts.feePerKb - Optional: Use an alternative fee per KB for this TX * @param {String} opts.payProUrl - Optional: Tx is from a payment protocol URL * @param {string} opts.excludeUnconfirmedUtxos - Optional: Do not use UTXOs of unconfirmed transactions as inputs * @returns {Callback} cb - Return error or the transaction proposal */ API.prototype.sendTxProposal = function(opts, cb) { $.checkState(this.credentials && this.credentials.isComplete()); $.checkArgument(!opts.message || this.credentials.sharedEncryptingKey, 'Cannot create transaction with message without shared Encrypting key'); $.checkArgument(opts); var self = this; var args = { toAddress: opts.toAddress, amount: opts.amount, message: API._encryptMessage(opts.message, this.credentials.sharedEncryptingKey) || null, feePerKb: opts.feePerKb, payProUrl: opts.payProUrl || null, excludeUnconfirmedUtxos: !!opts.excludeUnconfirmedUtxos, type: opts.type, outputs: _.cloneDeep(opts.outputs), customData: opts.customData }; if (args.outputs) { _.each(args.outputs, function(o) { o.message = API._encryptMessage(o.message, self.credentials.sharedEncryptingKey) || null; }); } log.debug('Generating & signing tx proposal:', JSON.stringify(args)); args.proposalSignature = this._computeProposalSignature(args); this._doPostRequest('/v1/txproposals/', args, function(err, txp) { if (err) return cb(err); return cb(null, txp); }); }; /** * Create a new address * * @param {Callback} cb * @returns {Callback} cb - Return error or the address */ API.prototype.createAddress = function(cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; self._doPostRequest('/v2/addresses/', {}, function(err, address) { if (err) return cb(err); if (!Verifier.checkAddress(self.credentials, address)) { return cb(Errors.SERVER_COMPROMISED); } return cb(null, address); }); }; /** * Get your main addresses * * @param {Object} opts * @param {Boolean} opts.doNotVerify * @param {Numeric} opts.limit (optional) - Limit the resultset. Return all addresses by default. * @param {Boolean} [opts.reverse=false] (optional) - Reverse the order of returned addresses. * @param {Callback} cb * @returns {Callback} cb - Return error or the array of addresses */ API.prototype.getMainAddresses = function(opts, cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; opts = opts || {}; var args = []; if (opts.limit) args.push('limit=' + opts.limit); if (opts.reverse) args.push('reverse=1'); var qs = ''; if (args.length > 0) { qs = '?' + args.join('&'); } var url = '/v1/addresses/' + qs; self._doGetRequest(url, function(err, addresses) { if (err) return cb(err); if (!opts.doNotVerify) { var fake = _.any(addresses, function(address) { return !Verifier.checkAddress(self.credentials, address); }); if (fake) return cb(Errors.SERVER_COMPROMISED); } return cb(null, addresses); }); }; /** * Update wallet balance * * @param {Callback} cb */ API.prototype.getBalance = function(cb) { $.checkState(this.credentials && this.credentials.isComplete()); this._doGetRequest('/v1/balance/', cb); }; /** * Get list of transactions proposals * * @param {Object} opts * @param {Boolean} opts.doNotVerify * @param {Boolean} opts.forAirGapped * @return {Callback} cb - Return error or array of transactions proposals */ API.prototype.getTxProposals = function(opts, cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; self._doGetRequest('/v1/txproposals/', function(err, txps) { if (err) return cb(err); self._processTxps(txps); async.every(txps, function(txp, acb) { if (opts.doNotVerify) return acb(true); self.getPayPro(txp, function(err, paypro) { var isLegit = Verifier.checkTxProposal(self.credentials, txp, { paypro: paypro, }); return acb(isLegit); }); }, function(isLegit) { if (!isLegit) return cb(Errors.SERVER_COMPROMISED); var result; if (opts.forAirGapped) { result = { txps: JSON.parse(JSON.stringify(txps)), encryptedPkr: Utils.encryptMessage(JSON.stringify(self.credentials.publicKeyRing), self.credentials.personalEncryptingKey), m: self.credentials.m, n: self.credentials.n, }; } else { result = txps; } return cb(null, result); }); }); }; API.prototype.getPayPro = function(txp, cb) { var self = this; if (!txp.payProUrl || this.doNotVerifyPayPro) return cb(); PayPro.get({ url: txp.payProUrl, http: self.payProHttp, }, function(err, paypro) { if (err) return cb(new Error('Cannot check transaction now:' + err)); return cb(null, paypro); }); }; /** * Sign a transaction proposal * * @param {Object} txp * @param {Callback} cb * @return {Callback} cb - Return error or object */ API.prototype.signTxProposal = function(txp, cb) { $.checkState(this.credentials && this.credentials.isComplete()); $.checkArgument(txp.creatorId); var self = this; if (!self.canSign() && !txp.signatures) return cb(new Error('You do not have the required keys to sign transactions')); if (self.isPrivKeyEncrypted()) return cb(new Error('Private Key is encrypted, cannot sign')); self.getPayPro(txp, function(err, paypro) { if (err) return cb(err); var isLegit = Verifier.checkTxProposal(self.credentials, txp, { paypro: paypro, }); if (!isLegit) return cb(Errors.SERVER_COMPROMISED); var signatures = txp.signatures || self._signTxp(txp); var url = '/v1/txproposals/' + txp.id + '/signatures/'; var args = { signatures: signatures }; self._doPostRequest(url, args, function(err, txp) { if (err) return cb(err); self._processTxps([txp]); return cb(null, txp); }); }) }; /** * Sign transaction proposal from AirGapped * * @param {Object} txp * @param {String} encryptedPkr * @param {Number} m * @param {Number} n * @return {Object} txp - Return transaction */ API.prototype.signTxProposalFromAirGapped = function(txp, encryptedPkr, m, n) { $.checkState(this.credentials); var self = this; if (!self.canSign()) throw Errors.MISSING_PRIVATE_KEY; if (self.isPrivKeyEncrypted()) throw Errors.ENCRYPTED_PRIVATE_KEY; var publicKeyRing; try { publicKeyRing = JSON.parse(Utils.decryptMessage(encryptedPkr, self.credentials.personalEncryptingKey)); } catch (ex) { throw new Error('Could not decrypt public key ring'); } if (!_.isArray(publicKeyRing) || publicKeyRing.length != n) { throw new Error('Invalid public key ring'); } self.credentials.m = m; self.credentials.n = n; self.credentials.addressType = txp.addressType; self.credentials.addPublicKeyRing(publicKeyRing); if (!Verifier.checkTxProposalBody(self.credentials, txp)) throw new Error('Fake transaction proposal'); return self._signTxp(txp); }; /** * Reject a transaction proposal * * @param {Object} txp * @param {String} reason * @param {Callback} cb * @return {Callback} cb - Return error or object */ API.prototype.rejectTxProposal = function(txp, reason, cb) { $.checkState(this.credentials && this.credentials.isComplete()); $.checkArgument(cb); var self = this; var url = '/v1/txproposals/' + txp.id + '/rejections/'; var args = { reason: API._encryptMessage(reason, self.credentials.sharedEncryptingKey) || '', }; self._doPostRequest(url, args, function(err, txp) { if (err) return cb(err); self._processTxps([txp]); return cb(null, txp); }); }; /** * Broadcast raw transaction * * @param {Object} opts * @param {String} opts.network * @param {String} opts.rawTx * @param {Callback} cb * @return {Callback} cb - Return error or txid */ API.prototype.broadcastRawTx = function(opts, cb) { $.checkState(this.credentials); $.checkArgument(cb); var self = this; opts = opts || {}; var url = '/v1/broadcast_raw/'; self._doPostRequest(url, opts, function(err, txid) { if (err) return cb(err); return cb(null, txid); }); }; API.prototype._doBroadcast = function(txp, cb) { var self = this; var url = '/v1/txproposals/' + txp.id + '/broadcast/'; self._doPostRequest(url, {}, function(err, txp) { if (err) return cb(err); return cb(null, txp); }); }; /** * Broadcast a transaction proposal * * @param {Object} txp * @param {Callback} cb * @return {Callback} cb - Return error or object */ API.prototype.broadcastTxProposal = function(txp, cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; self.getPayPro(txp, function(err, paypro) { if (paypro) { var t = API.buildTx(txp); self.createAddress(function(err, addr) { if (err) return cb(err); PayPro.send({ http: self.payProHttp, url: txp.payProUrl, amountSat: txp.amount, refundAddr: addr.address, merchant_data: paypro.merchant_data, rawTx: t.uncheckedSerialize(), }, function(err, ack, memo) { if (err) return cb(err); self._doBroadcast(txp, function(err, txp) { return cb(err, txp, memo); }); }); }); } else { self._doBroadcast(txp, cb); } }); }; /** * Remove a transaction proposal * * @param {Object} txp * @param {Callback} cb * @return {Callback} cb - Return error or empty */ API.prototype.removeTxProposal = function(txp, cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; var url = '/v1/txproposals/' + txp.id; self._doDeleteRequest(url, function(err) { return cb(err); }); }; /** * Get transaction history * * @param {Object} opts * @param {Number} opts.skip (defaults to 0) * @param {Number} opts.limit * @param {Callback} cb * @return {Callback} cb - Return error or array of transactions */ API.prototype.getTxHistory = function(opts, cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; var args = []; if (opts) { if (opts.skip) args.push('skip=' + opts.skip); if (opts.limit) args.push('limit=' + opts.limit); } var qs = ''; if (args.length > 0) { qs = '?' + args.join('&'); } var url = '/v1/txhistory/' + qs; self._doGetRequest(url, function(err, txs) { if (err) return cb(err); self._processTxps(txs); return cb(null, txs); }); }; /** * getTx * * @param {String} TransactionId * @return {Callback} cb - Return error or transaction */ API.prototype.getTx = function(id, cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; var url = '/v1/txproposals/' + id; this._doGetRequest(url, function(err, tx) { if (err) return cb(err); self._processTxps([tx]); return cb(null, tx); }); }; /** * Start an address scanning process. * When finished, the scanning process will send a notification 'ScanFinished' to all copayers. * * @param {Object} opts * @param {Boolean} opts.includeCopayerBranches (defaults to false) * @param {Callback} cb */ API.prototype.startScan = function(opts, cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; var args = { includeCopayerBranches: opts.includeCopayerBranches, }; self._doPostRequest('/v1/addresses/scan', args, function(err) { return cb(err); }); }; /* * * Compatibility Functions * */ API.prototype._oldCopayDecrypt = function(username, password, blob) { var SEP1 = '@#$'; var SEP2 = '%^#@'; var decrypted; try { var passphrase = username + SEP1 + password; decrypted = sjcl.decrypt(passphrase, blob); } catch (e) { passphrase = username + SEP2 + password; try { decrypted = sjcl.decrypt(passphrase, blob); } catch (e) { log.debug(e); }; } if (!decrypted) return null; var ret; try { ret = JSON.parse(decrypted); } catch (e) {}; return ret; }; API.prototype.getWalletIdsFromOldCopay = function(username, password, blob) { var p = this._oldCopayDecrypt(username, password, blob); if (!p) return null; var ids = p.walletIds.concat(_.keys(p.focusedTimestamps)); return _.uniq(ids); }; /** * createWalletFromOldCopay * * @param username * @param password * @param blob * @param cb * @return {undefined} */ API.prototype.createWalletFromOldCopay = function(username, password, blob, cb) { var self = this; var w = this._oldCopayDecrypt(username, password, blob); if (!w) return cb('Could not decrypt'); if (w.publicKeyRing.copayersExtPubKeys.length != w.opts.totalCopayers) return cb('Wallet is incomplete, cannot be imported'); this.credentials = Credentials.fromOldCopayWallet(w); this.recreateWallet(cb); }; /* Adds access to the current copayer * @param {Object} opts * @param {bool} opts.generateNewKey Optional: generate a new key for the new access * @param {string} opts.restrictions * - cannotProposeTXs * - cannotXXX TODO * @param {string} opts.name (name for the new access) * * return the accesses Wallet and the requestPrivateKey */ API.prototype.addAccess = function(opts, cb) { $.checkState(this.credentials && this.credentials.canSign()); var reqPrivKey = new Bitcore.PrivateKey(opts.generateNewKey ? null : this.credentials.requestPrivKey); var requestPubKey = reqPrivKey.toPublicKey().toString(); var xPriv = new Bitcore.HDPrivateKey(this.credentials.xPrivKey) .derive(this.credentials.getBaseAddressDerivationPath()); var sig = Utils.signRequestPubKey(requestPubKey, xPriv); var copayerId = this.credentials.copayerId; var opts = { copayerId: copayerId, requestPubKey: requestPubKey, signature: sig, name: opts.name, restrictions: opts.restrictions, }; this._doPutRequest('/v1/copayers/' + copayerId + '/', opts, function(err, res) { if (err) return cb(err); return cb(null, res.wallet, reqPrivKey); }); }; module.exports = API;
lib/api.js
/** @namespace Client.API */ 'use strict'; var _ = require('lodash'); var $ = require('preconditions').singleton(); var util = require('util'); var async = require('async'); var events = require('events'); var Bitcore = require('bitcore-lib'); var sjcl = require('sjcl'); var url = require('url'); var querystring = require('querystring'); var Stringify = require('json-stable-stringify'); var request; if (process && !process.browser) { request = require('request'); } else { request = require('browser-request'); } var Common = require('./common'); var Constants = Common.Constants; var Defaults = Common.Defaults; var Utils = Common.Utils; var PayPro = require('./paypro'); var log = require('./log'); var Credentials = require('./credentials'); var Verifier = require('./verifier'); var Package = require('../package.json'); var ClientError = require('./errors/clienterror'); var Errors = require('./errors/errordefinitions'); var BASE_URL = 'http://localhost:3232/bws/api'; /** * @desc ClientAPI constructor. * * @param {Object} opts * @constructor */ function API(opts) { opts = opts || {}; this.verbose = !!opts.verbose; this.request = opts.request || request; this.baseUrl = opts.baseUrl || BASE_URL; var parsedUrl = url.parse(this.baseUrl); this.basePath = parsedUrl.path; this.baseHost = parsedUrl.protocol + '//' + parsedUrl.host; this.payProHttp = null; // Only for testing this.doNotVerifyPayPro = opts.doNotVerifyPayPro; this.timeout = opts.timeout || 50000; if (this.verbose) { log.setLevel('debug'); } else { log.setLevel('info'); } }; util.inherits(API, events.EventEmitter); API.privateKeyEncryptionOpts = { iter: 10000 }; API.prototype.initNotifications = function(cb) { log.warn('DEPRECATED: use initialize() instead.'); this.initialize({}, cb); }; API.prototype.initialize = function(opts, cb) { $.checkState(this.credentials); var self = this; self._initNotifications(opts); return cb(); }; API.prototype.dispose = function(cb) { var self = this; self._disposeNotifications(); return cb(); }; API.prototype._fetchLatestNotifications = function(interval, cb) { var self = this; cb = cb || function() {}; var opts = { lastNotificationId: self.lastNotificationId, }; if (!self.lastNotificationId) { opts.timeSpan = interval; } self.getNotifications(opts, function(err, notifications) { if (err) { log.warn('Error receiving notifications.'); log.debug(err); return cb(err); } if (notifications.length > 0) { self.lastNotificationId = _.last(notifications).id; } _.each(notifications, function(notification) { self.emit('notification', notification); }); return cb(); }); }; API.prototype._initNotifications = function(opts) { var self = this; opts = opts || {}; var interval = opts.notificationIntervalSeconds || 5; self.notificationsIntervalId = setInterval(function() { self._fetchLatestNotifications(interval, function(err) { if (err) { if (err.code == 'NOT_FOUND' || err.code == 'NOT_AUTHORIZED') { self._disposeNotifications(); } } }); }, interval * 1000); }; API.prototype._disposeNotifications = function() { var self = this; if (self.notificationsIntervalId) { clearInterval(self.notificationsIntervalId); self.notificationsIntervalId = null; } }; /** * Reset notification polling with new interval * @memberof Client.API * @param {Numeric} notificationIntervalSeconds - use 0 to pause notifications */ API.prototype.setNotificationsInterval = function(notificationIntervalSeconds) { var self = this; self._disposeNotifications(); if (notificationIntervalSeconds > 0) { self._initNotifications({ notificationIntervalSeconds: notificationIntervalSeconds }); } }; /** * Encrypt a message * @private * @static * @memberof Client.API * @param {String} message * @param {String} encryptingKey */ API._encryptMessage = function(message, encryptingKey) { if (!message) return null; return Utils.encryptMessage(message, encryptingKey); }; /** * Decrypt a message * @private * @static * @memberof Client.API * @param {String} message * @param {String} encryptingKey */ API._decryptMessage = function(message, encryptingKey) { if (!message) return ''; try { return Utils.decryptMessage(message, encryptingKey); } catch (ex) { return '<ECANNOTDECRYPT>'; } }; /** * Decrypt text fields in transaction proposals * @private * @static * @memberof Client.API * @param {Array} txps * @param {String} encryptingKey */ API.prototype._processTxps = function(txps) { var self = this; if (!txps) return; var encryptingKey = self.credentials.sharedEncryptingKey; _.each([].concat(txps), function(txp) { txp.encryptedMessage = txp.message; txp.message = API._decryptMessage(txp.message, encryptingKey) || null; _.each(txp.actions, function(action) { action.comment = API._decryptMessage(action.comment, encryptingKey); // TODO get copayerName from Credentials -> copayerId to copayerName // action.copayerName = null; }); _.each(txp.outputs, function(output) { output.encryptedMessage = output.message; output.message = API._decryptMessage(output.message, encryptingKey) || null; }); txp.hasUnconfirmedInputs = _.any(txp.inputs, function(input) { return input.confirmations == 0; }); }); }; /** * Parse errors * @private * @static * @memberof Client.API * @param {Object} body */ API._parseError = function(body) { if (_.isString(body)) { try { body = JSON.parse(body); } catch (e) { body = { error: body }; } } var ret; if (body && body.code) { ret = new ClientError(body.code, body.message); } else { ret = { code: 'ERROR', error: body ? body.error : 'There was an unknown error processing the request', }; } log.error(ret); return ret; }; /** * Sign an HTTP request * @private * @static * @memberof Client.API * @param {String} method - The HTTP method * @param {String} url - The URL for the request * @param {Object} args - The arguments in case this is a POST/PUT request * @param {String} privKey - Private key to sign the request */ API._signRequest = function(method, url, args, privKey) { var message = [method.toLowerCase(), url, JSON.stringify(args)].join('|'); return Utils.signMessage(message, privKey); }; /** * Seed from random * * @param {Object} opts * @param {String} opts.network - default 'livenet' */ API.prototype.seedFromRandom = function(opts) { $.checkArgument(arguments.length <= 1, 'DEPRECATED: only 1 argument accepted.'); $.checkArgument(_.isUndefined(opts) || _.isObject(opts), 'DEPRECATED: argument should be an options object.'); opts = opts || {}; this.credentials = Credentials.create(opts.network || 'livenet'); }; /** * Seed from random with mnemonic * * @param {Object} opts * @param {String} opts.network - default 'livenet' * @param {String} opts.passphrase * @param {Number} opts.language - default 'en' * @param {Number} opts.account - default 0 */ API.prototype.seedFromRandomWithMnemonic = function(opts) { $.checkArgument(arguments.length <= 1, 'DEPRECATED: only 1 argument accepted.'); $.checkArgument(_.isUndefined(opts) || _.isObject(opts), 'DEPRECATED: argument should be an options object.'); opts = opts || {}; this.credentials = Credentials.createWithMnemonic(opts.network || 'livenet', opts.passphrase, opts.language || 'en', opts.account || 0); }; API.prototype.getMnemonic = function() { return this.credentials.getMnemonic(); }; API.prototype.mnemonicHasPassphrase = function() { return this.credentials.mnemonicHasPassphrase; }; API.prototype.clearMnemonic = function() { return this.credentials.clearMnemonic(); }; /** * Seed from extended private key * * @param {String} xPrivKey */ API.prototype.seedFromExtendedPrivateKey = function(xPrivKey) { this.credentials = Credentials.fromExtendedPrivateKey(xPrivKey); }; /** * Seed from Mnemonics (language autodetected) * Can throw an error if mnemonic is invalid * * @param {String} BIP39 words * @param {Object} opts * @param {String} opts.network - default 'livenet' * @param {String} opts.passphrase * @param {Number} opts.account - default 0 * @param {String} opts.derivationStrategy - default 'BIP44' */ API.prototype.seedFromMnemonic = function(words, opts) { $.checkArgument(_.isUndefined(opts) || _.isObject(opts), 'DEPRECATED: second argument should be an options object.'); opts = opts || {}; this.credentials = Credentials.fromMnemonic(opts.network || 'livenet', words, opts.passphrase, opts.account || 0, opts.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP44); }; /** * Seed from external wallet public key * * @param {String} xPubKey * @param {String} source - A name identifying the source of the xPrivKey (e.g. ledger, TREZOR, ...) * @param {String} entropySourceHex - A HEX string containing pseudo-random data, that can be deterministically derived from the xPrivKey, and should not be derived from xPubKey. * @param {Object} opts * @param {Number} opts.account - default 0 * @param {String} opts.derivationStrategy - default 'BIP44' */ API.prototype.seedFromExtendedPublicKey = function(xPubKey, source, entropySourceHex, opts) { $.checkArgument(_.isUndefined(opts) || _.isObject(opts)); opts = opts || {}; this.credentials = Credentials.fromExtendedPublicKey(xPubKey, source, entropySourceHex, opts.account || 0, opts.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP44); }; /** * Export wallet * * @param {Object} opts * @param {Boolean} opts.noSign */ API.prototype.export = function(opts) { $.checkState(this.credentials); opts = opts || {}; var output; var c = Credentials.fromObj(this.credentials); if (opts.noSign) { c.setNoSign(); } output = JSON.stringify(c.toObj()); return output; } /** * Import wallet * * @param {Object} str * @param {Object} opts * @param {String} opts.password If the source has the private key encrypted, the password * will be needed for derive credentials fields. */ API.prototype.import = function(str, opts) { opts = opts || {}; try { var credentials = Credentials.fromObj(JSON.parse(str)); this.credentials = credentials; } catch (ex) { throw Errors.INVALID_BACKUP; } }; API.prototype._import = function(cb) { $.checkState(this.credentials); var self = this; // First option, grab wallet info from BWS. self.openWallet(function(err, ret) { // it worked? if (!err) return cb(null, ret); // Is the error other than "copayer was not found"? || or no priv key. if (err.code != 'NOT_AUTHORIZED' || self.isPrivKeyExternal()) return cb(err); //Second option, lets try to add an access log.info('Copayer not found, trying to add access'); self.addAccess({}, function(err) { // it worked? if (!err) self.openWallet(cb); return cb(Errors.WALLET_DOES_NOT_EXIST) }); }); }; /** * Import from Mnemonics (language autodetected) * Can throw an error if mnemonic is invalid * * @param {String} BIP39 words * @param {Object} opts * @param {String} opts.network - default 'livenet' * @param {String} opts.passphrase * @param {Number} opts.account - default 0 * @param {String} opts.derivationStrategy - default 'BIP44' */ API.prototype.importFromMnemonic = function(words, opts, cb) { log.debug('Importing from 12 Words'); opts = opts || {}; try { this.credentials = Credentials.fromMnemonic(opts.network || 'livenet', words, opts.passphrase, opts.account || 0, opts.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP44); } catch (e) { log.info('Mnemonic error:', e); return cb(Errors.INVALID_BACKUP); }; this._import(cb); }; API.prototype.importFromExtendedPrivateKey = function(xPrivKey, cb) { log.debug('Importing from Extended Private Key'); try { this.credentials = Credentials.fromExtendedPrivateKey(xPrivKey); } catch (e) { log.info('xPriv error:', e); return cb(Errors.INVALID_BACKUP); }; this._import(cb); }; /** * Import from Extended Public Key * * @param {String} xPubKey * @param {String} source - A name identifying the source of the xPrivKey * @param {String} entropySourceHex - A HEX string containing pseudo-random data, that can be deterministically derived from the xPrivKey, and should not be derived from xPubKey. * @param {Object} opts * @param {Number} opts.account - default 0 * @param {String} opts.derivationStrategy - default 'BIP44' */ API.prototype.importFromExtendedPublicKey = function(xPubKey, source, entropySourceHex, opts, cb) { $.checkArgument(arguments.length == 5, "DEPRECATED: should receive 5 arguments"); $.checkArgument(_.isUndefined(opts) || _.isObject(opts)); $.shouldBeFunction(cb); opts = opts || {}; log.debug('Importing from Extended Private Key'); try { this.credentials = Credentials.fromExtendedPublicKey(xPubKey, source, entropySourceHex, opts.account || 0, opts.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP44); } catch (e) { log.info('xPriv error:', e); return cb(Errors.INVALID_BACKUP); }; this._import(cb); }; API.prototype.decryptBIP38PrivateKey = function(encryptedPrivateKeyBase58, passphrase, opts, cb) { var Bip38 = require('bip38'); var bip38 = new Bip38(); var privateKeyWif; try { privateKeyWif = bip38.decrypt(encryptedPrivateKeyBase58, passphrase); } catch (ex) { return cb(new Error('Could not decrypt BIP38 private key', ex)); } var privateKey = new Bitcore.PrivateKey(privateKeyWif); var address = privateKey.publicKey.toAddress().toString(); var addrBuff = new Buffer(address, 'ascii'); var actualChecksum = Bitcore.crypto.Hash.sha256sha256(addrBuff).toString('hex').substring(0, 8); var expectedChecksum = Bitcore.encoding.Base58Check.decode(encryptedPrivateKeyBase58).toString('hex').substring(6, 14); if (actualChecksum != expectedChecksum) return cb(new Error('Incorrect passphrase')); return cb(null, privateKeyWif); }; API.prototype.getBalanceFromPrivateKey = function(privateKey, cb) { var self = this; var privateKey = new Bitcore.PrivateKey(privateKey); var address = privateKey.publicKey.toAddress(); self.getUtxos({ addresses: address.toString(), }, function(err, utxos) { if (err) return cb(err); return cb(null, _.sum(utxos, 'satoshis')); }); }; API.prototype.buildTxFromPrivateKey = function(privateKey, destinationAddress, opts, cb) { var self = this; opts = opts || {}; var privateKey = new Bitcore.PrivateKey(privateKey); var address = privateKey.publicKey.toAddress(); async.waterfall([ function(next) { self.getUtxos({ addresses: address.toString(), }, function(err, utxos) { return next(err, utxos); }); }, function(utxos, next) { if (!_.isArray(utxos) || utxos.length == 0) return next(new Error('No utxos found')); var fee = opts.fee || 10000; var amount = _.sum(utxos, 'satoshis') - fee; if (amount <= 0) return next(Errors.INSUFFICIENT_FUNDS); var tx; try { var toAddress = Bitcore.Address.fromString(destinationAddress); tx = new Bitcore.Transaction() .from(utxos) .to(toAddress, amount) .fee(fee) .sign(privateKey); // Make sure the tx can be serialized tx.serialize(); } catch (ex) { log.error('Could not build transaction from private key', ex); return next(Errors.COULD_NOT_BUILD_TRANSACTION); } return next(null, tx); } ], cb); }; /** * Open a wallet and try to complete the public key ring. * * @param {Callback} cb - The callback that handles the response. It returns a flag indicating that the wallet is complete. * @fires API#walletCompleted */ API.prototype.openWallet = function(cb) { $.checkState(this.credentials); var self = this; if (self.credentials.isComplete() && self.credentials.hasWalletInfo()) return cb(null, true); self._doGetRequest('/v2/wallets/?includeExtendedInfo=1', function(err, ret) { if (err) return cb(err); var wallet = ret.wallet; if (wallet.status != 'complete') return cb(); if (self.credentials.walletPrivKey) { if (!Verifier.checkCopayers(self.credentials, wallet.copayers)) { return cb(Errors.SERVER_COMPROMISED); } } else { // this should only happends in AIR-GAPPED flows log.warn('Could not verify copayers key (missing wallet Private Key)'); } // Wallet was not complete. We are completing it. self.credentials.addPublicKeyRing(API._extractPublicKeyRing(wallet.copayers)); if (!self.credentials.hasWalletInfo()) { var me = _.find(wallet.copayers, { id: self.credentials.copayerId }); self.credentials.addWalletInfo(wallet.id, wallet.name, wallet.m, wallet.n, null, me.name); } self.emit('walletCompleted', wallet); self._processTxps(ret.pendingTxps); self._processCustomData(ret); return cb(null, ret); }); }; /** * Do an HTTP request * @private * * @param {Object} method * @param {String} url * @param {Object} args * @param {Callback} cb */ API.prototype._doRequest = function(method, url, args, cb) { $.checkState(this.credentials); var reqSignature; var key = args._requestPrivKey || this.credentials.requestPrivKey; if (key) { delete args['_requestPrivKey']; reqSignature = API._signRequest(method, url, args, key); } var absUrl = this.baseUrl + url; var args = { // relUrl: only for testing with `supertest` relUrl: this.basePath + url, headers: { 'x-identity': this.credentials.copayerId, 'x-signature': reqSignature, 'x-client-version': 'bwc-' + Package.version, }, method: method, url: absUrl, body: args, json: true, withCredentials: false, timeout: this.timeout, }; log.debug('Request Args', util.inspect(args, { depth: 10 })); this.request(args, function(err, res, body) { log.debug(util.inspect(body, { depth: 10 })); if (!res) { return cb({ code: 'CONNECTION_ERROR', }); } if (res.statusCode != 200) { if (res.statusCode == 404) return cb({ code: 'NOT_FOUND' }); if (!res.statusCode) return cb({ code: 'CONNECTION_ERROR', }); return cb(API._parseError(body)); } if (body === '{"error":"read ECONNRESET"}') return cb(JSON.parse(body)); return cb(null, body, res.header); }); }; /** * Do a POST request * @private * * @param {String} url * @param {Object} args * @param {Callback} cb */ API.prototype._doPostRequest = function(url, args, cb) { return this._doRequest('post', url, args, cb); }; API.prototype._doPutRequest = function(url, args, cb) { return this._doRequest('put', url, args, cb); }; /** * Do a GET request * @private * * @param {String} url * @param {Callback} cb */ API.prototype._doGetRequest = function(url, cb) { url += url.indexOf('?') > 0 ? '&' : '?'; url += 'r=' + _.random(10000, 99999); return this._doRequest('get', url, {}, cb); }; /** * Do a DELETE request * @private * * @param {String} url * @param {Callback} cb */ API.prototype._doDeleteRequest = function(url, cb) { return this._doRequest('delete', url, {}, cb); }; API._buildSecret = function(walletId, walletPrivKey, network) { if (_.isString(walletPrivKey)) { walletPrivKey = Bitcore.PrivateKey.fromString(walletPrivKey); } var widHex = new Buffer(walletId.replace(/-/g, ''), 'hex'); var widBase58 = new Bitcore.encoding.Base58(widHex).toString(); return _.padRight(widBase58, 22, '0') + walletPrivKey.toWIF() + (network == 'testnet' ? 'T' : 'L'); }; API.parseSecret = function(secret) { $.checkArgument(secret); function split(str, indexes) { var parts = []; indexes.push(str.length); var i = 0; while (i < indexes.length) { parts.push(str.substring(i == 0 ? 0 : indexes[i - 1], indexes[i])); i++; }; return parts; }; try { var secretSplit = split(secret, [22, 74]); var widBase58 = secretSplit[0].replace(/0/g, ''); var widHex = Bitcore.encoding.Base58.decode(widBase58).toString('hex'); var walletId = split(widHex, [8, 12, 16, 20]).join('-'); var walletPrivKey = Bitcore.PrivateKey.fromString(secretSplit[1]); var networkChar = secretSplit[2]; return { walletId: walletId, walletPrivKey: walletPrivKey, network: networkChar == 'T' ? 'testnet' : 'livenet', }; } catch (ex) { throw new Error('Invalid secret'); } }; API.buildTx = function(txp) { var t = new Bitcore.Transaction(); $.checkState(_.contains(_.values(Constants.SCRIPT_TYPES), txp.addressType)); switch (txp.addressType) { case Constants.SCRIPT_TYPES.P2SH: _.each(txp.inputs, function(i) { t.from(i, i.publicKeys, txp.requiredSignatures); }); break; case Constants.SCRIPT_TYPES.P2PKH: t.from(txp.inputs); break; } if (txp.toAddress && txp.amount && !txp.outputs) { t.to(txp.toAddress, txp.amount); } else if (txp.outputs) { _.each(txp.outputs, function(o) { $.checkState(o.script || o.toAddress, 'Output should have either toAddress or script specified'); if (o.script) { t.addOutput(new Bitcore.Transaction.Output({ script: o.script, satoshis: o.amount })); } else { t.to(o.toAddress, o.amount); } }); } if (_.startsWith(txp.version, '1.')) { Bitcore.Transaction.FEE_SECURITY_MARGIN = 1; t.feePerKb(txp.feePerKb); } else { t.fee(txp.fee); } t.change(txp.changeAddress.address); // Shuffle outputs for improved privacy if (t.outputs.length > 1) { $.checkState(t.outputs.length == txp.outputOrder.length); t.sortOutputs(function(outputs) { return _.map(txp.outputOrder, function(i) { return outputs[i]; }); }); } // Validate inputs vs outputs independently of Bitcore var totalInputs = _.reduce(txp.inputs, function(memo, i) { return +i.satoshis + memo; }, 0); var totalOutputs = _.reduce(t.outputs, function(memo, o) { return +o.satoshis + memo; }, 0); $.checkState(totalInputs - totalOutputs >= 0); $.checkState(totalInputs - totalOutputs <= Defaults.MAX_TX_FEE); return t; }; API.signTxp = function(txp, derivedXPrivKey) { //Derive proper key to sign, for each input var privs = []; var derived = {}; var xpriv = new Bitcore.HDPrivateKey(derivedXPrivKey); _.each(txp.inputs, function(i) { if (!derived[i.path]) { derived[i.path] = xpriv.derive(i.path).privateKey; privs.push(derived[i.path]); } }); var t = API.buildTx(txp); var signatures = _.map(privs, function(priv, i) { return t.getSignatures(priv); }); signatures = _.map(_.sortBy(_.flatten(signatures), 'inputIndex'), function(s) { return s.signature.toDER().toString('hex'); }); return signatures; }; API.prototype._signTxp = function(txp) { return API.signTxp(txp, this.credentials.getDerivedXPrivKey()); }; /** * Join * @private * * @param {String} walletId * @param {String} walletPrivKey * @param {String} xPubKey * @param {String} requestPubKey * @param {String} copayerName * @param {Object} Optional args * @param {String} opts.customData * @param {Callback} cb */ API.prototype._doJoinWallet = function(walletId, walletPrivKey, xPubKey, requestPubKey, copayerName, opts, cb) { $.shouldBeFunction(cb); opts = opts || {}; // Adds encrypted walletPrivateKey to CustomData opts.customData = opts.customData || {}; opts.customData.walletPrivKey = walletPrivKey.toString();; var encCustomData = Utils.encryptMessage(JSON.stringify(opts.customData), this.credentials.personalEncryptingKey); var args = { walletId: walletId, name: copayerName, xPubKey: xPubKey, requestPubKey: requestPubKey, customData: encCustomData, }; if (opts.dryRun) args.dryRun = true; if (_.isBoolean(opts.supportBIP44AndP2PKH)) args.supportBIP44AndP2PKH = opts.supportBIP44AndP2PKH; var hash = Utils.getCopayerHash(args.name, args.xPubKey, args.requestPubKey); args.copayerSignature = Utils.signMessage(hash, walletPrivKey); var url = '/v2/wallets/' + walletId + '/copayers'; this._doPostRequest(url, args, function(err, body) { if (err) return cb(err); return cb(null, body.wallet); }); }; /** * Return if wallet is complete */ API.prototype.isComplete = function() { return this.credentials && this.credentials.isComplete(); }; /** * Is private key currently encrypted? (ie, locked) * * @return {Boolean} */ API.prototype.isPrivKeyEncrypted = function() { return this.credentials && this.credentials.isPrivKeyEncrypted(); }; /** * Is private key encryption setup? * * @return {Boolean} */ API.prototype.hasPrivKeyEncrypted = function() { return this.credentials && this.credentials.hasPrivKeyEncrypted(); }; /** * Is private key external? * * @return {Boolean} */ API.prototype.isPrivKeyExternal = function() { return this.credentials && this.credentials.hasExternalSource(); }; /** * Get external wallet source name * * @return {String} */ API.prototype.getPrivKeyExternalSourceName = function() { return this.credentials ? this.credentials.getExternalSourceName() : null; }; /** * unlocks the private key. `lock` need to be called explicity * later to remove the unencrypted private key. * * @param password */ API.prototype.unlock = function(password) { try { this.credentials.unlock(password); } catch (e) { throw new Error('Could not unlock:' + e); } }; /** * Can this credentials sign a transaction? * (Only returns fail on a 'proxy' setup for airgapped operation) * * @return {undefined} */ API.prototype.canSign = function() { return this.credentials && this.credentials.canSign(); }; API._extractPublicKeyRing = function(copayers) { return _.map(copayers, function(copayer) { var pkr = _.pick(copayer, ['xPubKey', 'requestPubKey']); pkr.copayerName = copayer.name; return pkr; }); }; /** * sets up encryption for the extended private key * * @param {String} password Password used to encrypt * @param {Object} opts optional: SJCL options to encrypt (.iter, .salt, etc). * @return {undefined} */ API.prototype.setPrivateKeyEncryption = function(password, opts) { this.credentials.setPrivateKeyEncryption(password, opts || API.privateKeyEncryptionOpts); }; /** * disables encryption for private key. * wallet must be unlocked * */ API.prototype.disablePrivateKeyEncryption = function(password, opts) { return this.credentials.disablePrivateKeyEncryption(); }; /** * Locks private key (removes the unencrypted version and keep only the encrypted) * * @return {undefined} */ API.prototype.lock = function() { this.credentials.lock(); }; /** * Get current fee levels for the specified network * * @param {string} network - 'livenet' (default) or 'testnet' * @param {Callback} cb * @returns {Callback} cb - Returns error or an object with status information */ API.prototype.getFeeLevels = function(network, cb) { var self = this; $.checkArgument(network || _.contains(['livenet', 'testnet'], network)); self._doGetRequest('/v1/feelevels/?network=' + (network || 'livenet'), function(err, result) { if (err) return cb(err); return cb(err, result); }); }; /** * Get service version * * @param {Callback} cb */ API.prototype.getVersion = function(cb) { this._doGetRequest('/v1/version/', cb); }; /** * * Create a wallet. * @param {String} walletName * @param {String} copayerName * @param {Number} m * @param {Number} n * @param {object} opts (optional: advanced options) * @param {string} opts.network - 'livenet' or 'testnet' * @param {String} opts.walletPrivKey - set a walletPrivKey (instead of random) * @param {String} opts.id - set a id for wallet (instead of server given) * @param {String} opts.withMnemonics - generate credentials * @param cb * @return {undefined} */ API.prototype.createWallet = function(walletName, copayerName, m, n, opts, cb) { var self = this; if (opts) $.shouldBeObject(opts); opts = opts || {}; var network = opts.network || 'livenet'; if (!_.contains(['testnet', 'livenet'], network)) return cb(new Error('Invalid network')); if (!self.credentials) { log.info('Generating new keys'); self.seedFromRandom({ network: network }); } else { log.info('Using existing keys'); } if (network != self.credentials.network) { return cb(new Error('Existing keys were created for a different network')); } var walletPrivKey = opts.walletPrivKey || new Bitcore.PrivateKey(); var args = { name: walletName, m: m, n: n, pubKey: (new Bitcore.PrivateKey(walletPrivKey)).toPublicKey().toString(), network: network, id: opts.id, }; self._doPostRequest('/v2/wallets/', args, function(err, body) { if (err) return cb(err); var walletId = body.walletId; self.credentials.addWalletInfo(walletId, walletName, m, n, walletPrivKey.toString(), copayerName); var c = self.credentials; var secret = API._buildSecret(c.walletId, c.walletPrivKey, c.network); self._doJoinWallet(walletId, walletPrivKey, self.credentials.xPubKey, self.credentials.requestPubKey, copayerName, {}, function(err, wallet) { if (err) return cb(err); return cb(null, n > 1 ? secret : null); }); }); }; /** * Join an existent wallet * * @param {String} secret * @param {String} copayerName * @param {Object} opts * @param {Boolean} opts.dryRun[=false] - Simulate wallet join * @param {Callback} cb * @returns {Callback} cb - Returns the wallet */ API.prototype.joinWallet = function(secret, copayerName, opts, cb) { var self = this; if (!cb) { cb = opts; opts = {}; log.warn('DEPRECATED WARN: joinWallet should receive 4 parameters.') } opts = opts || {}; try { var secretData = API.parseSecret(secret); } catch (ex) { return cb(ex); } if (!self.credentials) { self.seedFromRandom({ network: secretData.network }); } self._doJoinWallet(secretData.walletId, secretData.walletPrivKey, self.credentials.xPubKey, self.credentials.requestPubKey, copayerName, { dryRun: !!opts.dryRun, }, function(err, wallet) { if (err) return cb(err); if (!opts.dryRun) { self.credentials.addWalletInfo(wallet.id, wallet.name, wallet.m, wallet.n, secretData.walletPrivKey.toString(), copayerName); } return cb(null, wallet); }); }; /** * Recreates a wallet, given credentials (with wallet id) * * @returns {Callback} cb - Returns the wallet */ API.prototype.recreateWallet = function(cb) { $.checkState(this.credentials); $.checkState(this.credentials.isComplete()); $.checkState(this.credentials.walletPrivKey); //$.checkState(this.credentials.hasWalletInfo()); var self = this; // First: Try to get the wallet with current credentials this.getStatus({ includeExtendedInfo: true }, function(err) { // No error? -> Wallet is ready. if (!err) { log.info('Wallet is already created'); return cb(); }; var walletPrivKey = Bitcore.PrivateKey.fromString(self.credentials.walletPrivKey); var walletId = self.credentials.walletId; var supportBIP44AndP2PKH = self.credentials.derivationStrategy != Constants.DERIVATION_STRATEGIES.BIP45; var args = { name: self.credentials.walletName || 'recovered wallet', m: self.credentials.m, n: self.credentials.n, pubKey: walletPrivKey.toPublicKey().toString(), network: self.credentials.network, id: walletId, supportBIP44AndP2PKH: supportBIP44AndP2PKH, }; self._doPostRequest('/v2/wallets/', args, function(err, body) { if (err) { if (err.code != 'WALLET_ALREADY_EXISTS') return cb(err); return self.addAccess({}, function(err) { if (err) return cb(err); self.openWallet(function(err) { return cb(err); }); }); } if (!walletId) { walletId = body.walletId; } var i = 1; async.each(self.credentials.publicKeyRing, function(item, next) { var name = item.copayerName || ('copayer ' + i++); self._doJoinWallet(walletId, walletPrivKey, item.xPubKey, item.requestPubKey, name, { supportBIP44AndP2PKH: supportBIP44AndP2PKH, }, function(err) { //Ignore error is copayer already in wallet if (err && err.code == 'COPAYER_IN_WALLET') return next(); return next(err); }); }, cb); }); }); }; API.prototype._processCustomData = function(result) { var copayers = result.wallet.copayers; if (!copayers) return; var me = _.find(copayers, { 'id': this.credentials.copayerId }); if (!me || !me.customData) return; var customData; try { customData = JSON.parse(Utils.decryptMessage(me.customData, this.credentials.personalEncryptingKey)); } catch (e) { log.warn('Could not decrypt customData:', me.customData); } if (!customData) return; // Add it to result result.customData = customData; // Update walletPrivateKey if (!this.credentials.walletPrivKey && customData.walletPrivKey) this.credentials.addWalletPrivateKey(customData.walletPrivKey) } /** * Get latest notifications * * @param {object} opts * @param {String} lastNotificationId (optional) - The ID of the last received notification * @param {String} timeSpan (optional) - A time window on which to look for notifications (in seconds) * @returns {Callback} cb - Returns error or an array of notifications */ API.prototype.getNotifications = function(opts, cb) { $.checkState(this.credentials); var self = this; opts = opts || {}; var url = '/v1/notifications/'; if (opts.lastNotificationId) { url += '?notificationId=' + opts.lastNotificationId; } else if (opts.timeSpan) { url += '?timeSpan=' + opts.timeSpan; } self._doGetRequest(url, function(err, result) { if (err) return cb(err); var notifications = _.filter(result, function(notification) { return (notification.creatorId != self.credentials.copayerId); }); return cb(null, notifications); }); }; /** * Get status of the wallet * * @param {object} opts.includeExtendedInfo (optional: query extended status) * @returns {Callback} cb - Returns error or an object with status information */ API.prototype.getStatus = function(opts, cb) { $.checkState(this.credentials); if (!cb) { cb = opts; opts = {}; log.warn('DEPRECATED WARN: getStatus should receive 2 parameters.') } var self = this; opts = opts || {}; self._doGetRequest('/v2/wallets/?includeExtendedInfo=' + (opts.includeExtendedInfo ? '1' : '0'), function(err, result) { if (err) return cb(err); if (result.wallet.status == 'pending') { var c = self.credentials; result.wallet.secret = API._buildSecret(c.walletId, c.walletPrivKey, c.network); } self._processTxps(result.pendingTxps); self._processCustomData(result); return cb(err, result); }); }; /** * Get copayer preferences * * @param {Callback} cb * @return {Callback} cb - Return error or object */ API.prototype.getPreferences = function(cb) { $.checkState(this.credentials && this.credentials.isComplete()); $.checkArgument(cb); var self = this; self._doGetRequest('/v1/preferences/', function(err, preferences) { if (err) return cb(err); return cb(null, preferences); }); }; /** * Save copayer preferences * * @param {Object} preferences * @param {Callback} cb * @return {Callback} cb - Return error or object */ API.prototype.savePreferences = function(preferences, cb) { $.checkState(this.credentials && this.credentials.isComplete()); $.checkArgument(cb); var self = this; self._doPutRequest('/v1/preferences/', preferences, cb); }; API.prototype._computeProposalSignature = function(args) { var hash; if (args.outputs) { $.shouldBeArray(args.outputs); // should match bws server createTx var proposalHeader = { outputs: _.map(args.outputs, function(output) { $.shouldBeNumber(output.amount); return _.pick(output, ['toAddress', 'amount', 'message']); }), message: args.message || null, payProUrl: args.payProUrl || null, }; hash = Utils.getProposalHash(proposalHeader); } else { $.shouldBeNumber(args.amount); hash = Utils.getProposalHash(args.toAddress, args.amount, args.message || null, args.payProUrl || null); } return Utils.signMessage(hash, this.credentials.requestPrivKey); } /** * fetchPayPro * * @param opts.payProUrl URL for paypro request * @returns {Callback} cb - Return error or the parsed payment protocol request * Returns (err,paypro) * paypro.amount * paypro.toAddress * paypro.memo */ API.prototype.fetchPayPro = function(opts, cb) { $.checkArgument(opts) .checkArgument(opts.payProUrl); PayPro.get({ url: opts.payProUrl, http: this.payProHttp, }, function(err, paypro) { if (err) return cb(err || 'Could not fetch PayPro request'); return cb(null, paypro); }); }; /** * Gets list of utxos * * @param {Function} cb * @param {Object} opts * @param {Array} opts.addresses (optional) - List of addresses from where to fetch UTXOs. * @returns {Callback} cb - Return error or the list of utxos */ API.prototype.getUtxos = function(opts, cb) { $.checkState(this.credentials && this.credentials.isComplete()); opts = opts || {}; var url = '/v1/utxos/'; if (opts.addresses) { url += '?' + querystring.stringify({ addresses: [].concat(opts.addresses).join(',') }); } this._doGetRequest(url, cb); }; /** * Send a transaction proposal * * @param {Object} opts * @param {String} opts.toAddress | opts.outputs[].toAddress * @param {Number} opts.amount | opts.outputs[].amount * @param {String} opts.message | opts.outputs[].message * @param {string} opts.feePerKb - Optional: Use an alternative fee per KB for this TX * @param {String} opts.payProUrl - Optional: Tx is from a payment protocol URL * @param {string} opts.excludeUnconfirmedUtxos - Optional: Do not use UTXOs of unconfirmed transactions as inputs * @returns {Callback} cb - Return error or the transaction proposal */ API.prototype.sendTxProposal = function(opts, cb) { $.checkState(this.credentials && this.credentials.isComplete()); $.checkArgument(!opts.message || this.credentials.sharedEncryptingKey, 'Cannot create transaction with message without shared Encrypting key'); $.checkArgument(opts); var self = this; var args = { toAddress: opts.toAddress, amount: opts.amount, message: API._encryptMessage(opts.message, this.credentials.sharedEncryptingKey) || null, feePerKb: opts.feePerKb, payProUrl: opts.payProUrl || null, excludeUnconfirmedUtxos: !!opts.excludeUnconfirmedUtxos, type: opts.type, outputs: _.cloneDeep(opts.outputs), customData: opts.customData }; if (args.outputs) { _.each(args.outputs, function(o) { o.message = API._encryptMessage(o.message, self.credentials.sharedEncryptingKey) || null; }); } log.debug('Generating & signing tx proposal:', JSON.stringify(args)); args.proposalSignature = this._computeProposalSignature(args); this._doPostRequest('/v1/txproposals/', args, function(err, txp) { if (err) return cb(err); return cb(null, txp); }); }; /** * Create a new address * * @param {Callback} cb * @returns {Callback} cb - Return error or the address */ API.prototype.createAddress = function(cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; self._doPostRequest('/v2/addresses/', {}, function(err, address) { if (err) return cb(err); if (!Verifier.checkAddress(self.credentials, address)) { return cb(Errors.SERVER_COMPROMISED); } return cb(null, address); }); }; /** * Get your main addresses * * @param {Object} opts * @param {Boolean} opts.doNotVerify * @param {Numeric} opts.limit (optional) - Limit the resultset. Return all addresses by default. * @param {Boolean} [opts.reverse=false] (optional) - Reverse the order of returned addresses. * @param {Callback} cb * @returns {Callback} cb - Return error or the array of addresses */ API.prototype.getMainAddresses = function(opts, cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; opts = opts || {}; var args = []; if (opts.limit) args.push('limit=' + opts.limit); if (opts.reverse) args.push('reverse=1'); var qs = ''; if (args.length > 0) { qs = '?' + args.join('&'); } var url = '/v1/addresses/' + qs; self._doGetRequest(url, function(err, addresses) { if (err) return cb(err); if (!opts.doNotVerify) { var fake = _.any(addresses, function(address) { return !Verifier.checkAddress(self.credentials, address); }); if (fake) return cb(Errors.SERVER_COMPROMISED); } return cb(null, addresses); }); }; /** * Update wallet balance * * @param {Callback} cb */ API.prototype.getBalance = function(cb) { $.checkState(this.credentials && this.credentials.isComplete()); this._doGetRequest('/v1/balance/', cb); }; /** * Get list of transactions proposals * * @param {Object} opts * @param {Boolean} opts.doNotVerify * @param {Boolean} opts.forAirGapped * @return {Callback} cb - Return error or array of transactions proposals */ API.prototype.getTxProposals = function(opts, cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; self._doGetRequest('/v1/txproposals/', function(err, txps) { if (err) return cb(err); self._processTxps(txps); async.every(txps, function(txp, acb) { if (opts.doNotVerify) return acb(true); self.getPayPro(txp, function(err, paypro) { var isLegit = Verifier.checkTxProposal(self.credentials, txp, { paypro: paypro, }); return acb(isLegit); }); }, function(isLegit) { if (!isLegit) return cb(Errors.SERVER_COMPROMISED); var result; if (opts.forAirGapped) { result = { txps: JSON.parse(JSON.stringify(txps)), encryptedPkr: Utils.encryptMessage(JSON.stringify(self.credentials.publicKeyRing), self.credentials.personalEncryptingKey), m: self.credentials.m, n: self.credentials.n, }; } else { result = txps; } return cb(null, result); }); }); }; API.prototype.getPayPro = function(txp, cb) { var self = this; if (!txp.payProUrl || this.doNotVerifyPayPro) return cb(); PayPro.get({ url: txp.payProUrl, http: self.payProHttp, }, function(err, paypro) { if (err) return cb(new Error('Cannot check transaction now:' + err)); return cb(null, paypro); }); }; /** * Sign a transaction proposal * * @param {Object} txp * @param {Callback} cb * @return {Callback} cb - Return error or object */ API.prototype.signTxProposal = function(txp, cb) { $.checkState(this.credentials && this.credentials.isComplete()); $.checkArgument(txp.creatorId); var self = this; if (!self.canSign() && !txp.signatures) return cb(new Error('You do not have the required keys to sign transactions')); if (self.isPrivKeyEncrypted()) return cb(new Error('Private Key is encrypted, cannot sign')); self.getPayPro(txp, function(err, paypro) { if (err) return cb(err); var isLegit = Verifier.checkTxProposal(self.credentials, txp, { paypro: paypro, }); if (!isLegit) return cb(Errors.SERVER_COMPROMISED); var signatures = txp.signatures || self._signTxp(txp); var url = '/v1/txproposals/' + txp.id + '/signatures/'; var args = { signatures: signatures }; self._doPostRequest(url, args, function(err, txp) { if (err) return cb(err); self._processTxps([txp]); return cb(null, txp); }); }) }; /** * Sign transaction proposal from AirGapped * * @param {Object} txp * @param {String} encryptedPkr * @param {Number} m * @param {Number} n * @return {Object} txp - Return transaction */ API.prototype.signTxProposalFromAirGapped = function(txp, encryptedPkr, m, n) { $.checkState(this.credentials); var self = this; if (!self.canSign()) throw Errors.MISSING_PRIVATE_KEY; if (self.isPrivKeyEncrypted()) throw Errors.ENCRYPTED_PRIVATE_KEY; var publicKeyRing; try { publicKeyRing = JSON.parse(Utils.decryptMessage(encryptedPkr, self.credentials.personalEncryptingKey)); } catch (ex) { throw new Error('Could not decrypt public key ring'); } if (!_.isArray(publicKeyRing) || publicKeyRing.length != n) { throw new Error('Invalid public key ring'); } self.credentials.m = m; self.credentials.n = n; self.credentials.addressType = txp.addressType; self.credentials.addPublicKeyRing(publicKeyRing); if (!Verifier.checkTxProposalBody(self.credentials, txp)) throw new Error('Fake transaction proposal'); return self._signTxp(txp); }; /** * Reject a transaction proposal * * @param {Object} txp * @param {String} reason * @param {Callback} cb * @return {Callback} cb - Return error or object */ API.prototype.rejectTxProposal = function(txp, reason, cb) { $.checkState(this.credentials && this.credentials.isComplete()); $.checkArgument(cb); var self = this; var url = '/v1/txproposals/' + txp.id + '/rejections/'; var args = { reason: API._encryptMessage(reason, self.credentials.sharedEncryptingKey) || '', }; self._doPostRequest(url, args, function(err, txp) { if (err) return cb(err); self._processTxps([txp]); return cb(null, txp); }); }; /** * Broadcast raw transaction * * @param {Object} opts * @param {String} opts.network * @param {String} opts.rawTx * @param {Callback} cb * @return {Callback} cb - Return error or txid */ API.prototype.broadcastRawTx = function(opts, cb) { $.checkState(this.credentials); $.checkArgument(cb); var self = this; opts = opts || {}; var url = '/v1/broadcast_raw/'; self._doPostRequest(url, opts, function(err, txid) { if (err) return cb(err); return cb(null, txid); }); }; API.prototype._doBroadcast = function(txp, cb) { var self = this; var url = '/v1/txproposals/' + txp.id + '/broadcast/'; self._doPostRequest(url, {}, function(err, txp) { if (err) return cb(err); return cb(null, txp); }); }; /** * Broadcast a transaction proposal * * @param {Object} txp * @param {Callback} cb * @return {Callback} cb - Return error or object */ API.prototype.broadcastTxProposal = function(txp, cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; self.getPayPro(txp, function(err, paypro) { if (paypro) { var t = API.buildTx(txp); self.createAddress(function(err, addr) { if (err) return cb(err); PayPro.send({ http: self.payProHttp, url: txp.payProUrl, amountSat: txp.amount, refundAddr: addr.address, merchant_data: paypro.merchant_data, rawTx: t.uncheckedSerialize(), }, function(err, ack, memo) { if (err) return cb(err); self._doBroadcast(txp, function(err, txp) { return cb(err, txp, memo); }); }); }); } else { self._doBroadcast(txp, cb); } }); }; /** * Remove a transaction proposal * * @param {Object} txp * @param {Callback} cb * @return {Callback} cb - Return error or empty */ API.prototype.removeTxProposal = function(txp, cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; var url = '/v1/txproposals/' + txp.id; self._doDeleteRequest(url, function(err) { return cb(err); }); }; /** * Get transaction history * * @param {Object} opts * @param {Number} opts.skip (defaults to 0) * @param {Number} opts.limit * @param {Callback} cb * @return {Callback} cb - Return error or array of transactions */ API.prototype.getTxHistory = function(opts, cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; var args = []; if (opts) { if (opts.skip) args.push('skip=' + opts.skip); if (opts.limit) args.push('limit=' + opts.limit); } var qs = ''; if (args.length > 0) { qs = '?' + args.join('&'); } var url = '/v1/txhistory/' + qs; self._doGetRequest(url, function(err, txs) { if (err) return cb(err); self._processTxps(txs); return cb(null, txs); }); }; /** * getTx * * @param {String} TransactionId * @return {Callback} cb - Return error or transaction */ API.prototype.getTx = function(id, cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; var url = '/v1/txproposals/' + id; this._doGetRequest(url, function(err, tx) { if (err) return cb(err); self._processTxps([tx]); return cb(null, tx); }); }; /** * Start an address scanning process. * When finished, the scanning process will send a notification 'ScanFinished' to all copayers. * * @param {Object} opts * @param {Boolean} opts.includeCopayerBranches (defaults to false) * @param {Callback} cb */ API.prototype.startScan = function(opts, cb) { $.checkState(this.credentials && this.credentials.isComplete()); var self = this; var args = { includeCopayerBranches: opts.includeCopayerBranches, }; self._doPostRequest('/v1/addresses/scan', args, function(err) { return cb(err); }); }; /* * * Compatibility Functions * */ API.prototype._oldCopayDecrypt = function(username, password, blob) { var SEP1 = '@#$'; var SEP2 = '%^#@'; var decrypted; try { var passphrase = username + SEP1 + password; decrypted = sjcl.decrypt(passphrase, blob); } catch (e) { passphrase = username + SEP2 + password; try { decrypted = sjcl.decrypt(passphrase, blob); } catch (e) { log.debug(e); }; } if (!decrypted) return null; var ret; try { ret = JSON.parse(decrypted); } catch (e) {}; return ret; }; API.prototype.getWalletIdsFromOldCopay = function(username, password, blob) { var p = this._oldCopayDecrypt(username, password, blob); if (!p) return null; var ids = p.walletIds.concat(_.keys(p.focusedTimestamps)); return _.uniq(ids); }; /** * createWalletFromOldCopay * * @param username * @param password * @param blob * @param cb * @return {undefined} */ API.prototype.createWalletFromOldCopay = function(username, password, blob, cb) { var self = this; var w = this._oldCopayDecrypt(username, password, blob); if (!w) return cb('Could not decrypt'); if (w.publicKeyRing.copayersExtPubKeys.length != w.opts.totalCopayers) return cb('Wallet is incomplete, cannot be imported'); this.credentials = Credentials.fromOldCopayWallet(w); this.recreateWallet(cb); }; /* Adds access to the current copayer * @param {Object} opts * @param {bool} opts.generateNewKey Optional: generate a new key for the new access * @param {string} opts.restrictions * - cannotProposeTXs * - cannotXXX TODO * @param {string} opts.name (name for the new access) * * return the accesses Wallet and the requestPrivateKey */ API.prototype.addAccess = function(opts, cb) { $.checkState(this.credentials && this.credentials.canSign()); var reqPrivKey = new Bitcore.PrivateKey(opts.generateNewKey ? null : this.credentials.requestPrivKey); var requestPubKey = reqPrivKey.toPublicKey().toString(); var xPriv = new Bitcore.HDPrivateKey(this.credentials.xPrivKey) .derive(this.credentials.getBaseAddressDerivationPath()); var sig = Utils.signRequestPubKey(requestPubKey, xPriv); var copayerId = this.credentials.copayerId; var opts = { copayerId: copayerId, requestPubKey: requestPubKey, signature: sig, name: opts.name, restrictions: opts.restrictions, }; this._doPutRequest('/v1/copayers/' + copayerId + '/', opts, function(err, res) { if (err) return cb(err); return cb(null, res.wallet, reqPrivKey); }); }; module.exports = API;
Fix buildTx for MULTIPLEOUTPUTS proposal without change Size of ``outputOrder`` array always assumes that change output will be added. This leads to failed assertion in ``buildTx`` when no change output needed.
lib/api.js
Fix buildTx for MULTIPLEOUTPUTS proposal without change
<ide><path>ib/api.js <ide> <ide> // Shuffle outputs for improved privacy <ide> if (t.outputs.length > 1) { <del> $.checkState(t.outputs.length == txp.outputOrder.length); <add> var outputOrder = txp.outputOrder; <add> if (!t.getChangeOutput()) { <add> outputOrder = _.dropRight(outputOrder); <add> } <add> $.checkState(t.outputs.length == outputOrder.length); <ide> t.sortOutputs(function(outputs) { <del> return _.map(txp.outputOrder, function(i) { <add> return _.map(outputOrder, function(i) { <ide> return outputs[i]; <ide> }); <ide> });
JavaScript
mit
1f351dcedf3a230e7c97b95ca4d2dcb2baa0852f
0
Rundiz/rundiz-template-for-admin,Rundiz/rundiz-template-for-admin,Rundiz/rundiz-template-for-admin
GruntFile.js
/** * @link https://gruntjs.com/configuring-tasks#building-the-files-object-dynamically Building the files object dynamically * @link https://github.com/laurenhamel/grunt-dart-sass Dart-sass on Grunt */ module.exports = function (grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // Compile SASS and minify them. 'dart-sass': { target: { options: { outputStyle: 'expanded', sourceMap: true }, files: [ { expand: true, cwd: 'assets/scss/', src: ['**/*.scss'], dest: 'assets/css/', ext: '.css' } ] }, targetMinified: { options: { outputStyle: 'compressed', sourceMap: true }, files: [ { expand: true, cwd: 'assets/scss/', src: ['**/*.scss'], dest: 'assets/css/', ext: '.min.css', extDot: 'first' } ] } }, // Replace version number. 'string-replace': { dist: { options: { replacements: [ {pattern: '__RDTA.VERSION__', replacement: '<%= pkg.version %>'} ] }, files: [ { expand: true, cwd: 'assets/css/rdta/', src: ['*.css'], dest: 'assets/css/rdta/' } ] } }, // Minify JS. uglify: { myjs: { options: { banner: '/*! Rundiz template for admin v <%= pkg.version %> \n' + 'License: <%= pkg.license %>*/', sourceMap: true, sourceMapName: "assets/js/rdta/rundiz-template-admin.min.map" }, files: [ {src: 'assets/js/rdta/rundiz-template-admin.js', dest: 'assets/js/rdta/rundiz-template-admin.min.js'} ] } }, watch: { files: ['assets/js/rdta/*.js', 'assets/scss/**/*.scss'], tasks: ['uglify', 'dart-sass']// no need to replace version number on development. } }); // Load the plugin that provides the "uglify" task. grunt.loadNpmTasks('grunt-contrib-uglify-es'); // Load the plugin that watch files changed. grunt.loadNpmTasks('grunt-contrib-watch'); // Load the plugin that will compile SASS. grunt.loadNpmTasks('grunt-dart-sass'); // Load the plugin that replace text string in file. grunt.loadNpmTasks('grunt-string-replace'); // Default task(s). grunt.registerTask('default', ['uglify', 'dart-sass', 'string-replace']); };
Remove grunt file.
GruntFile.js
Remove grunt file.
<ide><path>runtFile.js <del>/** <del> * @link https://gruntjs.com/configuring-tasks#building-the-files-object-dynamically Building the files object dynamically <del> * @link https://github.com/laurenhamel/grunt-dart-sass Dart-sass on Grunt <del> */ <del>module.exports = function (grunt) { <del> <del> // Project configuration. <del> grunt.initConfig({ <del> pkg: grunt.file.readJSON('package.json'), <del> // Compile SASS and minify them. <del> 'dart-sass': { <del> target: { <del> options: { <del> outputStyle: 'expanded', <del> sourceMap: true <del> }, <del> files: [ <del> { <del> expand: true, <del> cwd: 'assets/scss/', <del> src: ['**/*.scss'], <del> dest: 'assets/css/', <del> ext: '.css' <del> } <del> ] <del> }, <del> targetMinified: { <del> options: { <del> outputStyle: 'compressed', <del> sourceMap: true <del> }, <del> files: [ <del> { <del> expand: true, <del> cwd: 'assets/scss/', <del> src: ['**/*.scss'], <del> dest: 'assets/css/', <del> ext: '.min.css', <del> extDot: 'first' <del> } <del> ] <del> } <del> }, <del> // Replace version number. <del> 'string-replace': { <del> dist: { <del> options: { <del> replacements: [ <del> {pattern: '__RDTA.VERSION__', replacement: '<%= pkg.version %>'} <del> ] <del> }, <del> files: [ <del> { <del> expand: true, <del> cwd: 'assets/css/rdta/', <del> src: ['*.css'], <del> dest: 'assets/css/rdta/' <del> } <del> ] <del> } <del> }, <del> // Minify JS. <del> uglify: { <del> myjs: { <del> options: { <del> banner: '/*! Rundiz template for admin v <%= pkg.version %> \n' + <del> 'License: <%= pkg.license %>*/', <del> sourceMap: true, <del> sourceMapName: "assets/js/rdta/rundiz-template-admin.min.map" <del> }, <del> files: [ <del> {src: 'assets/js/rdta/rundiz-template-admin.js', dest: 'assets/js/rdta/rundiz-template-admin.min.js'} <del> ] <del> } <del> }, <del> watch: { <del> files: ['assets/js/rdta/*.js', 'assets/scss/**/*.scss'], <del> tasks: ['uglify', 'dart-sass']// no need to replace version number on development. <del> } <del> }); <del> <del> // Load the plugin that provides the "uglify" task. <del> grunt.loadNpmTasks('grunt-contrib-uglify-es'); <del> // Load the plugin that watch files changed. <del> grunt.loadNpmTasks('grunt-contrib-watch'); <del> // Load the plugin that will compile SASS. <del> grunt.loadNpmTasks('grunt-dart-sass'); <del> // Load the plugin that replace text string in file. <del> grunt.loadNpmTasks('grunt-string-replace'); <del> <del> // Default task(s). <del> grunt.registerTask('default', ['uglify', 'dart-sass', 'string-replace']); <del> <del>};
Java
apache-2.0
4173e1f60f165736b50c150919803321569aba1d
0
juve/corral,juve/corral,juve/corral
package edu.usc.glidein.service.impl; import java.io.BufferedReader; import java.io.CharArrayWriter; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import javax.naming.NamingException; import org.apache.axis.message.addressing.EndpointReferenceType; import org.apache.log4j.Logger; import org.globus.delegation.DelegationException; import org.globus.delegation.DelegationUtil; import org.globus.delegation.service.DelegationResource; import org.globus.gsi.GlobusCredential; import org.globus.wsrf.PersistenceCallback; import org.globus.wsrf.Resource; import org.globus.wsrf.ResourceException; import org.globus.wsrf.ResourceIdentifier; import org.globus.wsrf.ResourceKey; import org.globus.wsrf.ResourceProperties; import org.globus.wsrf.ResourcePropertySet; import org.globus.wsrf.impl.ReflectionResourceProperty; import org.globus.wsrf.impl.SimpleResourceKey; import org.globus.wsrf.impl.SimpleResourcePropertySet; import edu.usc.glidein.service.ServiceConfiguration; import edu.usc.glidein.service.db.Database; import edu.usc.glidein.service.db.DatabaseException; import edu.usc.glidein.service.db.GlideinDAO; import edu.usc.glidein.service.exec.Condor; import edu.usc.glidein.service.exec.CondorException; import edu.usc.glidein.service.exec.CondorGridType; import edu.usc.glidein.service.exec.CondorJob; import edu.usc.glidein.service.exec.CondorUniverse; import edu.usc.glidein.service.state.Event; import edu.usc.glidein.service.state.EventQueue; import edu.usc.glidein.service.state.GlideinEvent; import edu.usc.glidein.service.state.GlideinEventCode; import edu.usc.glidein.service.state.GlideinListener; import edu.usc.glidein.service.state.SiteEvent; import edu.usc.glidein.service.state.SiteEventCode; import edu.usc.glidein.stubs.types.EnvironmentVariable; import edu.usc.glidein.stubs.types.ExecutionService; import edu.usc.glidein.stubs.types.Glidein; import edu.usc.glidein.stubs.types.GlideinState; import edu.usc.glidein.stubs.types.ServiceType; import edu.usc.glidein.stubs.types.Site; import edu.usc.glidein.stubs.types.SiteState; import edu.usc.glidein.util.AddressingUtil; import edu.usc.glidein.util.Base64; import edu.usc.glidein.util.CredentialUtil; import edu.usc.glidein.util.IOUtil; public class GlideinResource implements Resource, ResourceIdentifier, PersistenceCallback, ResourceProperties { private Logger logger = Logger.getLogger(GlideinResource.class); private SimpleResourcePropertySet resourceProperties; private Glidein glidein = null; /** * Default constructor required */ public GlideinResource() { } public void setGlidein(Glidein glidein) throws ResourceException { this.glidein = glidein; setResourceProperties(); } public Glidein getGlidein() { return glidein; } public Object getID() { return getKey(); } public ResourceKey getKey() { if (glidein == null) return null; return new SimpleResourceKey( GlideinNames.RESOURCE_KEY, new Integer(glidein.getId())); } public ResourcePropertySet getResourcePropertySet() { return resourceProperties; } private void setResourceProperties() throws ResourceException { try { resourceProperties = new SimpleResourcePropertySet(GlideinNames.RESOURCE_PROPERTIES); resourceProperties.add(new ReflectionResourceProperty(GlideinNames.RP_GLIDEIN_ID,"Id",glidein)); // TODO: Set the rest of the resource properties, or don't } catch(Exception e) { throw new ResourceException("Unable to set glidein resource properties",e); } } public void create(Glidein glidein) throws ResourceException { info("Creating glidein for site "+glidein.getSiteId()); // Initialize glidein glidein.setState(GlideinState.NEW); glidein.setShortMessage("Created"); // Save in the database try { Database db = Database.getDatabase(); GlideinDAO dao = db.getGlideinDAO(); dao.create(glidein); } catch (DatabaseException dbe) { throw new ResourceException(dbe); } // Set glidein setGlidein(glidein); } public void load(ResourceKey key) throws ResourceException { info("Loading glidein "+key.getValue()); int id = ((Integer)key.getValue()).intValue(); try { Database db = Database.getDatabase(); GlideinDAO dao = db.getGlideinDAO(); setGlidein(dao.load(id)); } catch(DatabaseException de) { throw new ResourceException(de); } } public void store() throws ResourceException { throw new UnsupportedOperationException(); } public void remove(boolean force) throws ResourceException { info("Removing glidein"); // If we are forcing the issue, then just delete it GlideinEventCode code = null; if (force) { code = GlideinEventCode.DELETE; } else { code = GlideinEventCode.REMOVE; } // Queue the event try { Event event = new GlideinEvent(code,getKey()); EventQueue queue = EventQueue.getInstance(); queue.add(event); } catch(NamingException ne) { throw new ResourceException("Unable to remove glidein",ne); } } public void submit(EndpointReferenceType credentialEPR) throws ResourceException { info("Submitting glidein"); try { // Get delegated credential DelegationResource delegationResource = DelegationUtil.getDelegationResource(credentialEPR); GlobusCredential credential = delegationResource.getCredential(); // Validate credential lifetime if (glidein.getWallTime()*60 > credential.getTimeLeft()) { throw new ResourceException("Credential does not have enough time left. " + "Need: "+(glidein.getWallTime()*60)+", have: "+credential.getTimeLeft()); } // Create submit event Event event = new GlideinEvent(GlideinEventCode.SUBMIT,getKey()); event.setProperty("credential", credential); EventQueue queue = EventQueue.getInstance(); queue.add(event); } catch (NamingException ne) { throw new ResourceException("Unable to submit glidein: "+ne.getMessage(),ne); } catch (DelegationException de) { throw new ResourceException("Unable to submit glidein: "+de.getMessage(),de); } } private void updateState(GlideinState state, String shortMessage, String longMessage) throws ResourceException { info("Changing state to "+state+": "+shortMessage); // Update object glidein.setState(state); glidein.setShortMessage(shortMessage); glidein.setLongMessage(longMessage); // Update database try { Database db = Database.getDatabase(); GlideinDAO dao = db.getGlideinDAO(); dao.updateState(glidein.getId(), state, shortMessage, longMessage); } catch(DatabaseException de) { throw new ResourceException(de); } } private void submitGlideinJob(GlobusCredential credential) throws ResourceException { info("Submitting glidein job"); SiteResource siteResource = getSiteResource(); Site site = siteResource.getSite(); // Get configuration ServiceConfiguration config; try { config = ServiceConfiguration.getInstance(); } catch (NamingException ne) { throw new ResourceException("Unable to submit glideing job: " + "Unable to get configuration",ne); } // Create working directory File jobDirectory = getWorkingDirectory(); // Create a job description CondorJob job = new CondorJob(jobDirectory); job.setUniverse(CondorUniverse.GRID); // Set jobmanager info ExecutionService glideinService = site.getGlideinService(); if(ServiceType.GT2.equals(glideinService.getServiceType())) job.setGridType(CondorGridType.GT2); else job.setGridType(CondorGridType.GT4); job.setGridContact(glideinService.getServiceContact()); job.setProject(glideinService.getProject()); job.setQueue(glideinService.getQueue()); // Set glidein executable String run = config.getRun(); job.setExecutable(run); job.setLocalExecutable(true); // Set number of processes job.setHostCount(glidein.getHostCount()); job.setCount(glidein.getCount()); job.setMaxTime(glidein.getWallTime()); // Add environment EnvironmentVariable env[] = site.getEnvironment(); if (env!=null) { for (EnvironmentVariable var : env) job.addEnvironment(var.getVariable(), var.getValue()); } // Add arguments job.addArgument("-installPath "+site.getInstallPath()); job.addArgument("-localPath "+site.getLocalPath()); job.addArgument("-condorHost "+glidein.getCondorHost()); job.addArgument("-wallTime "+glidein.getWallTime()); if(glidein.getGcbBroker()!=null) job.addArgument("-gcbBroker "+glidein.getGcbBroker()); if(glidein.getIdleTime()>0) job.addArgument("-idleTime "+glidein.getIdleTime()); if(glidein.getCondorDebug()!=null) { String[] debug = glidein.getCondorDebug().split("[ ,]+"); for(String level : debug) job.addArgument("-debug "+level); } if(glidein.getNumCpus()>0) job.addArgument("-numCpus "+glidein.getNumCpus()); // If there is a special config file, use it String configFile = null; if (glidein.getCondorConfig()==null) { configFile = config.getGlideinCondorConfig(); } else { try { // Save config to a file in the submit directory configFile = "glidein_condor_config"; String cfg = Base64.fromBase64(glidein.getCondorConfig()); IOUtil.write(cfg, new File(job.getJobDirectory(),configFile)); } catch (IOException ioe) { throw new ResourceException("Unable to submit glidein job: " + "Error writing glidein_condor_config",ioe); } } job.addInputFile(configFile); job.setCredential(credential); // Add a listener job.addListener(new GlideinListener(getKey())); // Submit job try { Condor condor = Condor.getInstance(); condor.submitJob(job); } catch (CondorException ce) { throw new ResourceException("Unable to submit glidein job: " + "Submit failed",ce); } } private boolean siteReady() throws ResourceException { SiteResource resource = getSiteResource(); SiteState state = resource.getSite().getState(); return SiteState.READY.equals(state); } private SiteResource getSiteResource() throws ResourceException { try { ResourceKey key = AddressingUtil.getSiteKey(glidein.getSiteId()); SiteResourceHome home = SiteResourceHome.getInstance(); SiteResource resource = (SiteResource)home.find(key); return resource; } catch (NamingException ne) { throw new ResourceException("Unable to get SiteResourceHome",ne); } } private void cancelGlideinJob() throws ResourceException { info("Cancelling glidein job"); // Find submit dir File dir = getWorkingDirectory(); File jobidFile = new File(dir,"jobid"); try { // Read job id from jobid file BufferedReader reader = new BufferedReader( new FileReader(jobidFile)); String jobid = reader.readLine(); reader.close(); // condor_rm job Condor.getInstance().cancelJob(jobid); } catch (IOException ioe) { throw new ResourceException( "Unable to cancel glidein job: Unable to read job id",ioe); } catch (CondorException ce) { throw new ResourceException( "Unable to cancel glidein job: condor_rm failed",ce); } } private void delete() throws ResourceException { try { Database db = Database.getDatabase(); GlideinDAO dao = db.getGlideinDAO(); dao.delete(glidein.getId()); } catch(DatabaseException de) { throw new ResourceException(de); } } private ServiceConfiguration getConfig() throws ResourceException { try { return ServiceConfiguration.getInstance(); } catch (NamingException ne) { throw new ResourceException("Unable to get service configuration",ne); } } private File getWorkingDirectory() throws ResourceException { File dir = new File(getConfig().getTempDir(),"glidein-"+glidein.getId()); // Create the directory if it doesn't exist if (dir.exists()) { if (!dir.isDirectory()) { throw new ResourceException( "Working directory is not a directory"); } } else { try { if (!dir.mkdirs()) { throw new ResourceException( "Unable to create working directory"); } } catch (SecurityException e) { throw new ResourceException( "Unable to create working directory"); } } return dir; } private void storeCredential(GlobusCredential credential) throws ResourceException { try { File work = getWorkingDirectory(); File credFile = new File(work,"credential"); CredentialUtil.store(credential,credFile); } catch (IOException ioe) { throw new ResourceException("Unable to store credential"); } } private GlobusCredential loadCredential() throws ResourceException { try { File work = getWorkingDirectory(); File credFile = new File(work,"credential"); GlobusCredential credential = CredentialUtil.load(credFile); return credential; } catch (IOException ioe) { throw new ResourceException("Unable to load credential"); } } private void fail(String message, Exception exception) { // Update status to FAILED error("Failure: "+message,exception); CharArrayWriter caw = new CharArrayWriter(); exception.printStackTrace(new PrintWriter(caw)); try { updateState(GlideinState.FAILED, message, caw.toString()); } catch (ResourceException re) { error("Unable to change state to "+GlideinState.FAILED,re); } } public synchronized void handleEvent(GlideinEvent event) { GlideinState state = glidein.getState(); GlideinEventCode code = (GlideinEventCode) event.getCode(); // If the glidein was deleted, then don't process any more events if (GlideinState.DELETED.equals(state)) { warn("Unable to process event "+code+": "+ "Glidein has been deleted"); return; } switch (code) { case SUBMIT: { // Only NEW glideins can be submitted if (GlideinState.NEW.equals(state)) { GlobusCredential credential = (GlobusCredential)event.getProperty("credential"); // Check to see if site is ready boolean ready = false; try { ready = siteReady(); } catch (ResourceException re) { fail("Unable to check for site ready state",re); } // If the site is ready, submit the glidein job, otherwise wait if (ready) { try { submitGlideinJob(credential); updateState(GlideinState.SUBMITTED,"Local job submitted",null); } catch (ResourceException re) { fail("Unable to submit job",re); } } else { try { storeCredential(credential); updateState(GlideinState.WAITING,"Waiting for site to be "+SiteState.READY,null); } catch (ResourceException re) { fail("Unable to wait for site ready state",re); } } } } break; case SITE_READY: { // If we are waiting, then queue a SUBMIT event if (GlideinState.WAITING.equals(state)) { try { GlobusCredential credential = loadCredential(); submitGlideinJob(credential); updateState(GlideinState.SUBMITTED,"Local job submitted",null); } catch (ResourceException re) { fail("Unable to submit job",re); } } } break; case QUEUED: { if (GlideinState.SUBMITTED.equals(state)) { try { updateState(GlideinState.QUEUED,"Glidein job queued",null); } catch (ResourceException re) { fail("Unable to set state to "+GlideinState.QUEUED,re); } } } break; case RUNNING: { try { updateState(GlideinState.RUNNING,"Glidein job running",null); } catch (ResourceException re) { fail("Unable to set state to "+GlideinState.RUNNING,re); } } break; case REMOVE: case JOB_SUCCESS: case DELETE: { // If the user requested remove if (GlideinEventCode.REMOVE.equals(code)) { // If a glidein job has been submitted cancel the job if (GlideinState.SUBMITTED.equals(state) || GlideinState.RUNNING.equals(state) || GlideinState.QUEUED.equals(state)) { try { cancelGlideinJob(); } catch (ResourceException re) { fail("Unable to cancel glidein job",re); } } } // Change the status to deleted glidein.setState(GlideinState.DELETED); // Remove the glidein from the ResourceHome try { GlideinResourceHome home = GlideinResourceHome.getInstance(); home.remove(getKey()); } catch (NamingException e) { fail("Unable to locate GlideinResourceHome",e); return; } catch (ResourceException re) { fail("Unable to remove glidein from GlideinResourceHome",re); return; } // Delete the glidein from the database try { delete(); } catch (ResourceException re) { fail("Unable to delete glidein from database",re); return; } // Tell the Site About it try { ResourceKey siteKey = AddressingUtil.getSiteKey(glidein.getSiteId()); Event siteEvent = new SiteEvent(SiteEventCode.GLIDEIN_DELETED, siteKey); EventQueue queue = EventQueue.getInstance(); queue.add(siteEvent); } catch (NamingException ne) { warn("Unable to notify site of deleted glidein",ne); } // Remove the working directory try { IOUtil.rmdirs(getWorkingDirectory()); } catch (ResourceException re) { warn("Unable to remove working dir",re); } } break; case JOB_FAILURE: { fail((String)event.getProperty("message"), (Exception)event.getProperty("exception")); } break; default: { IllegalStateException ise = new IllegalStateException(); ise.fillInStackTrace(); error("Unhandled event: "+event,ise); } break; } } private String logPrefix() { if (glidein == null) { return ""; } else { return "Glidein "+glidein.getId()+": "; } } public void debug(String message) { debug(message,null); } public void debug(String message, Throwable t) { logger.debug(logPrefix()+message, t); } public void info(String message) { info(message,null); } public void info(String message, Throwable t) { logger.info(logPrefix()+message,t); } public void warn(String message) { warn(message,null); } public void warn(String message, Throwable t) { logger.warn(logPrefix()+message,t); } public void error(String message) { error(message,null); } public void error(String message, Throwable t) { logger.error(logPrefix()+message,t); } }
src/edu/usc/glidein/service/impl/GlideinResource.java
package edu.usc.glidein.service.impl; import java.io.File; import java.io.IOException; import javax.naming.NamingException; import org.apache.axis.message.addressing.EndpointReferenceType; import org.apache.log4j.Logger; import org.globus.delegation.DelegationException; import org.globus.delegation.DelegationUtil; import org.globus.delegation.service.DelegationResource; import org.globus.gsi.GlobusCredential; import org.globus.wsrf.PersistenceCallback; import org.globus.wsrf.RemoveCallback; import org.globus.wsrf.Resource; import org.globus.wsrf.ResourceException; import org.globus.wsrf.ResourceIdentifier; import org.globus.wsrf.ResourceKey; import org.globus.wsrf.ResourceProperties; import org.globus.wsrf.ResourcePropertySet; import org.globus.wsrf.impl.ReflectionResourceProperty; import org.globus.wsrf.impl.SimpleResourceKey; import org.globus.wsrf.impl.SimpleResourcePropertySet; import edu.usc.glidein.service.ServiceConfiguration; import edu.usc.glidein.service.db.Database; import edu.usc.glidein.service.db.DatabaseException; import edu.usc.glidein.service.db.GlideinDAO; import edu.usc.glidein.service.exec.Condor; import edu.usc.glidein.service.exec.CondorException; import edu.usc.glidein.service.exec.CondorGridType; import edu.usc.glidein.service.exec.CondorJob; import edu.usc.glidein.service.exec.CondorUniverse; import edu.usc.glidein.service.state.Event; import edu.usc.glidein.service.state.EventQueue; import edu.usc.glidein.service.state.GlideinEvent; import edu.usc.glidein.service.state.GlideinEventCode; import edu.usc.glidein.service.state.GlideinListener; import edu.usc.glidein.stubs.types.EnvironmentVariable; import edu.usc.glidein.stubs.types.ExecutionService; import edu.usc.glidein.stubs.types.Glidein; import edu.usc.glidein.stubs.types.GlideinState; import edu.usc.glidein.stubs.types.ServiceType; import edu.usc.glidein.stubs.types.Site; import edu.usc.glidein.stubs.types.SiteState; import edu.usc.glidein.util.AddressingUtil; import edu.usc.glidein.util.Base64; import edu.usc.glidein.util.IOUtil; public class GlideinResource implements Resource, ResourceIdentifier, PersistenceCallback, RemoveCallback, ResourceProperties { private Logger logger = Logger.getLogger(GlideinResource.class); private SimpleResourcePropertySet resourceProperties; private Glidein glidein = null; /** * Default constructor required */ public GlideinResource() { } public void setGlidein(Glidein glidein) throws ResourceException { this.glidein = glidein; setResourceProperties(); } public Glidein getGlidein() { return glidein; } public Object getID() { return getKey(); } public ResourceKey getKey() { if (glidein == null) return null; return new SimpleResourceKey( GlideinNames.RESOURCE_KEY, new Integer(glidein.getId())); } public ResourcePropertySet getResourcePropertySet() { return resourceProperties; } private void setResourceProperties() throws ResourceException { try { resourceProperties = new SimpleResourcePropertySet(GlideinNames.RESOURCE_PROPERTIES); resourceProperties.add(new ReflectionResourceProperty(GlideinNames.RP_GLIDEIN_ID,"Id",glidein)); // TODO: Set the rest of the resource properties, or don't } catch(Exception e) { throw new ResourceException("Unable to set glidein resource properties",e); } } public void create(Glidein glidein) throws ResourceException { logger.debug("Creating glidein for site "+glidein.getSiteId()); // Initialize glidein glidein.setState(GlideinState.NEW); glidein.setShortMessage("Created"); // Save in the database try { Database db = Database.getDatabase(); GlideinDAO dao = db.getGlideinDAO(); dao.create(glidein); } catch (DatabaseException dbe) { throw new ResourceException(dbe); } // Set glidein setGlidein(glidein); } public void load(ResourceKey key) throws ResourceException { logger.debug("Loading "+key.getValue()); int id = ((Integer)key.getValue()).intValue(); try { Database db = Database.getDatabase(); GlideinDAO dao = db.getGlideinDAO(); setGlidein(dao.load(id)); } catch(DatabaseException de) { throw new ResourceException(de); } } public void store() throws ResourceException { logger.debug("Storing "+getGlidein().getId()); throw new ResourceException("Tried to store GlideinResource"); /* try { Database db = Database.getDatabase(); GlideinDAO dao = db.getGlideinDAO(); dao.store(glidein); } catch(DatabaseException de) { throw new ResourceException(de); } */ } public void remove() throws ResourceException { remove(false); } public void remove(boolean force) throws ResourceException { logger.debug("Removing "+getGlidein().getId()); // If we are forcing the issue, then just delete it GlideinEventCode code = null; if (force) { code = GlideinEventCode.DELETE; } else { code = GlideinEventCode.REMOVE; } // Queue the event try { Event event = new GlideinEvent(code,getKey()); EventQueue queue = EventQueue.getInstance(); queue.add(event); } catch(NamingException ne) { throw new ResourceException("Unable to remove glidein",ne); } } public void submit(EndpointReferenceType credentialEPR) throws ResourceException { logger.debug("Submitting "+glidein.getId()); try { // Get delegated credential DelegationResource delegationResource = DelegationUtil.getDelegationResource(credentialEPR); GlobusCredential credential = delegationResource.getCredential(); // Validate credential lifetime if (glidein.getWallTime()*60 > credential.getTimeLeft()) { throw new ResourceException("Credential does not have enough time left. " + "Need: "+(glidein.getWallTime()*60)+", have: "+credential.getTimeLeft()); } // Create submit event Event event = new GlideinEvent(GlideinEventCode.SUBMIT,getKey()); event.setProperty("credential", credential); EventQueue queue = EventQueue.getInstance(); queue.add(event); } catch (NamingException ne) { throw new ResourceException("Unable to submit glidein: "+ne.getMessage(),ne); } catch (DelegationException de) { throw new ResourceException("Unable to submit glidein: "+de.getMessage(),de); } } private void updateState(GlideinState state, String shortMessage, String longMessage) throws ResourceException { logger.debug("Changing state of glidein "+getGlidein().getId()+" to "+state+": "+shortMessage); // Update object glidein.setState(state); glidein.setShortMessage(shortMessage); glidein.setLongMessage(longMessage); // Update database try { Database db = Database.getDatabase(); GlideinDAO dao = db.getGlideinDAO(); dao.updateState(glidein.getId(), state, shortMessage, longMessage); } catch(DatabaseException de) { throw new ResourceException(de); } } private void submitGlideinJob(GlobusCredential credential) throws ResourceException { logger.debug("Submitting glidein job "+glidein.getId()); SiteResource siteResource = getSiteResource(); Site site = siteResource.getSite(); // Get configuration ServiceConfiguration config; try { config = ServiceConfiguration.getInstance(); } catch (NamingException ne) { throw new ResourceException("Unable to submit glideing job: " + "Unable to get configuration",ne); } // Create working directory File jobDirectory = new File(config.getTempDir(),"glidein-"+glidein.getId()); // Create a job description CondorJob job = new CondorJob(jobDirectory); job.setUniverse(CondorUniverse.GRID); // Set jobmanager info ExecutionService glideinService = site.getGlideinService(); if(ServiceType.GT2.equals(glideinService.getServiceType())) job.setGridType(CondorGridType.GT2); else job.setGridType(CondorGridType.GT4); job.setGridContact(glideinService.getServiceContact()); job.setProject(glideinService.getProject()); job.setQueue(glideinService.getQueue()); // Set glidein executable String run = config.getRun(); job.setExecutable(run); job.setLocalExecutable(true); // Set number of processes job.setHostCount(glidein.getHostCount()); job.setCount(glidein.getCount()); job.setMaxTime(glidein.getWallTime()); // Add environment EnvironmentVariable env[] = site.getEnvironment(); if (env!=null) { for (EnvironmentVariable var : env) job.addEnvironment(var.getVariable(), var.getValue()); } // Add arguments job.addArgument("-installPath "+site.getInstallPath()); job.addArgument("-localPath "+site.getLocalPath()); job.addArgument("-condorHost "+glidein.getCondorHost()); job.addArgument("-wallTime "+glidein.getWallTime()); if(glidein.getGcbBroker()!=null) job.addArgument("-gcbBroker "+glidein.getGcbBroker()); if(glidein.getIdleTime()>0) job.addArgument("-idleTime "+glidein.getIdleTime()); if(glidein.getCondorDebug()!=null) { String[] debug = glidein.getCondorDebug().split("[ ,]+"); for(String level : debug) job.addArgument("-debug "+level); } if(glidein.getNumCpus()>0) job.addArgument("-numCpus "+glidein.getNumCpus()); // If there is a special config file, use it String configFile = null; if (glidein.getCondorConfig()==null) { configFile = config.getGlideinCondorConfig(); } else { try { // Save config to a file in the submit directory configFile = "glidein_condor_config"; String cfg = Base64.fromBase64(glidein.getCondorConfig()); IOUtil.write(cfg, new File(job.getJobDirectory(),configFile)); } catch (IOException ioe) { throw new ResourceException("Unable to submit glidein job: " + "Error writing glidein_condor_config",ioe); } } job.addInputFile(configFile); job.setCredential(credential); // Add a listener job.addListener(new GlideinListener(getKey())); // Submit job try { Condor condor = Condor.getInstance(); condor.submitJob(job); } catch (CondorException ce) { throw new ResourceException("Unable to submit glidein job: " + "Submit failed",ce); } logger.debug("Submitted glidein job '"+glidein.getId()+"'"); } private boolean siteReady() throws ResourceException { SiteResource resource = getSiteResource(); SiteState state = resource.getSite().getState(); return SiteState.READY.equals(state); } private SiteResource getSiteResource() throws ResourceException { try { ResourceKey key = AddressingUtil.getSiteKey(glidein.getSiteId()); SiteResourceHome home = SiteResourceHome.getInstance(); SiteResource resource = (SiteResource)home.find(key); return resource; } catch (NamingException ne) { throw new ResourceException("Unable to get SiteResourceHome",ne); } } private void cancelGlideinJob() throws ResourceException { // TODO: Cancel glidein job } private void delete() throws ResourceException { try { Database db = Database.getDatabase(); GlideinDAO dao = db.getGlideinDAO(); dao.delete(glidein.getId()); glidein = null; resourceProperties = null; } catch(DatabaseException de) { throw new ResourceException(de); } } public synchronized void handleEvent(GlideinEvent event) { /* TODO: Implement handleEvent GlideinState state = glidein.getState(); GlideinEventCode code = (GlideinEventCode) event.getCode(); switch (code) { case SUBMIT: // Only NEW glideins can be submitted if (GlideinState.NEW.equals(state)) { if (siteReady()) { GlobusCredential event.getProperty("credential"); submitGlideinJob(credential); updateState(GlideinState.SUBMITTED,"Local job submitted",null); } else { updateState(GlideinState.WAITING,"Waiting for Site to be READY",null); } } break; case SITE_READY: // If we are waiting, then queue a SUBMIT event if (GlideinState.WAITING.equals(state)) { submitGlideinJob(); updateState(GlideinState.SUBMITTED,"Local job submitted",null); } break; case QUEUED: // A SUBMITTED job has been QUEUED remotely if (GlideinState.SUBMITTED.equals(state)) { updateState(GlideinState.QUEUED,"Glidein queued remotely",null); } break; case RUNNING: if (GlideinState.QUEUED.equals(state)) { updateState(GlideinState.RUNNING,"Glidein job running",null); } break; case REMOVE: cancelGlideinJob(); updateState(GlideinState.CANCELLED,"Local job cancelled",null); break; case EXITED: case DELETE: ResourceKey siteKey = AddressingUtil.getSiteKey(glidein.getSiteId()); // Delete the glidein after it has exited or if // a force delete was requested GlideinResourceHome home = GlideinResourceHome.getInstance(); home.remove(getKey()); // TODO: Figure out when Resource.remove gets called delete(); // Tell the Site About it Event siteEvent = new SiteEvent(SiteEventCode.GLIDEIN_FINISHED, siteKey); EventQueue queue = EventQueue.getInstance(); queue.add(siteEvent); break; case FAILED: // TODO: Fail job break; default: logger.warn("Unhandled event: "+event); break; } */ } }
Implement Glidein state changes git-svn-id: bdb5f82b9b83a1400e05d69d262344b821646179@1390 e217846f-e12e-0410-a4e5-89ccaea66ff7
src/edu/usc/glidein/service/impl/GlideinResource.java
Implement Glidein state changes
<ide><path>rc/edu/usc/glidein/service/impl/GlideinResource.java <ide> package edu.usc.glidein.service.impl; <ide> <add>import java.io.BufferedReader; <add>import java.io.CharArrayWriter; <ide> import java.io.File; <add>import java.io.FileReader; <ide> import java.io.IOException; <add>import java.io.PrintWriter; <ide> <ide> import javax.naming.NamingException; <ide> <ide> import org.globus.delegation.service.DelegationResource; <ide> import org.globus.gsi.GlobusCredential; <ide> import org.globus.wsrf.PersistenceCallback; <del>import org.globus.wsrf.RemoveCallback; <ide> import org.globus.wsrf.Resource; <ide> import org.globus.wsrf.ResourceException; <ide> import org.globus.wsrf.ResourceIdentifier; <ide> import edu.usc.glidein.service.state.GlideinEvent; <ide> import edu.usc.glidein.service.state.GlideinEventCode; <ide> import edu.usc.glidein.service.state.GlideinListener; <add>import edu.usc.glidein.service.state.SiteEvent; <add>import edu.usc.glidein.service.state.SiteEventCode; <ide> import edu.usc.glidein.stubs.types.EnvironmentVariable; <ide> import edu.usc.glidein.stubs.types.ExecutionService; <ide> import edu.usc.glidein.stubs.types.Glidein; <ide> import edu.usc.glidein.stubs.types.SiteState; <ide> import edu.usc.glidein.util.AddressingUtil; <ide> import edu.usc.glidein.util.Base64; <add>import edu.usc.glidein.util.CredentialUtil; <ide> import edu.usc.glidein.util.IOUtil; <ide> <del>public class GlideinResource implements Resource, ResourceIdentifier, PersistenceCallback, RemoveCallback, ResourceProperties <add>public class GlideinResource implements Resource, ResourceIdentifier, PersistenceCallback, ResourceProperties <ide> { <ide> private Logger logger = Logger.getLogger(GlideinResource.class); <ide> private SimpleResourcePropertySet resourceProperties; <ide> <ide> public void create(Glidein glidein) throws ResourceException <ide> { <del> logger.debug("Creating glidein for site "+glidein.getSiteId()); <add> info("Creating glidein for site "+glidein.getSiteId()); <ide> <ide> // Initialize glidein <ide> glidein.setState(GlideinState.NEW); <ide> <ide> public void load(ResourceKey key) throws ResourceException <ide> { <del> logger.debug("Loading "+key.getValue()); <add> info("Loading glidein "+key.getValue()); <ide> int id = ((Integer)key.getValue()).intValue(); <ide> try { <ide> Database db = Database.getDatabase(); <ide> <ide> public void store() throws ResourceException <ide> { <del> logger.debug("Storing "+getGlidein().getId()); <del> <del> throw new ResourceException("Tried to store GlideinResource"); <del> <del> /* <del> try { <del> Database db = Database.getDatabase(); <del> GlideinDAO dao = db.getGlideinDAO(); <del> dao.store(glidein); <del> } catch(DatabaseException de) { <del> throw new ResourceException(de); <del> } <del> */ <del> } <del> <del> public void remove() throws ResourceException <del> { <del> remove(false); <add> throw new UnsupportedOperationException(); <ide> } <ide> <ide> public void remove(boolean force) throws ResourceException <ide> { <del> logger.debug("Removing "+getGlidein().getId()); <add> info("Removing glidein"); <ide> <ide> // If we are forcing the issue, then just delete it <ide> GlideinEventCode code = null; <ide> <ide> public void submit(EndpointReferenceType credentialEPR) throws ResourceException <ide> { <del> logger.debug("Submitting "+glidein.getId()); <add> info("Submitting glidein"); <ide> try { <ide> <ide> // Get delegated credential <ide> private void updateState(GlideinState state, String shortMessage, String longMessage) <ide> throws ResourceException <ide> { <del> logger.debug("Changing state of glidein "+getGlidein().getId()+" to "+state+": "+shortMessage); <add> info("Changing state to "+state+": "+shortMessage); <ide> <ide> // Update object <ide> glidein.setState(state); <ide> <ide> private void submitGlideinJob(GlobusCredential credential) throws ResourceException <ide> { <del> logger.debug("Submitting glidein job "+glidein.getId()); <add> info("Submitting glidein job"); <ide> <ide> SiteResource siteResource = getSiteResource(); <ide> Site site = siteResource.getSite(); <ide> } <ide> <ide> // Create working directory <del> File jobDirectory = new File(config.getTempDir(),"glidein-"+glidein.getId()); <add> File jobDirectory = getWorkingDirectory(); <ide> <ide> // Create a job description <ide> CondorJob job = new CondorJob(jobDirectory); <ide> throw new ResourceException("Unable to submit glidein job: " + <ide> "Submit failed",ce); <ide> } <del> <del> logger.debug("Submitted glidein job '"+glidein.getId()+"'"); <ide> } <ide> <ide> private boolean siteReady() throws ResourceException <ide> <ide> private void cancelGlideinJob() throws ResourceException <ide> { <del> // TODO: Cancel glidein job <add> info("Cancelling glidein job"); <add> <add> // Find submit dir <add> File dir = getWorkingDirectory(); <add> File jobidFile = new File(dir,"jobid"); <add> <add> try { <add> // Read job id from jobid file <add> BufferedReader reader = new BufferedReader( <add> new FileReader(jobidFile)); <add> String jobid = reader.readLine(); <add> reader.close(); <add> <add> // condor_rm job <add> Condor.getInstance().cancelJob(jobid); <add> } catch (IOException ioe) { <add> throw new ResourceException( <add> "Unable to cancel glidein job: Unable to read job id",ioe); <add> } catch (CondorException ce) { <add> throw new ResourceException( <add> "Unable to cancel glidein job: condor_rm failed",ce); <add> } <ide> } <ide> <ide> private void delete() throws ResourceException <ide> Database db = Database.getDatabase(); <ide> GlideinDAO dao = db.getGlideinDAO(); <ide> dao.delete(glidein.getId()); <del> glidein = null; <del> resourceProperties = null; <ide> } catch(DatabaseException de) { <ide> throw new ResourceException(de); <ide> } <ide> } <ide> <add> private ServiceConfiguration getConfig() throws ResourceException <add> { <add> try { <add> return ServiceConfiguration.getInstance(); <add> } catch (NamingException ne) { <add> throw new ResourceException("Unable to get service configuration",ne); <add> } <add> } <add> <add> private File getWorkingDirectory() throws ResourceException <add> { <add> File dir = new File(getConfig().getTempDir(),"glidein-"+glidein.getId()); <add> <add> // Create the directory if it doesn't exist <add> if (dir.exists()) { <add> if (!dir.isDirectory()) { <add> throw new ResourceException( <add> "Working directory is not a directory"); <add> } <add> } else { <add> try { <add> if (!dir.mkdirs()) { <add> throw new ResourceException( <add> "Unable to create working directory"); <add> } <add> } catch (SecurityException e) { <add> throw new ResourceException( <add> "Unable to create working directory"); <add> } <add> } <add> <add> return dir; <add> } <add> <add> private void storeCredential(GlobusCredential credential) throws ResourceException <add> { <add> try { <add> File work = getWorkingDirectory(); <add> File credFile = new File(work,"credential"); <add> CredentialUtil.store(credential,credFile); <add> } catch (IOException ioe) { <add> throw new ResourceException("Unable to store credential"); <add> } <add> } <add> <add> private GlobusCredential loadCredential() throws ResourceException <add> { <add> try { <add> File work = getWorkingDirectory(); <add> File credFile = new File(work,"credential"); <add> GlobusCredential credential = CredentialUtil.load(credFile); <add> return credential; <add> } catch (IOException ioe) { <add> throw new ResourceException("Unable to load credential"); <add> } <add> } <add> <add> private void fail(String message, Exception exception) <add> { <add> // Update status to FAILED <add> error("Failure: "+message,exception); <add> CharArrayWriter caw = new CharArrayWriter(); <add> exception.printStackTrace(new PrintWriter(caw)); <add> try { <add> updateState(GlideinState.FAILED, message, caw.toString()); <add> } catch (ResourceException re) { <add> error("Unable to change state to "+GlideinState.FAILED,re); <add> } <add> } <add> <ide> public synchronized void handleEvent(GlideinEvent event) <ide> { <del> /* TODO: Implement handleEvent <ide> GlideinState state = glidein.getState(); <ide> GlideinEventCode code = (GlideinEventCode) event.getCode(); <ide> <add> // If the glidein was deleted, then don't process any more events <add> if (GlideinState.DELETED.equals(state)) { <add> warn("Unable to process event "+code+": "+ <add> "Glidein has been deleted"); <add> return; <add> } <add> <ide> switch (code) { <ide> <del> case SUBMIT: <add> case SUBMIT: { <ide> // Only NEW glideins can be submitted <del> if (GlideinState.NEW.equals(state)) { <del> if (siteReady()) { <del> GlobusCredential event.getProperty("credential"); <add> if (GlideinState.NEW.equals(state)) { <add> GlobusCredential credential = (GlobusCredential)event.getProperty("credential"); <add> <add> // Check to see if site is ready <add> boolean ready = false; <add> try { <add> ready = siteReady(); <add> } catch (ResourceException re) { <add> fail("Unable to check for site ready state",re); <add> } <add> <add> // If the site is ready, submit the glidein job, otherwise wait <add> if (ready) { <add> try { <add> submitGlideinJob(credential); <add> updateState(GlideinState.SUBMITTED,"Local job submitted",null); <add> } catch (ResourceException re) { <add> fail("Unable to submit job",re); <add> } <add> } else { <add> try { <add> storeCredential(credential); <add> updateState(GlideinState.WAITING,"Waiting for site to be "+SiteState.READY,null); <add> } catch (ResourceException re) { <add> fail("Unable to wait for site ready state",re); <add> } <add> } <add> } <add> } break; <add> <add> case SITE_READY: { <add> // If we are waiting, then queue a SUBMIT event <add> if (GlideinState.WAITING.equals(state)) { <add> try { <add> GlobusCredential credential = loadCredential(); <ide> submitGlideinJob(credential); <ide> updateState(GlideinState.SUBMITTED,"Local job submitted",null); <del> } else { <del> updateState(GlideinState.WAITING,"Waiting for Site to be READY",null); <add> } catch (ResourceException re) { <add> fail("Unable to submit job",re); <ide> } <ide> } <del> break; <del> <del> case SITE_READY: <del> // If we are waiting, then queue a SUBMIT event <del> if (GlideinState.WAITING.equals(state)) { <del> submitGlideinJob(); <del> updateState(GlideinState.SUBMITTED,"Local job submitted",null); <del> } <del> break; <del> <del> case QUEUED: <del> // A SUBMITTED job has been QUEUED remotely <add> } break; <add> <add> case QUEUED: { <ide> if (GlideinState.SUBMITTED.equals(state)) { <del> updateState(GlideinState.QUEUED,"Glidein queued remotely",null); <del> } <del> break; <del> <del> case RUNNING: <del> if (GlideinState.QUEUED.equals(state)) { <add> try { <add> updateState(GlideinState.QUEUED,"Glidein job queued",null); <add> } catch (ResourceException re) { <add> fail("Unable to set state to "+GlideinState.QUEUED,re); <add> } <add> } <add> } break; <add> <add> case RUNNING: { <add> try { <ide> updateState(GlideinState.RUNNING,"Glidein job running",null); <del> } <del> break; <add> } catch (ResourceException re) { <add> fail("Unable to set state to "+GlideinState.RUNNING,re); <add> } <add> } break; <add> <add> case REMOVE: <add> case JOB_SUCCESS: <add> case DELETE: { <add> // If the user requested remove <add> if (GlideinEventCode.REMOVE.equals(code)) { <add> <add> // If a glidein job has been submitted cancel the job <add> if (GlideinState.SUBMITTED.equals(state) || <add> GlideinState.RUNNING.equals(state) || <add> GlideinState.QUEUED.equals(state)) { <add> try { <add> cancelGlideinJob(); <add> } catch (ResourceException re) { <add> fail("Unable to cancel glidein job",re); <add> } <add> } <add> } <ide> <del> case REMOVE: <del> cancelGlideinJob(); <del> updateState(GlideinState.CANCELLED,"Local job cancelled",null); <del> break; <del> <del> case EXITED: <del> case DELETE: <del> ResourceKey siteKey = AddressingUtil.getSiteKey(glidein.getSiteId()); <add> // Change the status to deleted <add> glidein.setState(GlideinState.DELETED); <ide> <del> // Delete the glidein after it has exited or if <del> // a force delete was requested <del> GlideinResourceHome home = GlideinResourceHome.getInstance(); <del> home.remove(getKey()); <del> // TODO: Figure out when Resource.remove gets called <del> delete(); <add> // Remove the glidein from the ResourceHome <add> try { <add> GlideinResourceHome home = GlideinResourceHome.getInstance(); <add> home.remove(getKey()); <add> } catch (NamingException e) { <add> fail("Unable to locate GlideinResourceHome",e); <add> return; <add> } catch (ResourceException re) { <add> fail("Unable to remove glidein from GlideinResourceHome",re); <add> return; <add> } <add> <add> // Delete the glidein from the database <add> try { <add> delete(); <add> } catch (ResourceException re) { <add> fail("Unable to delete glidein from database",re); <add> return; <add> } <ide> <ide> // Tell the Site About it <del> Event siteEvent = new SiteEvent(SiteEventCode.GLIDEIN_FINISHED, siteKey); <del> EventQueue queue = EventQueue.getInstance(); <del> queue.add(siteEvent); <del> break; <del> <del> case FAILED: <del> // TODO: Fail job <del> break; <del> <del> default: <del> logger.warn("Unhandled event: "+event); <del> break; <del> } <del> */ <add> try { <add> ResourceKey siteKey = AddressingUtil.getSiteKey(glidein.getSiteId()); <add> Event siteEvent = new SiteEvent(SiteEventCode.GLIDEIN_DELETED, siteKey); <add> EventQueue queue = EventQueue.getInstance(); <add> queue.add(siteEvent); <add> } catch (NamingException ne) { <add> warn("Unable to notify site of deleted glidein",ne); <add> } <add> <add> // Remove the working directory <add> try { <add> IOUtil.rmdirs(getWorkingDirectory()); <add> } catch (ResourceException re) { <add> warn("Unable to remove working dir",re); <add> } <add> } break; <add> <add> case JOB_FAILURE: { <add> fail((String)event.getProperty("message"), <add> (Exception)event.getProperty("exception")); <add> } break; <add> <add> default: { <add> IllegalStateException ise = new IllegalStateException(); <add> ise.fillInStackTrace(); <add> error("Unhandled event: "+event,ise); <add> } break; <add> } <add> } <add> <add> private String logPrefix() <add> { <add> if (glidein == null) { <add> return ""; <add> } else { <add> return "Glidein "+glidein.getId()+": "; <add> } <add> } <add> public void debug(String message) <add> { <add> debug(message,null); <add> } <add> public void debug(String message, Throwable t) <add> { <add> logger.debug(logPrefix()+message, t); <add> } <add> public void info(String message) <add> { <add> info(message,null); <add> } <add> public void info(String message, Throwable t) <add> { <add> logger.info(logPrefix()+message,t); <add> } <add> public void warn(String message) <add> { <add> warn(message,null); <add> } <add> public void warn(String message, Throwable t) <add> { <add> logger.warn(logPrefix()+message,t); <add> } <add> public void error(String message) <add> { <add> error(message,null); <add> } <add> public void error(String message, Throwable t) <add> { <add> logger.error(logPrefix()+message,t); <ide> } <ide> }
Java
mit
034227b82b51010cd6bb8d0573dbcdbe91a95cfc
0
JabRef/jabref,sauliusg/jabref,JabRef/jabref,Siedlerchr/jabref,Siedlerchr/jabref,zellerdev/jabref,JabRef/jabref,Siedlerchr/jabref,zellerdev/jabref,zellerdev/jabref,zellerdev/jabref,sauliusg/jabref,Siedlerchr/jabref,sauliusg/jabref,zellerdev/jabref,JabRef/jabref,sauliusg/jabref
package org.jabref.logic.texparser; import java.io.IOException; import java.io.LineNumberReader; import java.io.UncheckedIOException; import java.nio.channels.ClosedChannelException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.model.texparser.TexParser; import org.jabref.model.texparser.TexParserResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DefaultTexParser implements TexParser { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultTexParser.class); private static final String TEX_EXT = ".tex"; /** * It is allowed to add new cite commands for pattern matching. * Some valid examples: "citep", "[cC]ite", and "[cC]ite(author|title|year|t|p)?". */ private static final String[] CITE_COMMANDS = { "[cC]ite(alt|alp|author|authorfull|date|num|p|t|text|title|url|year|yearpar)?", "([aA]|fnote|foot|footfull|full|no|[nN]ote|[pP]aren|[pP]note|[tT]ext|[sS]mart|super)cite", "footcitetext" }; private static final String CITE_GROUP = "key"; private static final Pattern CITE_PATTERN = Pattern.compile( String.format("\\\\(%s)\\*?(?:\\[(?:[^\\]]*)\\]){0,2}\\{(?<%s>[^\\}]*)\\}", String.join("|", CITE_COMMANDS), CITE_GROUP)); private static final String INCLUDE_GROUP = "file"; private static final Pattern INCLUDE_PATTERN = Pattern.compile( String.format("\\\\(?:include|input)\\{(?<%s>[^\\}]*)\\}", INCLUDE_GROUP)); private final TexParserResult texParserResult; public DefaultTexParser() { this.texParserResult = new TexParserResult(); } public TexParserResult getTexParserResult() { return texParserResult; } @Override public TexParserResult parse(String citeString) { matchCitation(Paths.get(""), 1, citeString); return texParserResult; } @Override public TexParserResult parse(Path texFile) { return parse(Collections.singletonList(texFile)); } @Override public TexParserResult parse(List<Path> texFiles) { texParserResult.addFiles(texFiles); List<Path> referencedFiles = new ArrayList<>(); for (Path file : texFiles) { if (!file.toFile().exists()) { LOGGER.error(String.format("File does not exist: %s", file)); continue; } try (LineNumberReader lineNumberReader = new LineNumberReader(Files.newBufferedReader(file))) { for (String line = lineNumberReader.readLine(); line != null; line = lineNumberReader.readLine()) { // Skip comments and blank lines. if (line.trim().isEmpty() || line.trim().charAt(0) == '%') { continue; } matchCitation(file, lineNumberReader.getLineNumber(), line); matchNestedFile(file, texFiles, referencedFiles, line); } } catch (ClosedChannelException e) { LOGGER.error("Parsing has been interrupted"); return null; } catch (IOException | UncheckedIOException e) { LOGGER.error(String.format("%s while parsing files: %s", e.getClass().getName(), e.getMessage())); } } // Parse all files referenced by TEX files, recursively. if (!referencedFiles.isEmpty()) { parse(referencedFiles); } return texParserResult; } /** * Find cites along a specific line and store them. */ private void matchCitation(Path file, int lineNumber, String line) { Matcher citeMatch = CITE_PATTERN.matcher(line); while (citeMatch.find()) { Arrays.stream(citeMatch.group(CITE_GROUP).split(",")) .forEach(key -> texParserResult.addKey(key, file, lineNumber, citeMatch.start(), citeMatch.end(), line)); } } /** * Find inputs and includes along a specific line and store them for parsing later. */ private void matchNestedFile(Path file, List<Path> texFiles, List<Path> referencedFiles, String line) { Matcher includeMatch = INCLUDE_PATTERN.matcher(line); while (includeMatch.find()) { String include = includeMatch.group(INCLUDE_GROUP); Path nestedFile = file.getParent().resolve( include.endsWith(TEX_EXT) ? include : String.format("%s%s", include, TEX_EXT)); if (!nestedFile.toFile().exists()) { LOGGER.error(String.format("Nested file does not exist: %s", nestedFile)); continue; } if (!texFiles.contains(nestedFile)) { referencedFiles.add(nestedFile); } } } }
src/main/java/org/jabref/logic/texparser/DefaultTexParser.java
package org.jabref.logic.texparser; import java.io.IOException; import java.io.LineNumberReader; import java.io.UncheckedIOException; import java.nio.channels.ClosedChannelException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.model.texparser.TexParser; import org.jabref.model.texparser.TexParserResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DefaultTexParser implements TexParser { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultTexParser.class); private static final String TEX_EXT = ".tex"; /** * It is allowed to add new cite commands for pattern matching. * Some valid examples: "citep", "[cC]ite", and "[cC]ite(author|title|year|t|p)?". */ private static final String[] CITE_COMMANDS = { "[cC]ite(alt|alp|author|authorfull|date|num|p|t|text|title|url|year|yearpar)?", "([aA]|fnote|foot|footfull|full|no|[nN]ote|[pP]aren|[pP]note|[tT]ext|[sS]mart|super)cite", "footcitetext" }; private static final String CITE_GROUP = "key"; private static final Pattern CITE_PATTERN = Pattern.compile( String.format("\\\\(%s)\\*?(?:\\[(?:[^\\]]*)\\]){0,2}\\{(?<%s>[^\\}]*)\\}", String.join("|", CITE_COMMANDS), CITE_GROUP)); private static final String INCLUDE_GROUP = "file"; private static final Pattern INCLUDE_PATTERN = Pattern.compile( String.format("\\\\(?:include|input)\\{(?<%s>[^\\}]*)\\}", INCLUDE_GROUP)); private final TexParserResult texParserResult; public DefaultTexParser() { this.texParserResult = new TexParserResult(); } public TexParserResult getTexParserResult() { return texParserResult; } @Override public TexParserResult parse(String citeString) { matchCitation(Paths.get(""), 1, citeString); return texParserResult; } @Override public TexParserResult parse(Path texFile) { return parse(Collections.singletonList(texFile)); } @Override public TexParserResult parse(List<Path> texFiles) { texParserResult.addFiles(texFiles); List<Path> referencedFiles = new ArrayList<>(); for (Path file : texFiles) { if (!file.toFile().exists()) { LOGGER.error(String.format("File does not exist: %s", file)); continue; } try (LineNumberReader lineNumberReader = new LineNumberReader(Files.newBufferedReader(file))) { for (String line = lineNumberReader.readLine(); line != null; line = lineNumberReader.readLine()) { // Skip comments and blank lines. if (line.isEmpty() || line.charAt(0) == '%') { continue; } matchCitation(file, lineNumberReader.getLineNumber(), line); matchNestedFile(file, texFiles, referencedFiles, line); } } catch (ClosedChannelException e) { LOGGER.error("Parsing has been interrupted"); return null; } catch (IOException | UncheckedIOException e) { LOGGER.error(String.format("%s while parsing files: %s", e.getClass().getName(), e.getMessage())); } } // Parse all files referenced by TEX files, recursively. if (!referencedFiles.isEmpty()) { parse(referencedFiles); } return texParserResult; } /** * Find cites along a specific line and store them. */ private void matchCitation(Path file, int lineNumber, String line) { Matcher citeMatch = CITE_PATTERN.matcher(line); while (citeMatch.find()) { Arrays.stream(citeMatch.group(CITE_GROUP).split(",")) .forEach(key -> texParserResult.addKey(key, file, lineNumber, citeMatch.start(), citeMatch.end(), line)); } } /** * Find inputs and includes along a specific line and store them for parsing later. */ private void matchNestedFile(Path file, List<Path> texFiles, List<Path> referencedFiles, String line) { Matcher includeMatch = INCLUDE_PATTERN.matcher(line); while (includeMatch.find()) { String include = includeMatch.group(INCLUDE_GROUP); Path inputFile = file.getParent().resolve( include.endsWith(TEX_EXT) ? include : String.format("%s%s", include, TEX_EXT)); if (!texFiles.contains(inputFile)) { referencedFiles.add(inputFile); } } } }
Add a check for nested files and improve the code to skip lines (DefaultTexParser)
src/main/java/org/jabref/logic/texparser/DefaultTexParser.java
Add a check for nested files and improve the code to skip lines (DefaultTexParser)
<ide><path>rc/main/java/org/jabref/logic/texparser/DefaultTexParser.java <ide> try (LineNumberReader lineNumberReader = new LineNumberReader(Files.newBufferedReader(file))) { <ide> for (String line = lineNumberReader.readLine(); line != null; line = lineNumberReader.readLine()) { <ide> // Skip comments and blank lines. <del> if (line.isEmpty() || line.charAt(0) == '%') { <add> if (line.trim().isEmpty() || line.trim().charAt(0) == '%') { <ide> continue; <ide> } <ide> matchCitation(file, lineNumberReader.getLineNumber(), line); <ide> while (includeMatch.find()) { <ide> String include = includeMatch.group(INCLUDE_GROUP); <ide> <del> Path inputFile = file.getParent().resolve( <add> Path nestedFile = file.getParent().resolve( <ide> include.endsWith(TEX_EXT) <ide> ? include <ide> : String.format("%s%s", include, TEX_EXT)); <ide> <del> if (!texFiles.contains(inputFile)) { <del> referencedFiles.add(inputFile); <add> if (!nestedFile.toFile().exists()) { <add> LOGGER.error(String.format("Nested file does not exist: %s", nestedFile)); <add> continue; <add> } <add> <add> if (!texFiles.contains(nestedFile)) { <add> referencedFiles.add(nestedFile); <ide> } <ide> } <ide> }
Java
apache-2.0
0ca4fe2a30421d95288508c3e4dc1d3b74967bf3
0
kermitt2/grobid,kermitt2/grobid,kermitt2/grobid,kermitt2/grobid,kermitt2/grobid,kermitt2/grobid
package org.grobid.core.utilities; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.grobid.core.GrobidModel; import org.grobid.core.engines.tagging.GrobidCRFEngine; import org.grobid.core.exceptions.GrobidPropertyException; import org.grobid.core.exceptions.GrobidResourceException; import org.grobid.core.utilities.GrobidConfig.ModelParameters; import org.grobid.core.utilities.GrobidConfig.DelftModelParameters; import org.grobid.core.utilities.GrobidConfig.DelftModelParameterSet; import org.grobid.core.utilities.GrobidConfig.WapitiModelParameters; import org.grobid.core.main.GrobidHomeFinder; import org.grobid.core.utilities.Consolidation.GrobidConsolidationService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.fasterxml.jackson.databind.DeserializationFeature; /** * This class provide methods to set/load/access grobid config value from a yaml config file loaded * in the class {@link GrobidConfig}. * * New yaml parameters and former properties should be equivalent via this class. We keep the * class name "GrobidProperties" for compatibility with Grobid modules and other Java applications * using Grobid as a library. * * to be done: having parameters that can be overridden by a system property having a compatible name. */ public class GrobidProperties { public static final Logger LOGGER = LoggerFactory.getLogger(GrobidProperties.class); static final String FOLDER_NAME_MODELS = "models"; static final String FILE_NAME_MODEL = "model"; private static final String GROBID_VERSION_FILE = "/grobid-version.txt"; static final String UNKNOWN_VERSION_STR = "unknown"; private static GrobidProperties grobidProperties = null; // indicate if GROBID is running in server mode or not private static boolean contextExecutionServer = false; /** * {@link GrobidConfig} object containing all config parameters used by grobid. */ private static GrobidConfig grobidConfig = null; /** * Map models specified inthe config file to their parameters */ private static Map<String, ModelParameters> modelMap = null; /** * Path to pdf to xml converter. */ private static File pathToPdfalto = null; private static File grobidHome = null; /** * Path to the yaml config file */ static File GROBID_CONFIG_PATH = null; private static String GROBID_VERSION = null; /** * Returns an instance of {@link GrobidProperties} object. If no one is set, then * it creates one */ public static GrobidProperties getInstance() { if (grobidProperties == null) { return getNewInstance(); } else { return grobidProperties; } } /** * Returns an instance of {@link GrobidProperties} object based on a custom grobid-home directory. * If no one is set, then it creates one. */ public static GrobidProperties getInstance(GrobidHomeFinder grobidHomeFinder) { synchronized (GrobidProperties.class) { if (grobidHome == null) { grobidHome = grobidHomeFinder.findGrobidHomeOrFail(); } } return getInstance(); } /** * Reload grobid config */ public static void reload() { getNewInstance(); } public static void reset() { getNewInstance(); } /** * Creates a new {@link GrobidProperties} object, initializes and returns it. * * @return GrobidProperties */ protected static synchronized GrobidProperties getNewInstance() { LOGGER.debug("synchronized getNewInstance"); grobidProperties = new GrobidProperties(); return grobidProperties; } /** * Load the path to GROBID_HOME from the env-entry set in web.xml. */ private static void assignGrobidHomePath() { if (grobidHome == null) { synchronized (GrobidProperties.class) { if (grobidHome == null) { grobidHome = new GrobidHomeFinder().findGrobidHomeOrFail(); } } } } /** * Return the grobid-home path. * * @return grobid home path */ public static File getGrobidHome() { return grobidHome; } public static File getGrobidHomePath() { return grobidHome; } /** * For back compatibility */ @Deprecated public static File get_GROBID_HOME_PATH() { return grobidHome; } /** * Set the grobid-home path. */ public static void setGrobidHome(final String pGROBID_HOME_PATH) { if (StringUtils.isBlank(pGROBID_HOME_PATH)) throw new GrobidPropertyException("Cannot set property grobidHome to null or empty."); grobidHome = new File(pGROBID_HOME_PATH); // exception if prop file does not exist if (!grobidHome.exists()) { throw new GrobidPropertyException("Could not read GROBID_HOME, the directory '" + pGROBID_HOME_PATH + "' does not exist."); } try { grobidHome = grobidHome.getCanonicalFile(); } catch (IOException e) { throw new GrobidPropertyException("Cannot set grobid home path to the given one '" + pGROBID_HOME_PATH + "', because it does not exist."); } } /** * Load the path to grobid config yaml from the env-entry set in web.xml. */ static void loadGrobidConfigPath() { LOGGER.debug("loading grobid config yaml"); if (GROBID_CONFIG_PATH == null) { synchronized (GrobidProperties.class) { if (GROBID_CONFIG_PATH == null) { GROBID_CONFIG_PATH = new GrobidHomeFinder().findGrobidConfigOrFail(grobidHome); } } } } /** * Return the path to the GROBID yaml config file * * @return grobid properties path */ public static File getGrobidConfigPath() { return GROBID_CONFIG_PATH; } /** * Set the GROBID config yaml file path. */ public static void setGrobidConfigPath(final String pGrobidConfigPath) { if (StringUtils.isBlank(pGrobidConfigPath)) throw new GrobidPropertyException("Cannot set GROBID config file to null or empty."); File grobidConfigPath = new File(pGrobidConfigPath); // exception if config file does not exist if (!grobidConfigPath.exists()) { throw new GrobidPropertyException("Cannot read GROBID yaml config file, the file '" + pGrobidConfigPath + "' does not exist."); } try { GROBID_CONFIG_PATH = grobidConfigPath.getCanonicalFile(); } catch (IOException e) { throw new GrobidPropertyException("Cannot set grobid yaml config file path to the given one '" + pGrobidConfigPath + "', because it does not exist."); } } /** * Create a new object and search where to find the grobid-home folder. * * We check if the system property GrobidPropertyKeys.PROP_GROBID_HOME * is set. If not set, the method will search for a folder named * grobid-home in the current project. * * Finally from the found grobid-home, the yaml config file is loaded and * the native and data resource paths are initialized. */ public GrobidProperties() { assignGrobidHomePath(); loadGrobidConfigPath(); setContextExecutionServer(false); try { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); grobidConfig = mapper.readValue(GROBID_CONFIG_PATH, GrobidConfig.class); } catch (IOException exp) { throw new GrobidPropertyException("Cannot open GROBID config yaml file at location '" + GROBID_CONFIG_PATH.getAbsolutePath() + "'", exp); } catch (Exception exp) { throw new GrobidPropertyException("Cannot open GROBID config yaml file " + getGrobidConfigPath().getAbsolutePath(), exp); } //getProps().putAll(getEnvironmentVariableOverrides(System.getenv())); initializeTmpPath(); // TBD: tmp to be created loadPdfaltoPath(); createModelMap(); } /** * Create a map between model names and associated parameters */ private static void createModelMap() { for(ModelParameters modelParameter : grobidConfig.grobid.models) { if (modelMap == null) modelMap = new TreeMap<>(); modelMap.put(modelParameter.name, modelParameter); } } /** * Add a model with its parameter object in the model map */ public static void addModel(ModelParameters modelParameter) { if (modelMap == null) modelMap = new TreeMap<>(); modelMap.put(modelParameter.name, modelParameter); } /** * Create indicated tmp path if it does not exist */ private void initializeTmpPath() { File tmpDir = getTempPath(); if (!tmpDir.exists()) { if (!tmpDir.mkdirs()) { LOGGER.warn("tmp does not exist and unable to create tmp directory: " + tmpDir.getAbsolutePath()); } } } /** * Return the distinct values of all the engines that are specified in the the config file */ public static Set<GrobidCRFEngine> getDistinctModels() { Set<GrobidCRFEngine> distinctModels = new HashSet<>(); for(ModelParameters modelParameter : grobidConfig.grobid.models) { if (modelParameter.engine == null) { // it should not happen normally continue; } GrobidCRFEngine localEngine = GrobidCRFEngine.get(modelParameter.engine); if (!distinctModels.contains(localEngine)) distinctModels.add(localEngine); } return distinctModels; } /** * Returns the current version of GROBID * * @return GROBID version */ public static String getVersion() { if (GROBID_VERSION == null) { synchronized (GrobidProperties.class) { if (GROBID_VERSION == null) { String grobidVersion = UNKNOWN_VERSION_STR; try (InputStream is = GrobidProperties.class.getResourceAsStream(GROBID_VERSION_FILE)) { grobidVersion = IOUtils.toString(is, "UTF-8"); } catch (IOException e) { LOGGER.error("Cannot read Grobid version from resources", e); } GROBID_VERSION = grobidVersion; } } } return GROBID_VERSION; } /** * Returns the temprorary path of grobid * * @return a directory for temp files */ public static File getTempPath() { if (grobidConfig.grobid.temp == null) return new File(System.getProperty("java.io.tmpdir")); else return new File(grobidHome.getPath(), grobidConfig.grobid.temp); } public static void setNativeLibraryPath(final String nativeLibPath) { grobidConfig.grobid.nativelibrary = nativeLibPath; } /** * Returns the path to the native libraries as {@link File} object. * * @return folder that contains native libraries */ public static File getNativeLibraryPath() { return new File(grobidHome.getPath(), grobidConfig.grobid.nativelibrary); } /** * Returns the installation path of DeLFT if set, null otherwise. It is required for using * a Deep Learning sequence labelling engine. * * @return path to the folder that contains the local install of DeLFT */ public static String getDeLFTPath() { return grobidConfig.grobid.delft.install; } public static String getDeLFTFilePath() { String rawPath = grobidConfig.grobid.delft.install; File pathFile = new File(rawPath); if (!Files.exists(Paths.get(rawPath).toAbsolutePath())) { rawPath = "../" + rawPath; pathFile = new File(rawPath); } return pathFile.getAbsolutePath(); } public static String getGluttonUrl() { if (grobidConfig.grobid.consolidation.glutton.url == null || grobidConfig.grobid.consolidation.glutton.url.trim().length() == 0) return null; else return grobidConfig.grobid.consolidation.glutton.url; } public static void setGluttonUrl(final String theUrl) { grobidConfig.grobid.consolidation.glutton.url = theUrl; } /** * Returns the host for a proxy connection, given in the grobid config file. * * @return proxy host */ public static String getProxyHost() { if (grobidConfig.grobid.proxy.host == null || grobidConfig.grobid.proxy.host.trim().length() == 0) return null; else return grobidConfig.grobid.proxy.host; } /** * Sets the host a proxy connection, given in the config file. * * @param the proxy host to be used */ public static void setProxyHost(final String host) { grobidConfig.grobid.proxy.host = host; System.setProperty("http.proxyHost", host); System.setProperty("https.proxyHost", host); } /** * Returns the port for a proxy connection, given in the grobid config file. * * @return proxy port */ public static Integer getProxyPort() { return grobidConfig.grobid.proxy.port; } /** * Set the "mailto" parameter to be used in the crossref query and in User-Agent * header, as recommended by CrossRef REST API documentation. * * @param mailto email parameter to be used for requesting crossref */ public static void setCrossrefMailto(final String mailto) { grobidConfig.grobid.consolidation.crossref.mailto = mailto; } /** * Get the "mailto" parameter to be used in the crossref query and in User-Agent * header, as recommended by CrossRef REST API documentation. * * @return string of the email parameter to be used for requesting crossref */ public static String getCrossrefMailto() { if (grobidConfig.grobid.consolidation.crossref.mailto == null || grobidConfig.grobid.consolidation.crossref.mailto.trim().length() == 0) return null; else return grobidConfig.grobid.consolidation.crossref.mailto; } /** * Set the Crossref Metadata Plus authorization token to be used for Crossref * requests for the subscribers of this service. This token will ensure that said * requests get directed to a pool of machines that are reserved for "Plus" SLA users. * * @param token authorization token to be used for requesting crossref */ public static void setCrossrefToken(final String token) { grobidConfig.grobid.consolidation.crossref.token = token; } /** * Get the Crossref Metadata Plus authorization token to be used for Crossref * requests for the subscribers of this service. This token will ensure that said * requests get directed to a pool of machines that are reserved for "Plus" SLA users. * * @return authorization token to be used for requesting crossref */ public static String getCrossrefToken() { if (grobidConfig.grobid.consolidation.crossref.token == null || grobidConfig.grobid.consolidation.crossref.token.trim().length() == 0) return null; else return grobidConfig.grobid.consolidation.crossref.token; } /** * Sets the port for a proxy connection, given in the grobid config file. * * @param proxy port */ public static void setProxyPort(int port) { grobidConfig.grobid.proxy.port = port; System.setProperty("http.proxyPort", ""+port); System.setProperty("https.proxyPort", ""+port); } public static Integer getPdfaltoMemoryLimitMb() { return grobidConfig.grobid.pdf.pdfalto.memory_limit_mb; } public static Integer getPdfaltoTimeoutMs() { return grobidConfig.grobid.pdf.pdfalto.timeout_sec * 1000; } /** * Returns the number of threads to be used when training, given in the grobid config file. * * @return number of threads */ public static Integer getNBThreads() { Integer nbThreadsConfig = Integer.valueOf(grobidConfig.grobid.nb_threads); if (nbThreadsConfig.intValue() == 0) { return Integer.valueOf(Runtime.getRuntime().availableProcessors()); } return nbThreadsConfig; } // PDF with more blocks will be skipped public static Integer getPdfBlocksMax() { return grobidConfig.grobid.pdf.blocks_max; } // PDF with more tokens will be skipped public static Integer getPdfTokensMax() { return grobidConfig.grobid.pdf.tokens_max; } /** * Sets the number of threads, given in the grobid-property file. * * @param nbThreads umber of threads */ public static void setNBThreads(int nbThreads) { grobidConfig.grobid.nb_threads = nbThreads; } public static String getLanguageDetectorFactory() { String factoryClassName = grobidConfig.grobid.language_detector_factory; if (StringUtils.isBlank(factoryClassName)) { throw new GrobidPropertyException("Language detection is enabled but a factory class name is not provided"); } return factoryClassName; } /** * Sets if a language id shall be used, given in the grobid-property file. * * @param useLanguageId true, if a language id shall be used */ /*public static void setUseLanguageId(final String useLanguageId) { setPropertyValue(GrobidPropertyKeys.PROP_USE_LANG_ID, useLanguageId); }*/ public static String getSentenceDetectorFactory() { String factoryClassName = grobidConfig.grobid.sentence_detector_factory; if (StringUtils.isBlank(factoryClassName)) { throw new GrobidPropertyException("Sentence detection is enabled but a factory class name is not provided"); } return factoryClassName; } /** * Returns the path to the home folder of pdf to xml converter. */ public static void loadPdfaltoPath() { LOGGER.debug("loading pdfalto command path"); String pathName = grobidConfig.grobid.pdf.pdfalto.path; pathToPdfalto = new File(grobidHome.getPath(), pathName); if (!pathToPdfalto.exists()) { throw new GrobidPropertyException( "Path to pdfalto doesn't exists. " + "Please set the path to pdfalto in the config file"); } pathToPdfalto = new File(pathToPdfalto, Utilities.getOsNameAndArch()); LOGGER.debug("pdfalto executable home directory set to " + pathToPdfalto.getAbsolutePath()); } /** * Returns the path to the home folder of pdfalto program. * * @return path to pdfalto program */ public static File getPdfaltoPath() { return pathToPdfalto; } private static String getGrobidCRFEngineName(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.error("No configuration parameter defined for model " + modelName); return null; } return param.engine; } public static GrobidCRFEngine getGrobidCRFEngine(final String modelName) { String engineName = getGrobidCRFEngineName(modelName); if (engineName == null) return null; else return GrobidCRFEngine.get(engineName); } public static GrobidCRFEngine getGrobidCRFEngine(final GrobidModel model) { return getGrobidCRFEngine(model.getModelName()); } public static File getModelPath(final GrobidModel model) { if (modelMap.get(model.getModelName()) == null) { // model is not specified in the config, ignoring return null; } String extension = getGrobidCRFEngine(model).getExt(); return new File(getGrobidHome(), FOLDER_NAME_MODELS + File.separator + model.getFolderName() + File.separator + FILE_NAME_MODEL + "." + extension); } public static File getModelPath() { return new File(getGrobidHome(), FOLDER_NAME_MODELS); } public static File getTemplatePath(final File resourcesDir, final GrobidModel model) { if (modelMap.get(model.getModelName()) == null) { // model is not specified in the config, ignoring return null; } File theFile = new File(resourcesDir, "dataset/" + model.getFolderName() + "/crfpp-templates/" + model.getTemplateName()); if (!theFile.exists()) { theFile = new File("resources/dataset/" + model.getFolderName() + "/crfpp-templates/" + model.getTemplateName()); } return theFile; } public static File getEvalCorpusPath(final File resourcesDir, final GrobidModel model) { File theFile = new File(resourcesDir, "dataset/" + model.getFolderName() + "/evaluation/"); if (!theFile.exists()) { theFile = new File("resources/dataset/" + model.getFolderName() + "/evaluation/"); } return theFile; } public static File getCorpusPath(final File resourcesDir, final GrobidModel model) { File theFile = new File(resourcesDir, "dataset/" + model.getFolderName() + "/corpus"); if (!theFile.exists()) { theFile = new File("resources/dataset/" + model.getFolderName() + "/corpus"); } return theFile; } public static String getLexiconPath() { return new File(getGrobidHome(), "lexicon").getAbsolutePath(); } public static File getLanguageDetectionResourcePath() { return new File(getGrobidHome(), "language-detection"); } /** * Returns the maximum parallel connections allowed in the pool. * * @return the number of connections */ public static int getMaxPoolConnections() { return grobidConfig.grobid.max_connections; } /** * Returns maximum time to wait before timeout when the pool is full. * * @return time to wait in milliseconds. */ public static int getPoolMaxWait() { return grobidConfig.grobid.pool_max_wait * 1000; } /** * Returns the consolidation service to be used. * * @return the consolidation service to be used */ public static GrobidConsolidationService getConsolidationService() { if (grobidConfig.grobid.consolidation.service == null) grobidConfig.grobid.consolidation.service = "crossref"; return GrobidConsolidationService.get(grobidConfig.grobid.consolidation.service); } /** * Set which consolidation service to use */ public static void setConsolidationService(String service) { grobidConfig.grobid.consolidation.service = service; } /** * Returns if the execution context is stand alone or server. * * @return the context of execution. Return false if the property value is * not readable. */ public static boolean isContextExecutionServer() { return contextExecutionServer; } /** * Set if the execution context is stand alone or server. * * @param state true to set the context of execution to server, false else. */ public static void setContextExecutionServer(boolean state) { contextExecutionServer = state; } public static String getPythonVirtualEnv() { return grobidConfig.grobid.delft.python_virtualEnv; } public static void setPythonVirtualEnv(String pythonVirtualEnv) { grobidConfig.grobid.delft.python_virtualEnv = pythonVirtualEnv; } public static int getWindow(final GrobidModel model) { ModelParameters parameters = modelMap.get(model.getModelName()); if (parameters != null && parameters.wapiti != null) return parameters.wapiti.window; else return 20; } public static double getEpsilon(final GrobidModel model) { ModelParameters parameters = modelMap.get(model.getModelName()); if (parameters != null && parameters.wapiti != null) return parameters.wapiti.epsilon; else return 0.00001; } public static int getNbMaxIterations(final GrobidModel model) { ModelParameters parameters = modelMap.get(model.getModelName()); if (parameters != null && parameters.wapiti != null) return parameters.wapiti.nbMaxIterations; else return 2000; } public static boolean useELMo(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.warn("No configuration parameter defined for model " + modelName); return false; } DelftModelParameters delftParam = param.delft; if (delftParam == null) { LOGGER.warn("No configuration parameter defined for DeLFT engine for model " + modelName); return false; } return param.delft.useELMo; } public static String getDelftArchitecture(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.warn("No configuration parameter defined for model " + modelName); return null; } DelftModelParameters delftParam = param.delft; if (delftParam == null) { LOGGER.warn("No configuration parameter defined for DeLFT engine for model " + modelName); return null; } return param.delft.architecture; } public static String getDelftEmbeddingsName(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.warn("No configuration parameter defined for model " + modelName); return null; } DelftModelParameters delftParam = param.delft; if (delftParam == null) { LOGGER.warn("No configuration parameter defined for DeLFT engine for model " + modelName); return null; } return param.delft.embeddings_name; } /** * Return -1 if not set in the configuration and the default DeLFT value will be used in this case. */ public static int getDelftTrainingMaxSequenceLength(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.warn("No configuration parameter defined for model " + modelName); return -1; } DelftModelParameters delftParam = param.delft; if (delftParam == null) { LOGGER.warn("No configuration parameter defined for DeLFT engine for model " + modelName); return -1; } DelftModelParameterSet delftParamSet = param.delft.training; if (delftParamSet == null) { LOGGER.warn("No training configuration parameter defined for DeLFT engine for model " + modelName); return -1; } return param.delft.training.max_sequence_length; } /** * Return -1 if not set in the configuration and the default DeLFT value will be used in this case. */ public static int getDelftRuntimeMaxSequenceLength(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.warn("No configuration parameter defined for model " + modelName); return -1; } DelftModelParameters delftParam = param.delft; if (delftParam == null) { LOGGER.warn("No configuration parameter defined for DeLFT engine for model " + modelName); return -1; } DelftModelParameterSet delftParamSet = param.delft.runtime; if (delftParamSet == null) { LOGGER.warn("No runtime configuration parameter defined for DeLFT engine for model " + modelName); return -1; } return param.delft.runtime.max_sequence_length; } /** * Return -1 if not set in the configuration and the default DeLFT value will be used in this case. */ public static int getDelftTrainingBatchSize(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.warn("No configuration parameter defined for model " + modelName); return -1; } DelftModelParameters delftParam = param.delft; if (delftParam == null) { LOGGER.warn("No configuration parameter defined for DeLFT engine for model " + modelName); return -1; } DelftModelParameterSet delftParamSet = param.delft.training; if (delftParamSet == null) { LOGGER.warn("No training configuration parameter defined for DeLFT engine for model " + modelName); return -1; } return param.delft.training.batch_size; } /** * Return -1 if not set in the configuration and the default DeLFT value will be used in this case. */ public static int getDelftRuntimeBatchSize(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.warn("No configuration parameter defined for model " + modelName); return -1; } DelftModelParameters delftParam = param.delft; if (delftParam == null) { LOGGER.warn("No configuration parameter defined for DeLFT engine for model " + modelName); return -1; } DelftModelParameterSet delftParamSet = param.delft.runtime; if (delftParamSet == null) { LOGGER.warn("No runtime configuration parameter defined for DeLFT engine for model " + modelName); return -1; } return param.delft.runtime.batch_size; } public static String getDelftArchitecture(final GrobidModel model) { return getDelftArchitecture(model.getModelName()); } }
grobid-core/src/main/java/org/grobid/core/utilities/GrobidProperties.java
package org.grobid.core.utilities; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.grobid.core.GrobidModel; import org.grobid.core.engines.tagging.GrobidCRFEngine; import org.grobid.core.exceptions.GrobidPropertyException; import org.grobid.core.exceptions.GrobidResourceException; import org.grobid.core.utilities.GrobidConfig.ModelParameters; import org.grobid.core.utilities.GrobidConfig.DelftModelParameters; import org.grobid.core.utilities.GrobidConfig.DelftModelParameterSet; import org.grobid.core.utilities.GrobidConfig.WapitiModelParameters; import org.grobid.core.main.GrobidHomeFinder; import org.grobid.core.utilities.Consolidation.GrobidConsolidationService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.fasterxml.jackson.databind.DeserializationFeature; /** * This class provide methods to set/load/access grobid config value from a yaml config file loaded * in the class {@link GrobidConfig}. * * New yaml parameters and former properties should be equivalent via this class. We keep the * class name "GrobidProperties" for compatibility with Grobid modules and other Java applications * using Grobid as a library. * * to be done: having parameters that can be overridden by a system property having a compatible name. */ public class GrobidProperties { public static final Logger LOGGER = LoggerFactory.getLogger(GrobidProperties.class); static final String FOLDER_NAME_MODELS = "models"; static final String FILE_NAME_MODEL = "model"; private static final String GROBID_VERSION_FILE = "/grobid-version.txt"; static final String UNKNOWN_VERSION_STR = "unknown"; private static GrobidProperties grobidProperties = null; // indicate if GROBID is running in server mode or not private static boolean contextExecutionServer = false; /** * {@link GrobidConfig} object containing all config parameters used by grobid. */ private static GrobidConfig grobidConfig = null; /** * Map models specified inthe config file to their parameters */ private static Map<String, ModelParameters> modelMap = null; /** * Path to pdf to xml converter. */ private static File pathToPdfalto = null; private static File grobidHome = null; /** * Path to the yaml config file */ static File GROBID_CONFIG_PATH = null; private static String GROBID_VERSION = null; /** * Returns an instance of {@link GrobidProperties} object. If no one is set, then * it creates one */ public static GrobidProperties getInstance() { if (grobidProperties == null) { return getNewInstance(); } else { return grobidProperties; } } /** * Returns an instance of {@link GrobidProperties} object based on a custom grobid-home directory. * If no one is set, then it creates one. */ public static GrobidProperties getInstance(GrobidHomeFinder grobidHomeFinder) { synchronized (GrobidProperties.class) { if (grobidHome == null) { grobidHome = grobidHomeFinder.findGrobidHomeOrFail(); } } return getInstance(); } /** * Reload grobid config */ public static void reload() { getNewInstance(); } public static void reset() { getNewInstance(); } /** * Creates a new {@link GrobidProperties} object, initializes and returns it. * * @return GrobidProperties */ protected static synchronized GrobidProperties getNewInstance() { LOGGER.debug("synchronized getNewInstance"); grobidProperties = new GrobidProperties(); return grobidProperties; } /** * Load the path to GROBID_HOME from the env-entry set in web.xml. */ private static void assignGrobidHomePath() { if (grobidHome == null) { synchronized (GrobidProperties.class) { if (grobidHome == null) { grobidHome = new GrobidHomeFinder().findGrobidHomeOrFail(); } } } } /** * Return the grobid-home path. * * @return grobid home path */ public static File getGrobidHome() { return grobidHome; } public static File getGrobidHomePath() { return grobidHome; } /** * For back compatibility */ @Deprecated public static File get_GROBID_HOME_PATH() { return grobidHome; } /** * Set the grobid-home path. */ public static void setGrobidHome(final String pGROBID_HOME_PATH) { if (StringUtils.isBlank(pGROBID_HOME_PATH)) throw new GrobidPropertyException("Cannot set property grobidHome to null or empty."); grobidHome = new File(pGROBID_HOME_PATH); // exception if prop file does not exist if (!grobidHome.exists()) { throw new GrobidPropertyException("Could not read GROBID_HOME, the directory '" + pGROBID_HOME_PATH + "' does not exist."); } try { grobidHome = grobidHome.getCanonicalFile(); } catch (IOException e) { throw new GrobidPropertyException("Cannot set grobid home path to the given one '" + pGROBID_HOME_PATH + "', because it does not exist."); } } /** * Load the path to grobid config yaml from the env-entry set in web.xml. */ static void loadGrobidConfigPath() { LOGGER.debug("loading grobid config yaml"); if (GROBID_CONFIG_PATH == null) { synchronized (GrobidProperties.class) { if (GROBID_CONFIG_PATH == null) { GROBID_CONFIG_PATH = new GrobidHomeFinder().findGrobidConfigOrFail(grobidHome); } } } } /** * Return the path to the GROBID yaml config file * * @return grobid properties path */ public static File getGrobidConfigPath() { return GROBID_CONFIG_PATH; } /** * Set the GROBID config yaml file path. */ public static void setGrobidConfigPath(final String pGrobidConfigPath) { if (StringUtils.isBlank(pGrobidConfigPath)) throw new GrobidPropertyException("Cannot set GROBID config file to null or empty."); File grobidConfigPath = new File(pGrobidConfigPath); // exception if config file does not exist if (!grobidConfigPath.exists()) { throw new GrobidPropertyException("Cannot read GROBID yaml config file, the file '" + pGrobidConfigPath + "' does not exist."); } try { GROBID_CONFIG_PATH = grobidConfigPath.getCanonicalFile(); } catch (IOException e) { throw new GrobidPropertyException("Cannot set grobid yaml config file path to the given one '" + pGrobidConfigPath + "', because it does not exist."); } } /** * Create a new object and search where to find the grobid-home folder. * * We check if the system property GrobidPropertyKeys.PROP_GROBID_HOME * is set. If not set, the method will search for a folder named * grobid-home in the current project. * * Finally from the found grobid-home, the yaml config file is loaded and * the native and data resource paths are initialized. */ public GrobidProperties() { assignGrobidHomePath(); loadGrobidConfigPath(); setContextExecutionServer(false); try { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); grobidConfig = mapper.readValue(GROBID_CONFIG_PATH, GrobidConfig.class); } catch (IOException exp) { throw new GrobidPropertyException("Cannot open GROBID config yaml file at location '" + GROBID_CONFIG_PATH.getAbsolutePath() + "'", exp); } catch (Exception exp) { throw new GrobidPropertyException("Cannot open GROBID config yaml file " + getGrobidConfigPath().getAbsolutePath(), exp); } //getProps().putAll(getEnvironmentVariableOverrides(System.getenv())); initializeTmpPath(); // TBD: tmp to be created loadPdfaltoPath(); createModelMap(); } /** * Create a map between model names and associated parameters */ private static void createModelMap() { for(ModelParameters modelParameter : grobidConfig.grobid.models) { if (modelMap == null) modelMap = new TreeMap<>(); modelMap.put(modelParameter.name, modelParameter); } } /** * Create indicated tmp path if it does not exist */ private void initializeTmpPath() { File tmpDir = getTempPath(); if (!tmpDir.exists()) { if (!tmpDir.mkdirs()) { LOGGER.warn("tmp does not exist and unable to create tmp directory: " + tmpDir.getAbsolutePath()); } } } /** * Return the distinct values of all the engines that are specified in the the config file */ public static Set<GrobidCRFEngine> getDistinctModels() { Set<GrobidCRFEngine> distinctModels = new HashSet<>(); for(ModelParameters modelParameter : grobidConfig.grobid.models) { if (modelParameter.engine == null) { // it should not happen normally continue; } GrobidCRFEngine localEngine = GrobidCRFEngine.get(modelParameter.engine); if (!distinctModels.contains(localEngine)) distinctModels.add(localEngine); } return distinctModels; } /** * Returns the current version of GROBID * * @return GROBID version */ public static String getVersion() { if (GROBID_VERSION == null) { synchronized (GrobidProperties.class) { if (GROBID_VERSION == null) { String grobidVersion = UNKNOWN_VERSION_STR; try (InputStream is = GrobidProperties.class.getResourceAsStream(GROBID_VERSION_FILE)) { grobidVersion = IOUtils.toString(is, "UTF-8"); } catch (IOException e) { LOGGER.error("Cannot read Grobid version from resources", e); } GROBID_VERSION = grobidVersion; } } } return GROBID_VERSION; } /** * Returns the temprorary path of grobid * * @return a directory for temp files */ public static File getTempPath() { if (grobidConfig.grobid.temp == null) return new File(System.getProperty("java.io.tmpdir")); else return new File(grobidHome.getPath(), grobidConfig.grobid.temp); } public static void setNativeLibraryPath(final String nativeLibPath) { grobidConfig.grobid.nativelibrary = nativeLibPath; } /** * Returns the path to the native libraries as {@link File} object. * * @return folder that contains native libraries */ public static File getNativeLibraryPath() { return new File(grobidHome.getPath(), grobidConfig.grobid.nativelibrary); } /** * Returns the installation path of DeLFT if set, null otherwise. It is required for using * a Deep Learning sequence labelling engine. * * @return path to the folder that contains the local install of DeLFT */ public static String getDeLFTPath() { return grobidConfig.grobid.delft.install; } public static String getDeLFTFilePath() { String rawPath = grobidConfig.grobid.delft.install; File pathFile = new File(rawPath); if (!Files.exists(Paths.get(rawPath).toAbsolutePath())) { rawPath = "../" + rawPath; pathFile = new File(rawPath); } return pathFile.getAbsolutePath(); } public static String getGluttonUrl() { if (grobidConfig.grobid.consolidation.glutton.url == null || grobidConfig.grobid.consolidation.glutton.url.trim().length() == 0) return null; else return grobidConfig.grobid.consolidation.glutton.url; } public static void setGluttonUrl(final String theUrl) { grobidConfig.grobid.consolidation.glutton.url = theUrl; } /** * Returns the host for a proxy connection, given in the grobid config file. * * @return proxy host */ public static String getProxyHost() { if (grobidConfig.grobid.proxy.host == null || grobidConfig.grobid.proxy.host.trim().length() == 0) return null; else return grobidConfig.grobid.proxy.host; } /** * Sets the host a proxy connection, given in the config file. * * @param the proxy host to be used */ public static void setProxyHost(final String host) { grobidConfig.grobid.proxy.host = host; System.setProperty("http.proxyHost", host); System.setProperty("https.proxyHost", host); } /** * Returns the port for a proxy connection, given in the grobid config file. * * @return proxy port */ public static Integer getProxyPort() { return grobidConfig.grobid.proxy.port; } /** * Set the "mailto" parameter to be used in the crossref query and in User-Agent * header, as recommended by CrossRef REST API documentation. * * @param mailto email parameter to be used for requesting crossref */ public static void setCrossrefMailto(final String mailto) { grobidConfig.grobid.consolidation.crossref.mailto = mailto; } /** * Get the "mailto" parameter to be used in the crossref query and in User-Agent * header, as recommended by CrossRef REST API documentation. * * @return string of the email parameter to be used for requesting crossref */ public static String getCrossrefMailto() { if (grobidConfig.grobid.consolidation.crossref.mailto == null || grobidConfig.grobid.consolidation.crossref.mailto.trim().length() == 0) return null; else return grobidConfig.grobid.consolidation.crossref.mailto; } /** * Set the Crossref Metadata Plus authorization token to be used for Crossref * requests for the subscribers of this service. This token will ensure that said * requests get directed to a pool of machines that are reserved for "Plus" SLA users. * * @param token authorization token to be used for requesting crossref */ public static void setCrossrefToken(final String token) { grobidConfig.grobid.consolidation.crossref.token = token; } /** * Get the Crossref Metadata Plus authorization token to be used for Crossref * requests for the subscribers of this service. This token will ensure that said * requests get directed to a pool of machines that are reserved for "Plus" SLA users. * * @return authorization token to be used for requesting crossref */ public static String getCrossrefToken() { if (grobidConfig.grobid.consolidation.crossref.token == null || grobidConfig.grobid.consolidation.crossref.token.trim().length() == 0) return null; else return grobidConfig.grobid.consolidation.crossref.token; } /** * Sets the port for a proxy connection, given in the grobid config file. * * @param proxy port */ public static void setProxyPort(int port) { grobidConfig.grobid.proxy.port = port; System.setProperty("http.proxyPort", ""+port); System.setProperty("https.proxyPort", ""+port); } public static Integer getPdfaltoMemoryLimitMb() { return grobidConfig.grobid.pdf.pdfalto.memory_limit_mb; } public static Integer getPdfaltoTimeoutMs() { return grobidConfig.grobid.pdf.pdfalto.timeout_sec * 1000; } /** * Returns the number of threads to be used when training, given in the grobid config file. * * @return number of threads */ public static Integer getNBThreads() { Integer nbThreadsConfig = Integer.valueOf(grobidConfig.grobid.nb_threads); if (nbThreadsConfig.intValue() == 0) { return Integer.valueOf(Runtime.getRuntime().availableProcessors()); } return nbThreadsConfig; } // PDF with more blocks will be skipped public static Integer getPdfBlocksMax() { return grobidConfig.grobid.pdf.blocks_max; } // PDF with more tokens will be skipped public static Integer getPdfTokensMax() { return grobidConfig.grobid.pdf.tokens_max; } /** * Sets the number of threads, given in the grobid-property file. * * @param nbThreads umber of threads */ public static void setNBThreads(int nbThreads) { grobidConfig.grobid.nb_threads = nbThreads; } public static String getLanguageDetectorFactory() { String factoryClassName = grobidConfig.grobid.language_detector_factory; if (StringUtils.isBlank(factoryClassName)) { throw new GrobidPropertyException("Language detection is enabled but a factory class name is not provided"); } return factoryClassName; } /** * Sets if a language id shall be used, given in the grobid-property file. * * @param useLanguageId true, if a language id shall be used */ /*public static void setUseLanguageId(final String useLanguageId) { setPropertyValue(GrobidPropertyKeys.PROP_USE_LANG_ID, useLanguageId); }*/ public static String getSentenceDetectorFactory() { String factoryClassName = grobidConfig.grobid.sentence_detector_factory; if (StringUtils.isBlank(factoryClassName)) { throw new GrobidPropertyException("Sentence detection is enabled but a factory class name is not provided"); } return factoryClassName; } /** * Returns the path to the home folder of pdf to xml converter. */ public static void loadPdfaltoPath() { LOGGER.debug("loading pdfalto command path"); String pathName = grobidConfig.grobid.pdf.pdfalto.path; pathToPdfalto = new File(grobidHome.getPath(), pathName); if (!pathToPdfalto.exists()) { throw new GrobidPropertyException( "Path to pdfalto doesn't exists. " + "Please set the path to pdfalto in the config file"); } pathToPdfalto = new File(pathToPdfalto, Utilities.getOsNameAndArch()); LOGGER.debug("pdfalto executable home directory set to " + pathToPdfalto.getAbsolutePath()); } /** * Returns the path to the home folder of pdfalto program. * * @return path to pdfalto program */ public static File getPdfaltoPath() { return pathToPdfalto; } private static String getGrobidCRFEngineName(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.error("No configuration parameter defined for model " + modelName); return null; } return param.engine; } public static GrobidCRFEngine getGrobidCRFEngine(final String modelName) { String engineName = getGrobidCRFEngineName(modelName); if (engineName == null) return null; else return GrobidCRFEngine.get(engineName); } public static GrobidCRFEngine getGrobidCRFEngine(final GrobidModel model) { return getGrobidCRFEngine(model.getModelName()); } public static File getModelPath(final GrobidModel model) { if (modelMap.get(model.getModelName()) == null) { // model is not specified in the config, ignoring return null; } String extension = getGrobidCRFEngine(model).getExt(); return new File(getGrobidHome(), FOLDER_NAME_MODELS + File.separator + model.getFolderName() + File.separator + FILE_NAME_MODEL + "." + extension); } public static File getModelPath() { return new File(getGrobidHome(), FOLDER_NAME_MODELS); } public static File getTemplatePath(final File resourcesDir, final GrobidModel model) { if (modelMap.get(model.getModelName()) == null) { // model is not specified in the config, ignoring return null; } File theFile = new File(resourcesDir, "dataset/" + model.getFolderName() + "/crfpp-templates/" + model.getTemplateName()); if (!theFile.exists()) { theFile = new File("resources/dataset/" + model.getFolderName() + "/crfpp-templates/" + model.getTemplateName()); } return theFile; } public static File getEvalCorpusPath(final File resourcesDir, final GrobidModel model) { File theFile = new File(resourcesDir, "dataset/" + model.getFolderName() + "/evaluation/"); if (!theFile.exists()) { theFile = new File("resources/dataset/" + model.getFolderName() + "/evaluation/"); } return theFile; } public static File getCorpusPath(final File resourcesDir, final GrobidModel model) { File theFile = new File(resourcesDir, "dataset/" + model.getFolderName() + "/corpus"); if (!theFile.exists()) { theFile = new File("resources/dataset/" + model.getFolderName() + "/corpus"); } return theFile; } public static String getLexiconPath() { return new File(getGrobidHome(), "lexicon").getAbsolutePath(); } public static File getLanguageDetectionResourcePath() { return new File(getGrobidHome(), "language-detection"); } /** * Returns the maximum parallel connections allowed in the pool. * * @return the number of connections */ public static int getMaxPoolConnections() { return grobidConfig.grobid.max_connections; } /** * Returns maximum time to wait before timeout when the pool is full. * * @return time to wait in milliseconds. */ public static int getPoolMaxWait() { return grobidConfig.grobid.pool_max_wait * 1000; } /** * Returns the consolidation service to be used. * * @return the consolidation service to be used */ public static GrobidConsolidationService getConsolidationService() { if (grobidConfig.grobid.consolidation.service == null) grobidConfig.grobid.consolidation.service = "crossref"; return GrobidConsolidationService.get(grobidConfig.grobid.consolidation.service); } /** * Set which consolidation service to use */ public static void setConsolidationService(String service) { grobidConfig.grobid.consolidation.service = service; } /** * Returns if the execution context is stand alone or server. * * @return the context of execution. Return false if the property value is * not readable. */ public static boolean isContextExecutionServer() { return contextExecutionServer; } /** * Set if the execution context is stand alone or server. * * @param state true to set the context of execution to server, false else. */ public static void setContextExecutionServer(boolean state) { contextExecutionServer = state; } public static String getPythonVirtualEnv() { return grobidConfig.grobid.delft.python_virtualEnv; } public static void setPythonVirtualEnv(String pythonVirtualEnv) { grobidConfig.grobid.delft.python_virtualEnv = pythonVirtualEnv; } public static int getWindow(final GrobidModel model) { ModelParameters parameters = modelMap.get(model.getModelName()); if (parameters != null && parameters.wapiti != null) return parameters.wapiti.window; else return 20; } public static double getEpsilon(final GrobidModel model) { ModelParameters parameters = modelMap.get(model.getModelName()); if (parameters != null && parameters.wapiti != null) return parameters.wapiti.epsilon; else return 0.00001; } public static int getNbMaxIterations(final GrobidModel model) { ModelParameters parameters = modelMap.get(model.getModelName()); if (parameters != null && parameters.wapiti != null) return parameters.wapiti.nbMaxIterations; else return 2000; } public static boolean useELMo(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.warn("No configuration parameter defined for model " + modelName); return false; } DelftModelParameters delftParam = param.delft; if (delftParam == null) { LOGGER.warn("No configuration parameter defined for DeLFT engine for model " + modelName); return false; } return param.delft.useELMo; } public static String getDelftArchitecture(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.warn("No configuration parameter defined for model " + modelName); return null; } DelftModelParameters delftParam = param.delft; if (delftParam == null) { LOGGER.warn("No configuration parameter defined for DeLFT engine for model " + modelName); return null; } return param.delft.architecture; } public static String getDelftEmbeddingsName(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.warn("No configuration parameter defined for model " + modelName); return null; } DelftModelParameters delftParam = param.delft; if (delftParam == null) { LOGGER.warn("No configuration parameter defined for DeLFT engine for model " + modelName); return null; } return param.delft.embeddings_name; } /** * Return -1 if not set in the configuration and the default DeLFT value will be used in this case. */ public static int getDelftTrainingMaxSequenceLength(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.warn("No configuration parameter defined for model " + modelName); return -1; } DelftModelParameters delftParam = param.delft; if (delftParam == null) { LOGGER.warn("No configuration parameter defined for DeLFT engine for model " + modelName); return -1; } DelftModelParameterSet delftParamSet = param.delft.training; if (delftParamSet == null) { LOGGER.warn("No training configuration parameter defined for DeLFT engine for model " + modelName); return -1; } return param.delft.training.max_sequence_length; } /** * Return -1 if not set in the configuration and the default DeLFT value will be used in this case. */ public static int getDelftRuntimeMaxSequenceLength(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.warn("No configuration parameter defined for model " + modelName); return -1; } DelftModelParameters delftParam = param.delft; if (delftParam == null) { LOGGER.warn("No configuration parameter defined for DeLFT engine for model " + modelName); return -1; } DelftModelParameterSet delftParamSet = param.delft.runtime; if (delftParamSet == null) { LOGGER.warn("No runtime configuration parameter defined for DeLFT engine for model " + modelName); return -1; } return param.delft.runtime.max_sequence_length; } /** * Return -1 if not set in the configuration and the default DeLFT value will be used in this case. */ public static int getDelftTrainingBatchSize(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.warn("No configuration parameter defined for model " + modelName); return -1; } DelftModelParameters delftParam = param.delft; if (delftParam == null) { LOGGER.warn("No configuration parameter defined for DeLFT engine for model " + modelName); return -1; } DelftModelParameterSet delftParamSet = param.delft.training; if (delftParamSet == null) { LOGGER.warn("No training configuration parameter defined for DeLFT engine for model " + modelName); return -1; } return param.delft.training.batch_size; } /** * Return -1 if not set in the configuration and the default DeLFT value will be used in this case. */ public static int getDelftRuntimeBatchSize(final String modelName) { ModelParameters param = modelMap.get(modelName); if (param == null) { LOGGER.warn("No configuration parameter defined for model " + modelName); return -1; } DelftModelParameters delftParam = param.delft; if (delftParam == null) { LOGGER.warn("No configuration parameter defined for DeLFT engine for model " + modelName); return -1; } DelftModelParameterSet delftParamSet = param.delft.runtime; if (delftParamSet == null) { LOGGER.warn("No runtime configuration parameter defined for DeLFT engine for model " + modelName); return -1; } return param.delft.runtime.batch_size; } public static String getDelftArchitecture(final GrobidModel model) { return getDelftArchitecture(model.getModelName()); } }
enable module to add their model parameters
grobid-core/src/main/java/org/grobid/core/utilities/GrobidProperties.java
enable module to add their model parameters
<ide><path>robid-core/src/main/java/org/grobid/core/utilities/GrobidProperties.java <ide> } <ide> <ide> /** <add> * Add a model with its parameter object in the model map <add> */ <add> public static void addModel(ModelParameters modelParameter) { <add> if (modelMap == null) <add> modelMap = new TreeMap<>(); <add> modelMap.put(modelParameter.name, modelParameter); <add> } <add> <add> /** <ide> * Create indicated tmp path if it does not exist <ide> */ <ide> private void initializeTmpPath() {
Java
agpl-3.0
1bbecac22181eb86aaa1fd952d8761c2d627d312
0
B3Partners/flamingo,B3Partners/flamingo,flamingo-geocms/flamingo,flamingo-geocms/flamingo,B3Partners/flamingo,flamingo-geocms/flamingo,flamingo-geocms/flamingo,B3Partners/flamingo
/* * Copyright (C) 2011-2016 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 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 nl.b3p.viewer.stripes; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.util.HtmlUtil; import net.sourceforge.stripes.util.StringUtil; import net.sourceforge.stripes.validation.LocalizableError; import net.sourceforge.stripes.validation.SimpleError; import net.sourceforge.stripes.validation.Validate; import nl.b3p.i18n.ResourceBundleProvider; import nl.b3p.viewer.components.ComponentRegistry; import nl.b3p.viewer.components.ComponentRegistryInitializer; import nl.b3p.viewer.config.ClobElement; import nl.b3p.viewer.config.app.Application; import nl.b3p.viewer.config.app.ConfiguredComponent; import nl.b3p.viewer.config.metadata.Metadata; import nl.b3p.viewer.config.security.Authorizations; import nl.b3p.viewer.config.security.User; import nl.b3p.viewer.util.SelectedContentCache; import org.apache.commons.lang.StringUtils; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.security.Principal; import java.util.*; /** * * @author Matthijs Laan */ @UrlBinding("/app/{name}/v{version}") @StrictBinding public class ApplicationActionBean extends LocalizableApplicationActionBean implements ActionBean { private ActionBeanContext context; @Validate private String name; @Validate private boolean unknown; @Validate private String version; // <editor-fold desc="bookmark variables" defaultstate="collapsed"> @Validate private String bookmark; @Validate private String extent; @Validate private String layers; @Validate private String levelOrder; // </editor-fold> @Validate private boolean debug; @Validate(on = "retrieveAppConfigJSON") private Application application; private String componentSourceHTML; private String appConfigJSON; private String viewerType; private String title; private String language; private JSONObject user; private String loginUrl; private HashMap<String,Object> globalLayout; //<editor-fold defaultstate="collapsed" desc="getters en setters"> public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } public Application getApplication() { return application; } public void setApplication(Application application) { this.application = application; } public void setContext(ActionBeanContext context) { this.context = context; } public ActionBeanContext getContext() { return context; } public String getComponentSourceHTML() { return componentSourceHTML; } public void setComponentSourceHTML(String componentSourceHTML) { this.componentSourceHTML = componentSourceHTML; } public String getAppConfigJSON() { return appConfigJSON; } public void setAppConfigJSON(String appConfigJSON) { this.appConfigJSON = appConfigJSON; } public String getViewerType(){ return viewerType; } public void setViewerType(String viewerType){ this.viewerType = viewerType; } public String getTitle(){ return title; } public void setTitle(String title){ this.title = title; } public String getLanguage(){ return language; } public void setLanguage(String language){ this.language = language; } public JSONObject getUser() { return user; } public void setUser(JSONObject user) { this.user = user; } public String getLoginUrl() { return loginUrl; } public void setLoginUrl(String loginUrl) { this.loginUrl = loginUrl; } public HashMap getGlobalLayout() { return globalLayout; } public void setGlobalLayout(HashMap globalLayout) { this.globalLayout = globalLayout; } public boolean isUnknown() { return unknown; } public void setUnknown(boolean unknown) { this.unknown = unknown; } public String getBookmark() { return bookmark; } public void setBookmark(String bookmark) { this.bookmark = bookmark; } public String getExtent() { return extent; } public void setExtent(String extent) { this.extent = extent; } public String getLayers() { return layers; } public void setLayers(String layers) { this.layers = layers; } public String getLevelOrder() { return levelOrder; } public void setLevelOrder(String levelOrder) { this.levelOrder = levelOrder; } //</editor-fold> static Application findApplication(String name, String version) { EntityManager em = Stripersist.getEntityManager(); if(name != null) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery q = cb.createQuery(Application.class); Root<Application> root = q.from(Application.class); Predicate namePredicate = cb.equal(root.get("name"), name); Predicate versionPredicate = version != null ? cb.equal(root.get("version"), version) : cb.isNull(root.get("version")); q.where(cb.and(namePredicate, versionPredicate)); try { return (Application) em.createQuery(q).getSingleResult(); } catch(NoResultException nre) { String decodedName = StringUtil.urlDecode(name); if(!decodedName.equals(name)){ return findApplication(decodedName, version); } } } return null; } public Resolution saveCache() throws JSONException, IOException{ Resolution view = view(); EntityManager em = Stripersist.getEntityManager(); Resolution r = checkRestriction(context, application, em); if (r != null) { return r; } SelectedContentCache cache = new SelectedContentCache(); JSONObject sc = cache.createSelectedContent(application, false,false, false,em); application.getDetails().put("selected_content_cache", new ClobElement(sc.toString())); em.getTransaction().commit(); return view; } public Resolution retrieveCache() throws JSONException, IOException{ Resolution view = view(); EntityManager em = Stripersist.getEntityManager(); Resolution r = checkRestriction(context, application, em); if (r != null) { return r; } ClobElement el = application.getDetails().get("selected_content_cache"); appConfigJSON = el.getValue(); return view; } public Resolution retrieveAppConfigJSON() throws IOException { EntityManager em = Stripersist.getEntityManager(); JSONObject response = new JSONObject(); response.put("success", false); JSONObject obj = application.toJSON(context.getRequest(), false, false, em); JSONObject details = obj.optJSONObject("details"); if (details != null) { details.remove(SelectedContentCache.DETAIL_CACHED_EXPANDED_SELECTED_CONTENT); details.remove(SelectedContentCache.DETAIL_CACHED_SELECTED_CONTENT); } appConfigJSON = obj.toString(); response.put("config", appConfigJSON); response.put("success", true); return new StreamingResolution("application/json", new StringReader(response.toString())); } @DefaultHandler public Resolution view() throws JSONException, IOException { if(unknown){ getDefaultViewer(); /* Redirected here from /index.jsp: further redirect to app with * name and version parameters of default app in URL and * unknown=false. This makes sure that links in URL always include * the app name. Required for compact bookmark links for default app * to work. */ return new RedirectResolution(ApplicationActionBean.class) .addParameter("name", name) .addParameter("version", version) .addParameter("debug", debug); } application = findApplication(name, version); if(application == null) { getContext().getValidationErrors().addGlobalError(new LocalizableError("app.notfound", HtmlUtil.encode(name + (version != null ? " v" + version : "")))); return new ForwardResolution("/WEB-INF/jsp/error.jsp"); } RedirectResolution login = new RedirectResolution(ApplicationActionBean.class) .addParameter("name", name) // binded parameters not included ? .addParameter("version", version) .addParameter("debug", debug) .addParameter("uitloggen", true) .includeRequestParameters(true); addBookmarkParameters(login); loginUrl = login.getUrl(context.getLocale()); String username = context.getRequest().getRemoteUser(); if(application.isAuthenticatedRequired() && username == null) { return login; } EntityManager em = Stripersist.getEntityManager(); Resolution r = checkRestriction(context, application, em); if(r != null){ return r; } if(username != null) { user = new JSONObject(); user.put("name", username); JSONObject roles = new JSONObject(); user.put("roles", roles); for(String role: Authorizations.getRoles(context.getRequest(),em)) { roles.put(role, Boolean.TRUE); } } buildComponentSourceHTML(em); appConfigJSON = application.toJSON(context.getRequest(),false, false,em).toString(); this.viewerType = retrieveViewerType(); if(StringUtils.isBlank(title)) { this.title = application.getName(); } this.language = application.getLang(); if(StringUtils.isBlank(language)) { this.language = "nl_NL"; } //make hashmap for jsonobject. this.globalLayout = new HashMap<String,Object>(); JSONObject layout = application.getGlobalLayout(); Iterator<String> keys = layout.keys(); while (keys.hasNext()){ String key = keys.next(); this.globalLayout.put(key, layout.get(key)); } context.getResponse().addHeader("X-UA-Compatible", "IE=edge"); return new ForwardResolution("/WEB-INF/jsp/app.jsp"); } public static Resolution checkRestriction(ActionBeanContext context, Application application, EntityManager em){ String username = context.getRequest().getRemoteUser(); User u = null; if(username != null){ Principal p = context.getRequest().getUserPrincipal(); if( p instanceof User){ u = (User)p; }else{ u = em.find(User.class, p.getName()); } } if(Authorizations.isUserExpired(u, context)){ ResourceBundle bundle = ResourceBundleProvider.getResourceBundle(determineLocaleForBundle(context, application)); String msg = bundle.getString("viewer.applicationactionbean.expired"); context.getValidationErrors().addGlobalError(new SimpleError(msg)); context.getRequest().getSession().invalidate(); return new ForwardResolution("/WEB-INF/jsp/error.jsp"); } else if (!Authorizations.isApplicationReadAuthorized(application, context.getRequest(), em) && (username == null || u != null && u.isAuthenticatedByIp())) { RedirectResolution login = new RedirectResolution(LoginActionBean.class) .addParameter("name", application.getName()) // binded parameters not included ? .addParameter("version", application.getVersion()) .includeRequestParameters(true); context.getRequest().getSession().invalidate(); return login; } else if (!Authorizations.isApplicationReadAuthorized(application, context.getRequest(), em) && username != null) { ResourceBundle bundle = ResourceBundleProvider.getResourceBundle(determineLocaleForBundle(context, application)); String msg = bundle.getString("viewer.applicationactionbean.norights"); context.getValidationErrors().addGlobalError(new SimpleError(msg)); context.getRequest().getSession().invalidate(); return new ForwardResolution("/WEB-INF/jsp/error_retry.jsp"); } return null; } /** * Build a hash key to make the single component source for all components * cacheable but updateable when the roles of the user change. This is not * meant to be a secure hash, the roles of a user are not secret. * * @param request servlet request with user credential * @param em the entitymanahger to use for database access * @return a key to use as a cache identifyer */ public static int getRolesCachekey(HttpServletRequest request, EntityManager em) { Set<String> roles = Authorizations.getRoles(request, em); if(roles.isEmpty()) { return 0; } List<String> sorted = new ArrayList<String>(roles); Collections.sort(sorted); int hash = 0; for(String role: sorted) { hash = hash ^ role.hashCode(); } return hash; } public Resolution uitloggen(){ application = findApplication(name, version); context.getRequest().getSession().invalidate(); if("true".equals(context.getRequest().getParameter("logout")) && "true".equals(context.getRequest().getParameter("returnAfterLogout"))) { RedirectResolution r = new RedirectResolution(ApplicationActionBean.class) .addParameter("name", application.getName()) .addParameter("version", application.getVersion()); addBookmarkParameters(r); return r; } else { RedirectResolution r = new RedirectResolution(LoginActionBean.class) .addParameter("name", application.getName()) .addParameter("version", application.getVersion()); addBookmarkParameters(r); return r; } } private void addBookmarkParameters(RedirectResolution r) { if (bookmark != null) { r.addParameter("bookmark", bookmark); } if(extent != null){ r.addParameter("extent", extent); } if(layers != null){ r.addParameter("layers", layers); } if(levelOrder != null){ r.addParameter("levelOrder", levelOrder); } } private void buildComponentSourceHTML(EntityManager em) throws IOException { StringBuilder sb = new StringBuilder(); // Sort components by classNames, so order is always the same for debugging ComponentRegistry cr = ComponentRegistryInitializer.getInstance(); List<ConfiguredComponent> comps = new ArrayList<ConfiguredComponent>(application.getComponents()); Collections.sort(comps); if(isDebug()) { Set<String> classNamesDone = new HashSet<String>(); for(ConfiguredComponent cc: comps) { if(!Authorizations.isConfiguredComponentAuthorized(cc, context.getRequest(), em)) { continue; } if(!classNamesDone.contains(cc.getClassName())) { classNamesDone.add(cc.getClassName()); if(cc.getViewerComponent() != null && cc.getViewerComponent().getSources() != null) { for(File f: cc.getViewerComponent().getSources()) { String url = new ForwardResolution(ComponentActionBean.class, "source") .addParameter("app", name) .addParameter("version", version) .addParameter("className", cc.getClassName()) .addParameter("file", f.getName()) .getUrl(context.getLocale()); sb.append(" <script type=\"text/javascript\" src=\""); sb.append(HtmlUtil.encode(context.getServletContext().getContextPath() + url)); sb.append("\"></script>\n"); } } } } } else { // If not debugging, create a single script tag with all source // for all components for the application for a minimal number of HTTP requests // The ComponentActionBean supports conditional HTTP requests using // Last-Modified. // Create a hash value that will change when the classNames used // in the application change, so that a browser will not use a // previous version from cache with other contents. int hash = 0; Set<String> classNamesDone = new HashSet<String>(); for (ConfiguredComponent cc : comps) { if (!Authorizations.isConfiguredComponentAuthorized(cc, context.getRequest(), em)) { continue; } if(!classNamesDone.contains(cc.getClassName())) { hash = hash ^ cc.getClassName().hashCode(); } else { classNamesDone.add(cc.getClassName()); } } if(user != null) { // Update component sources when roles of user change hash = hash ^ getRolesCachekey(context.getRequest(), em); // Update component sources when roles of configured components // may have changed hash = hash ^ (int)application.getAuthorizationsModified().getTime(); } String url = new ForwardResolution(ComponentActionBean.class, "source") .addParameter("app", name) .addParameter("version", version) .addParameter("minified", true) .addParameter("hash", hash) .getUrl(context.getLocale()); sb.append(" <script type=\"text/javascript\" src=\""); sb.append(HtmlUtil.encode(context.getServletContext().getContextPath() + url)); sb.append("\"></script>\n"); } componentSourceHTML = sb.toString(); } private String retrieveViewerType (){ String type = "openlayers"; String typePrefix = "viewer.mapcomponents"; Set<ConfiguredComponent> components = application.getComponents(); for (ConfiguredComponent component : components) { String className = component.getClassName(); if(className.startsWith(typePrefix)){ type = className.substring(typePrefix.length() +1).toLowerCase().replace("map", ""); break; } } return type; } private void getDefaultViewer(){ EntityManager em = Stripersist.getEntityManager(); try { Metadata md = em.createQuery("from Metadata where configKey = :key", Metadata.class).setParameter("key", Metadata.DEFAULT_APPLICATION).getSingleResult(); String appId = md.getConfigValue(); Long id = Long.parseLong(appId); Application app = em.find(Application.class, id); name = app.getName(); version = app.getVersion(); } catch (NoResultException | NullPointerException e) { name = "default"; version = null; } } }
viewer/src/main/java/nl/b3p/viewer/stripes/ApplicationActionBean.java
/* * Copyright (C) 2011-2016 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 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 nl.b3p.viewer.stripes; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.util.HtmlUtil; import net.sourceforge.stripes.util.StringUtil; import net.sourceforge.stripes.validation.LocalizableError; import net.sourceforge.stripes.validation.SimpleError; import net.sourceforge.stripes.validation.Validate; import nl.b3p.i18n.ResourceBundleProvider; import nl.b3p.viewer.components.ComponentRegistry; import nl.b3p.viewer.components.ComponentRegistryInitializer; import nl.b3p.viewer.config.ClobElement; import nl.b3p.viewer.config.app.Application; import nl.b3p.viewer.config.app.ConfiguredComponent; import nl.b3p.viewer.config.metadata.Metadata; import nl.b3p.viewer.config.security.Authorizations; import nl.b3p.viewer.config.security.User; import nl.b3p.viewer.util.SelectedContentCache; import org.apache.commons.lang.StringUtils; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.security.Principal; import java.util.*; /** * * @author Matthijs Laan */ @UrlBinding("/app/{name}/v{version}") @StrictBinding public class ApplicationActionBean extends LocalizableApplicationActionBean implements ActionBean { private ActionBeanContext context; @Validate private String name; @Validate private boolean unknown; @Validate private String version; // <editor-fold desc="bookmark variables" defaultstate="collapsed"> @Validate private String bookmark; @Validate private String extent; @Validate private String layers; @Validate private String levelOrder; // </editor-fold> @Validate private boolean debug; @Validate(on = "retrieveAppConfigJSON") private Application application; private String componentSourceHTML; private String appConfigJSON; private String viewerType; private String title; private String language; private JSONObject user; private String loginUrl; private HashMap<String,Object> globalLayout; //<editor-fold defaultstate="collapsed" desc="getters en setters"> public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } public Application getApplication() { return application; } public void setApplication(Application application) { this.application = application; } public void setContext(ActionBeanContext context) { this.context = context; } public ActionBeanContext getContext() { return context; } public String getComponentSourceHTML() { return componentSourceHTML; } public void setComponentSourceHTML(String componentSourceHTML) { this.componentSourceHTML = componentSourceHTML; } public String getAppConfigJSON() { return appConfigJSON; } public void setAppConfigJSON(String appConfigJSON) { this.appConfigJSON = appConfigJSON; } public String getViewerType(){ return viewerType; } public void setViewerType(String viewerType){ this.viewerType = viewerType; } public String getTitle(){ return title; } public void setTitle(String title){ this.title = title; } public String getLanguage(){ return language; } public void setLanguage(String language){ this.language = language; } public JSONObject getUser() { return user; } public void setUser(JSONObject user) { this.user = user; } public String getLoginUrl() { return loginUrl; } public void setLoginUrl(String loginUrl) { this.loginUrl = loginUrl; } public HashMap getGlobalLayout() { return globalLayout; } public void setGlobalLayout(HashMap globalLayout) { this.globalLayout = globalLayout; } public boolean isUnknown() { return unknown; } public void setUnknown(boolean unknown) { this.unknown = unknown; } public String getBookmark() { return bookmark; } public void setBookmark(String bookmark) { this.bookmark = bookmark; } public String getExtent() { return extent; } public void setExtent(String extent) { this.extent = extent; } public String getLayers() { return layers; } public void setLayers(String layers) { this.layers = layers; } public String getLevelOrder() { return levelOrder; } public void setLevelOrder(String levelOrder) { this.levelOrder = levelOrder; } //</editor-fold> static Application findApplication(String name, String version) { EntityManager em = Stripersist.getEntityManager(); if(name != null) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery q = cb.createQuery(Application.class); Root<Application> root = q.from(Application.class); Predicate namePredicate = cb.equal(root.get("name"), name); Predicate versionPredicate = version != null ? cb.equal(root.get("version"), version) : cb.isNull(root.get("version")); q.where(cb.and(namePredicate, versionPredicate)); try { return (Application) em.createQuery(q).getSingleResult(); } catch(NoResultException nre) { String decodedName = StringUtil.urlDecode(name); if(!decodedName.equals(name)){ return findApplication(decodedName, version); } } } return null; } public Resolution saveCache() throws JSONException, IOException{ Resolution view = view(); EntityManager em = Stripersist.getEntityManager(); Resolution r = checkRestriction(context, application, em); if (r != null) { return r; } SelectedContentCache cache = new SelectedContentCache(); JSONObject sc = cache.createSelectedContent(application, false,false, false,em); application.getDetails().put("selected_content_cache", new ClobElement(sc.toString())); em.getTransaction().commit(); return view; } public Resolution retrieveCache() throws JSONException, IOException{ Resolution view = view(); EntityManager em = Stripersist.getEntityManager(); Resolution r = checkRestriction(context, application, em); if (r != null) { return r; } ClobElement el = application.getDetails().get("selected_content_cache"); appConfigJSON = el.getValue(); return view; } public Resolution retrieveAppConfigJSON() throws IOException { EntityManager em = Stripersist.getEntityManager(); JSONObject response = new JSONObject(); response.put("success", false); JSONObject obj = application.toJSON(context.getRequest(), false, false, em); JSONObject details = obj.optJSONObject("details"); if (details != null) { details.remove(SelectedContentCache.DETAIL_CACHED_EXPANDED_SELECTED_CONTENT); details.remove(SelectedContentCache.DETAIL_CACHED_SELECTED_CONTENT); } appConfigJSON = obj.toString(); response.put("config", appConfigJSON); response.put("success", true); return new StreamingResolution("application/json", new StringReader(response.toString())); } @DefaultHandler public Resolution view() throws JSONException, IOException { if(unknown){ getDefaultViewer(); /* Redirected here from /index.jsp: further redirect to app with * name and version parameters of default app in URL and * unknown=false. This makes sure that links in URL always include * the app name. Required for compact bookmark links for default app * to work. */ return new RedirectResolution(ApplicationActionBean.class) .addParameter("name", name) .addParameter("version", version) .addParameter("debug", debug); } application = findApplication(name, version); if(application == null) { getContext().getValidationErrors().addGlobalError(new LocalizableError("app.notfound", name + (version != null ? " v" + version : ""))); return new ForwardResolution("/WEB-INF/jsp/error.jsp"); } RedirectResolution login = new RedirectResolution(ApplicationActionBean.class) .addParameter("name", name) // binded parameters not included ? .addParameter("version", version) .addParameter("debug", debug) .addParameter("uitloggen", true) .includeRequestParameters(true); addBookmarkParameters(login); loginUrl = login.getUrl(context.getLocale()); String username = context.getRequest().getRemoteUser(); if(application.isAuthenticatedRequired() && username == null) { return login; } EntityManager em = Stripersist.getEntityManager(); Resolution r = checkRestriction(context, application, em); if(r != null){ return r; } if(username != null) { user = new JSONObject(); user.put("name", username); JSONObject roles = new JSONObject(); user.put("roles", roles); for(String role: Authorizations.getRoles(context.getRequest(),em)) { roles.put(role, Boolean.TRUE); } } buildComponentSourceHTML(em); appConfigJSON = application.toJSON(context.getRequest(),false, false,em).toString(); this.viewerType = retrieveViewerType(); if(StringUtils.isBlank(title)) { this.title = application.getName(); } this.language = application.getLang(); if(StringUtils.isBlank(language)) { this.language = "nl_NL"; } //make hashmap for jsonobject. this.globalLayout = new HashMap<String,Object>(); JSONObject layout = application.getGlobalLayout(); Iterator<String> keys = layout.keys(); while (keys.hasNext()){ String key = keys.next(); this.globalLayout.put(key, layout.get(key)); } context.getResponse().addHeader("X-UA-Compatible", "IE=edge"); return new ForwardResolution("/WEB-INF/jsp/app.jsp"); } public static Resolution checkRestriction(ActionBeanContext context, Application application, EntityManager em){ String username = context.getRequest().getRemoteUser(); User u = null; if(username != null){ Principal p = context.getRequest().getUserPrincipal(); if( p instanceof User){ u = (User)p; }else{ u = em.find(User.class, p.getName()); } } if(Authorizations.isUserExpired(u, context)){ ResourceBundle bundle = ResourceBundleProvider.getResourceBundle(determineLocaleForBundle(context, application)); String msg = bundle.getString("viewer.applicationactionbean.expired"); context.getValidationErrors().addGlobalError(new SimpleError(msg)); context.getRequest().getSession().invalidate(); return new ForwardResolution("/WEB-INF/jsp/error.jsp"); } else if (!Authorizations.isApplicationReadAuthorized(application, context.getRequest(), em) && (username == null || u != null && u.isAuthenticatedByIp())) { RedirectResolution login = new RedirectResolution(LoginActionBean.class) .addParameter("name", application.getName()) // binded parameters not included ? .addParameter("version", application.getVersion()) .includeRequestParameters(true); context.getRequest().getSession().invalidate(); return login; } else if (!Authorizations.isApplicationReadAuthorized(application, context.getRequest(), em) && username != null) { ResourceBundle bundle = ResourceBundleProvider.getResourceBundle(determineLocaleForBundle(context, application)); String msg = bundle.getString("viewer.applicationactionbean.norights"); context.getValidationErrors().addGlobalError(new SimpleError(msg)); context.getRequest().getSession().invalidate(); return new ForwardResolution("/WEB-INF/jsp/error_retry.jsp"); } return null; } /** * Build a hash key to make the single component source for all components * cacheable but updateable when the roles of the user change. This is not * meant to be a secure hash, the roles of a user are not secret. * * @param request servlet request with user credential * @param em the entitymanahger to use for database access * @return a key to use as a cache identifyer */ public static int getRolesCachekey(HttpServletRequest request, EntityManager em) { Set<String> roles = Authorizations.getRoles(request, em); if(roles.isEmpty()) { return 0; } List<String> sorted = new ArrayList<String>(roles); Collections.sort(sorted); int hash = 0; for(String role: sorted) { hash = hash ^ role.hashCode(); } return hash; } public Resolution uitloggen(){ application = findApplication(name, version); context.getRequest().getSession().invalidate(); if("true".equals(context.getRequest().getParameter("logout")) && "true".equals(context.getRequest().getParameter("returnAfterLogout"))) { RedirectResolution r = new RedirectResolution(ApplicationActionBean.class) .addParameter("name", application.getName()) .addParameter("version", application.getVersion()); addBookmarkParameters(r); return r; } else { RedirectResolution r = new RedirectResolution(LoginActionBean.class) .addParameter("name", application.getName()) .addParameter("version", application.getVersion()); addBookmarkParameters(r); return r; } } private void addBookmarkParameters(RedirectResolution r) { if (bookmark != null) { r.addParameter("bookmark", bookmark); } if(extent != null){ r.addParameter("extent", extent); } if(layers != null){ r.addParameter("layers", layers); } if(levelOrder != null){ r.addParameter("levelOrder", levelOrder); } } private void buildComponentSourceHTML(EntityManager em) throws IOException { StringBuilder sb = new StringBuilder(); // Sort components by classNames, so order is always the same for debugging ComponentRegistry cr = ComponentRegistryInitializer.getInstance(); List<ConfiguredComponent> comps = new ArrayList<ConfiguredComponent>(application.getComponents()); Collections.sort(comps); if(isDebug()) { Set<String> classNamesDone = new HashSet<String>(); for(ConfiguredComponent cc: comps) { if(!Authorizations.isConfiguredComponentAuthorized(cc, context.getRequest(), em)) { continue; } if(!classNamesDone.contains(cc.getClassName())) { classNamesDone.add(cc.getClassName()); if(cc.getViewerComponent() != null && cc.getViewerComponent().getSources() != null) { for(File f: cc.getViewerComponent().getSources()) { String url = new ForwardResolution(ComponentActionBean.class, "source") .addParameter("app", name) .addParameter("version", version) .addParameter("className", cc.getClassName()) .addParameter("file", f.getName()) .getUrl(context.getLocale()); sb.append(" <script type=\"text/javascript\" src=\""); sb.append(HtmlUtil.encode(context.getServletContext().getContextPath() + url)); sb.append("\"></script>\n"); } } } } } else { // If not debugging, create a single script tag with all source // for all components for the application for a minimal number of HTTP requests // The ComponentActionBean supports conditional HTTP requests using // Last-Modified. // Create a hash value that will change when the classNames used // in the application change, so that a browser will not use a // previous version from cache with other contents. int hash = 0; Set<String> classNamesDone = new HashSet<String>(); for (ConfiguredComponent cc : comps) { if (!Authorizations.isConfiguredComponentAuthorized(cc, context.getRequest(), em)) { continue; } if(!classNamesDone.contains(cc.getClassName())) { hash = hash ^ cc.getClassName().hashCode(); } else { classNamesDone.add(cc.getClassName()); } } if(user != null) { // Update component sources when roles of user change hash = hash ^ getRolesCachekey(context.getRequest(), em); // Update component sources when roles of configured components // may have changed hash = hash ^ (int)application.getAuthorizationsModified().getTime(); } String url = new ForwardResolution(ComponentActionBean.class, "source") .addParameter("app", name) .addParameter("version", version) .addParameter("minified", true) .addParameter("hash", hash) .getUrl(context.getLocale()); sb.append(" <script type=\"text/javascript\" src=\""); sb.append(HtmlUtil.encode(context.getServletContext().getContextPath() + url)); sb.append("\"></script>\n"); } componentSourceHTML = sb.toString(); } private String retrieveViewerType (){ String type = "openlayers"; String typePrefix = "viewer.mapcomponents"; Set<ConfiguredComponent> components = application.getComponents(); for (ConfiguredComponent component : components) { String className = component.getClassName(); if(className.startsWith(typePrefix)){ type = className.substring(typePrefix.length() +1).toLowerCase().replace("map", ""); break; } } return type; } private void getDefaultViewer(){ EntityManager em = Stripersist.getEntityManager(); try { Metadata md = em.createQuery("from Metadata where configKey = :key", Metadata.class).setParameter("key", Metadata.DEFAULT_APPLICATION).getSingleResult(); String appId = md.getConfigValue(); Long id = Long.parseLong(appId); Application app = em.find(Application.class, id); name = app.getName(); version = app.getVersion(); } catch (NoResultException | NullPointerException e) { name = "default"; version = null; } } }
fix xss in ApplicationActionBean (#1881)
viewer/src/main/java/nl/b3p/viewer/stripes/ApplicationActionBean.java
fix xss in ApplicationActionBean (#1881)
<ide><path>iewer/src/main/java/nl/b3p/viewer/stripes/ApplicationActionBean.java <ide> application = findApplication(name, version); <ide> <ide> if(application == null) { <del> getContext().getValidationErrors().addGlobalError(new LocalizableError("app.notfound", name + (version != null ? " v" + version : ""))); <add> getContext().getValidationErrors().addGlobalError(new LocalizableError("app.notfound", HtmlUtil.encode(name + (version != null ? " v" + version : "")))); <ide> return new ForwardResolution("/WEB-INF/jsp/error.jsp"); <ide> } <ide>
Java
apache-2.0
63c513ad827e08ce8e3ad56e39fe3851fd5ebe5b
0
petr-ujezdsky/versions-maven-plugin-1,tomerc/versions-maven-plugin,mojohaus/versions-maven-plugin,prostagma/versions-maven-plugin,mohanaraosv/versions-maven-plugin,bcalmac/branch-maven-plugin,petr-ujezdsky/versions-maven-plugin,mojohaus/versions-maven-plugin,HelloWallet/versions-maven-plugin
package org.codehaus.mojo.versions; /* * 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 org.apache.maven.BuildFailureException; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException; 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.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.RuntimeInformation; import org.apache.maven.lifecycle.Lifecycle; import org.apache.maven.lifecycle.LifecycleExecutionException; import org.apache.maven.lifecycle.LifecycleExecutor; import org.apache.maven.lifecycle.mapping.LifecycleMapping; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.model.Prerequisites; import org.apache.maven.model.Profile; import org.apache.maven.model.ReportPlugin; import org.apache.maven.model.io.xpp3.MavenXpp3Writer; import org.apache.maven.plugin.InvalidPluginException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.PluginManager; import org.apache.maven.plugin.PluginManagerException; import org.apache.maven.plugin.PluginNotFoundException; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.plugin.version.PluginVersionNotFoundException; import org.apache.maven.plugin.version.PluginVersionResolutionException; import org.apache.maven.project.DefaultProjectBuilderConfiguration; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.interpolation.ModelInterpolationException; import org.apache.maven.project.interpolation.ModelInterpolator; import org.apache.maven.settings.Settings; import org.codehaus.mojo.versions.api.ArtifactVersions; import org.codehaus.mojo.versions.api.PomHelper; import org.codehaus.mojo.versions.ordering.MavenVersionComparator; import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; import org.codehaus.mojo.versions.utils.PluginComparator; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.StringUtils; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import java.io.IOException; import java.io.Reader; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Pattern; /** * Displays all plugins that have newer versions available. * * @author Stephen Connolly * @goal display-plugin-updates * @requiresProject true * @requiresDirectInvocation false * @since 1.0-alpha-1 */ public class DisplayPluginUpdatesMojo extends AbstractVersionsUpdaterMojo { // ------------------------------ FIELDS ------------------------------ /** * The width to pad warn messages. * * @since 1.0-alpha-1 */ private static final int WARN_PAD_SIZE = 65; /** * The width to pad info messages. * * @since 1.0-alpha-1 */ private static final int INFO_PAD_SIZE = 68; /** * String to flag a plugin version being forced by the super-pom. * * @since 1.0-alpha-1 */ private static final String FROM_SUPER_POM = "(from super-pom) "; /** * @component * @since 1.0-alpha-1 */ private LifecycleExecutor lifecycleExecutor; /** * @component * @since 1.0-alpha-3 */ private ModelInterpolator modelInterpolator; /** * The plugin manager. * * @component * @since 1.0-alpha-1 */ private PluginManager pluginManager; /** * @component * @since 1.3 */ private RuntimeInformation runtimeInformation; // --------------------- GETTER / SETTER METHODS --------------------- /** * Returns the pluginManagement section of the super-pom. * * @return Returns the pluginManagement section of the super-pom. * @throws MojoExecutionException when things go wrong. */ private Map<String, String> getSuperPomPluginManagement() throws MojoExecutionException { if ( new DefaultArtifactVersion( "3.0" ).compareTo( runtimeInformation.getApplicationVersion() ) <= 0 ) { getLog().debug( "Using Maven 3.x strategy to determine superpom defined plugins" ); try { Method getPluginsBoundByDefaultToAllLifecycles = LifecycleExecutor.class.getMethod( "getPluginsBoundByDefaultToAllLifecycles", new Class[]{ String.class } ); Set<Plugin> plugins = (Set<Plugin>) getPluginsBoundByDefaultToAllLifecycles.invoke( lifecycleExecutor, new Object[]{ getProject().getPackaging() } ); // we need to provide a copy with the version blanked out so that inferring from super-pom // works as for 2.x as 3.x fills in the version on us! Map<String, String> result = new LinkedHashMap<String, String>( plugins.size() ); for ( Plugin plugin : plugins ) { result.put( getPluginCoords( plugin ), getPluginVersion( plugin ) ); } URL superPom = getClass().getClassLoader().getResource( "org/apache/maven/model/pom-4.0.0.xml" ); if ( superPom != null ) { try { Reader reader = ReaderFactory.newXmlReader( superPom ); try { StringBuilder buf = new StringBuilder( IOUtil.toString( reader ) ); ModifiedPomXMLEventReader pom = newModifiedPomXER( buf ); Pattern pathRegex = Pattern.compile( "/project(/profiles/profile)?" + "((/build(/pluginManagement)?)|(/reporting))" + "/plugins/plugin" ); Stack<StackState> pathStack = new Stack<StackState>(); StackState curState = null; while ( pom.hasNext() ) { XMLEvent event = pom.nextEvent(); if ( event.isStartDocument() ) { curState = new StackState( "" ); pathStack.clear(); } else if ( event.isStartElement() ) { String elementName = event.asStartElement().getName().getLocalPart(); if ( curState != null && pathRegex.matcher( curState.path ).matches() ) { if ( "groupId".equals( elementName ) ) { curState.groupId = pom.getElementText().trim(); continue; } else if ( "artifactId".equals( elementName ) ) { curState.artifactId = pom.getElementText().trim(); continue; } else if ( "version".equals( elementName ) ) { curState.version = pom.getElementText().trim(); continue; } } pathStack.push( curState ); curState = new StackState( curState.path + "/" + elementName ); } else if ( event.isEndElement() ) { if ( curState != null && pathRegex.matcher( curState.path ).matches() ) { if ( curState.artifactId != null ) { Plugin plugin = new Plugin(); plugin.setArtifactId( curState.artifactId ); plugin.setGroupId( curState.groupId == null ? PomHelper.APACHE_MAVEN_PLUGINS_GROUPID : curState.groupId ); plugin.setVersion( curState.version ); if ( !result.containsKey( getPluginCoords( plugin ) ) ) { result.put( getPluginCoords( plugin ), getPluginVersion( plugin ) ); } } } curState = pathStack.pop(); } } } finally { IOUtil.close( reader ); } } catch ( IOException e ) { // ignore } catch ( XMLStreamException e ) { // ignore } } return result; } catch ( NoSuchMethodException e1 ) { // no much we can do here } catch ( InvocationTargetException e1 ) { // no much we can do here } catch ( IllegalAccessException e1 ) { // no much we can do here } } getLog().debug( "Using Maven 2.x strategy to determine superpom defined plugins" ); Map<String, String> superPomPluginManagement = new HashMap(); try { MavenProject superProject = projectBuilder.buildStandaloneSuperProject( new DefaultProjectBuilderConfiguration() ); superPomPluginManagement.putAll( getPluginManagement( superProject.getOriginalModel() ) ); } catch ( ProjectBuildingException e ) { throw new MojoExecutionException( "Could not determine the super pom.xml", e ); } return superPomPluginManagement; } /** * Gets the plugin management plugins of a specific project. * * @param model the model to get the plugin management plugins from. * @return The map of effective plugin versions keyed by coordinates. * @since 1.0-alpha-1 */ private Map<String, String> getPluginManagement( Model model ) { // we want only those parts of pluginManagement that are defined in this project Map<String, String> pluginManagement = new HashMap<String, String>(); try { for ( Plugin plugin : model.getBuild().getPluginManagement().getPlugins() ) { String coord = getPluginCoords( plugin ); String version = getPluginVersion( plugin ); if ( version != null ) { pluginManagement.put( coord, version ); } } } catch ( NullPointerException e ) { // guess there are no plugins here } try { for ( Profile profile : model.getProfiles() ) { try { for ( Plugin plugin : profile.getBuild().getPluginManagement().getPlugins() ) { String coord = getPluginCoords( plugin ); String version = getPluginVersion( plugin ); if ( version != null ) { pluginManagement.put( coord, version ); } } } catch ( NullPointerException e ) { // guess there are no plugins here } } } catch ( NullPointerException e ) { // guess there are no profiles here } return pluginManagement; } // ------------------------ INTERFACE METHODS ------------------------ // --------------------- Interface Mojo --------------------- /** * @throws MojoExecutionException when things go wrong * @throws MojoFailureException when things go wrong in a very bad way * @see AbstractVersionsUpdaterMojo#execute() * @since 1.0-alpha-1 */ public void execute() throws MojoExecutionException, MojoFailureException { Set<String> pluginsWithVersionsSpecified; try { pluginsWithVersionsSpecified = findPluginsWithVersionsSpecified( getProject() ); } catch ( XMLStreamException e ) { throw new MojoExecutionException( e.getMessage(), e ); } catch ( IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } Map<String, String> superPomPluginManagement = getSuperPomPluginManagement(); getLog().debug( "superPom plugins = " + superPomPluginManagement ); Map<String, String> parentPluginManagement = new HashMap<String, String>(); Map<String, String> parentBuildPlugins = new HashMap<String, String>(); Map<String, String> parentReportPlugins = new HashMap<String, String>(); List<MavenProject> parents = getParentProjects( getProject() ); for ( MavenProject parentProject : parents ) { getLog().debug( "Processing parent: " + parentProject.getGroupId() + ":" + parentProject.getArtifactId() + ":" + parentProject.getVersion() + " -> " + parentProject.getFile() ); StringWriter writer = new StringWriter(); boolean havePom = false; Model interpolatedModel; try { Model originalModel = parentProject.getOriginalModel(); if ( originalModel == null ) { getLog().warn( "project.getOriginalModel()==null for " + parentProject.getGroupId() + ":" + parentProject.getArtifactId() + ":" + parentProject.getVersion() + " is null, substituting project.getModel()" ); originalModel = parentProject.getModel(); } try { new MavenXpp3Writer().write( writer, originalModel ); writer.close(); havePom = true; } catch ( IOException e ) { // ignore } interpolatedModel = modelInterpolator.interpolate( originalModel, null, new DefaultProjectBuilderConfiguration().setExecutionProperties( getProject().getProperties() ), false ); } catch ( ModelInterpolationException e ) { throw new MojoExecutionException( e.getMessage(), e ); } if ( havePom ) { try { Set<String> withVersionSpecified = findPluginsWithVersionsSpecified( new StringBuilder( writer.toString() ) ); Map<String, String> map = getPluginManagement( interpolatedModel ); map.keySet().retainAll( withVersionSpecified ); parentPluginManagement.putAll( map ); map = getBuildPlugins( interpolatedModel, true ); map.keySet().retainAll( withVersionSpecified ); parentPluginManagement.putAll( map ); map = getReportPlugins( interpolatedModel, true ); map.keySet().retainAll( withVersionSpecified ); parentPluginManagement.putAll( map ); } catch ( IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } catch ( XMLStreamException e ) { throw new MojoExecutionException( e.getMessage(), e ); } } else { parentPluginManagement.putAll( getPluginManagement( interpolatedModel ) ); parentPluginManagement.putAll( getBuildPlugins( interpolatedModel, true ) ); parentPluginManagement.putAll( getReportPlugins( interpolatedModel, true ) ); } } Set<Plugin> plugins = getProjectPlugins( superPomPluginManagement, parentPluginManagement, parentBuildPlugins, parentReportPlugins, pluginsWithVersionsSpecified ); List<String> updates = new ArrayList<String>(); List<String> lockdowns = new ArrayList<String>(); Map<ArtifactVersion, Map<String, String>> upgrades = new TreeMap<ArtifactVersion, Map<String, String>>( new MavenVersionComparator() ); ArtifactVersion curMavenVersion = runtimeInformation.getApplicationVersion(); ArtifactVersion specMavenVersion = new DefaultArtifactVersion( getRequiredMavenVersion( getProject(), "2.0" ) ); ArtifactVersion minMavenVersion = null; boolean superPomDrivingMinVersion = false; Iterator<Plugin> i = plugins.iterator(); while ( i.hasNext() ) { Object plugin = i.next(); String groupId = getPluginGroupId( plugin ); String artifactId = getPluginArtifactId( plugin ); String version = getPluginVersion( plugin ); String coords = ArtifactUtils.versionlessKey( groupId, artifactId ); if ( version == null ) { version = parentPluginManagement.get( coords ); } getLog().debug( new StringBuilder().append( "Checking " ).append( coords ).append( " for updates newer than " ).append( version ).toString() ); String effectiveVersion = version; VersionRange versionRange; boolean unspecified = version == null; try { versionRange = unspecified ? VersionRange.createFromVersionSpec( "[0,)" ) : VersionRange.createFromVersionSpec( version ); } catch ( InvalidVersionSpecificationException e ) { throw new MojoExecutionException( "Invalid version range specification: " + version, e ); } Artifact artifact = artifactFactory.createPluginArtifact( groupId, artifactId, versionRange ); ArtifactVersion artifactVersion = null; try { // now we want to find the newest version that is compatible with the invoking version of Maven ArtifactVersions artifactVersions = getHelper().lookupArtifactVersions( artifact, true ); ArtifactVersion[] newerVersions = artifactVersions.getVersions( Boolean.TRUE.equals( this.allowSnapshots ) ); ArtifactVersion minRequires = null; for ( int j = newerVersions.length - 1; j >= 0; j-- ) { Artifact probe = artifactFactory.createDependencyArtifact( groupId, artifactId, VersionRange.createFromVersion( newerVersions[j].toString() ), "pom", null, "runtime" ); try { getHelper().resolveArtifact( probe, true ); MavenProject mavenProject = projectBuilder.buildFromRepository( probe, remotePluginRepositories, localRepository ); ArtifactVersion requires = new DefaultArtifactVersion( getRequiredMavenVersion( mavenProject, "2.0" ) ); if ( specMavenVersion.compareTo( requires ) >= 0 && artifactVersion == null ) { artifactVersion = newerVersions[j]; } if ( effectiveVersion == null && curMavenVersion.compareTo( requires ) >= 0 ) { // version was unspecified, current version of maven thinks it should use this effectiveVersion = newerVersions[j].toString(); } if ( artifactVersion != null && effectiveVersion != null ) { // no need to look at any older versions. break; } if ( minRequires == null || minRequires.compareTo( requires ) > 0 ) { Map<String, String> upgradePlugins = upgrades.get( requires ); if ( upgradePlugins == null ) { upgrades.put( requires, upgradePlugins = new LinkedHashMap<String, String>() ); } String upgradePluginKey = compactKey( groupId, artifactId ); if ( !upgradePlugins.containsKey( upgradePluginKey ) ) { upgradePlugins.put( upgradePluginKey, newerVersions[j].toString() ); } minRequires = requires; } } catch ( ArtifactResolutionException e ) { // ignore bad version } catch ( ArtifactNotFoundException e ) { // ignore bad version } catch ( ProjectBuildingException e ) { // ignore bad version } } if ( effectiveVersion != null ) { VersionRange currentVersionRange = VersionRange.createFromVersion( effectiveVersion ); Artifact probe = artifactFactory.createDependencyArtifact( groupId, artifactId, currentVersionRange, "pom", null, "runtime" ); try { getHelper().resolveArtifact( probe, true ); MavenProject mavenProject = projectBuilder.buildFromRepository( probe, remotePluginRepositories, localRepository ); ArtifactVersion requires = new DefaultArtifactVersion( getRequiredMavenVersion( mavenProject, "2.0" ) ); if ( minMavenVersion == null || minMavenVersion.compareTo( requires ) < 0 ) { minMavenVersion = requires; } } catch ( ArtifactResolutionException e ) { // ignore bad version } catch ( ArtifactNotFoundException e ) { // ignore bad version } catch ( ProjectBuildingException e ) { // ignore bad version } } } catch ( ArtifactMetadataRetrievalException e ) { throw new MojoExecutionException( e.getMessage(), e ); } String newVersion; if ( version == null && pluginsWithVersionsSpecified.contains( coords ) ) { // Hack ALERT! // // All this should be re-written in a less "pom is xml" way... but it'll // work for now :-( // // we have removed the version information, as it was the same as from // the super-pom... but it actually was specified. version = artifactVersion != null ? artifactVersion.toString() : null; } getLog().debug( "[" + coords + "].version=" + version ); getLog().debug( "[" + coords + "].artifactVersion=" + artifactVersion ); getLog().debug( "[" + coords + "].effectiveVersion=" + effectiveVersion ); getLog().debug( "[" + coords + "].specified=" + pluginsWithVersionsSpecified.contains( coords ) ); if ( version == null || !pluginsWithVersionsSpecified.contains( coords ) ) { version = (String) superPomPluginManagement.get( ArtifactUtils.versionlessKey( artifact ) ); Boolean fromSuperPom = (version != null); getLog().debug( "[" + coords + "].superPom.version=" + version ); newVersion = artifactVersion != null ? artifactVersion.toString() : ( fromSuperPom ? version : ( effectiveVersion != null ? effectiveVersion : "(unknown)" ) ); if ( fromSuperPom || "(unknown)".equals(newVersion) ) { StringBuilder buf = new StringBuilder( compactKey( groupId, artifactId ) ); buf.append( ' ' ); int padding = WARN_PAD_SIZE - effectiveVersion.length() - ( fromSuperPom ? FROM_SUPER_POM.length() : 0 ); while ( buf.length() < padding ) { buf.append( '.' ); } buf.append( ' ' ); if ( fromSuperPom ) { buf.append( FROM_SUPER_POM ); superPomDrivingMinVersion = true; } buf.append( effectiveVersion ); lockdowns.add( buf.toString() ); } } else if ( artifactVersion != null ) { newVersion = artifactVersion.toString(); } else { newVersion = null; } if ( version != null && artifactVersion != null && newVersion != null && new DefaultArtifactVersion( effectiveVersion ).compareTo( new DefaultArtifactVersion( newVersion ) ) < 0 ) { StringBuilder buf = new StringBuilder( compactKey( groupId, artifactId ) ); buf.append( ' ' ); int padding = INFO_PAD_SIZE - version.length() - newVersion.length() - 4; while ( buf.length() < padding ) { buf.append( '.' ); } buf.append( ' ' ); buf.append( effectiveVersion ); buf.append( " -> " ); buf.append( newVersion ); updates.add( buf.toString() ); } } getLog().info( "" ); if ( updates.isEmpty() ) { getLog().info( "All plugins with a version specified are using the latest versions." ); } else { getLog().info( "The following plugin updates are available:" ); for ( String update : updates ) { getLog().info( " " + update ); } } getLog().info( "" ); if ( lockdowns.isEmpty() ) { getLog().info( "All plugins have a version specified." ); } else { getLog().warn( "The following plugins do not have their version specified:" ); for ( String lockdown : lockdowns ) { getLog().warn( " " + lockdown ); } } getLog().info( "" ); boolean noMavenMinVersion = getRequiredMavenVersion( getProject(), null ) == null; boolean noExplicitMavenMinVersion = getProject().getPrerequisites() == null || getProject().getPrerequisites().getMaven() == null; if ( noMavenMinVersion ) { getLog().warn( "Project does not define minimum Maven version, default is: 2.0" ); } else if ( noExplicitMavenMinVersion ) { getLog().info( "Project inherits minimum Maven version as: " + specMavenVersion ); } else { ArtifactVersion explicitMavenVersion = new DefaultArtifactVersion( getProject().getPrerequisites().getMaven() ); if ( explicitMavenVersion.compareTo( specMavenVersion ) < 0 ) { getLog().error( "Project's effective minimum Maven (from parent) is: " + specMavenVersion ); getLog().error( "Project defines minimum Maven version as: " + explicitMavenVersion ); } else { getLog().info( "Project defines minimum Maven version as: " + specMavenVersion ); } } getLog().info( "Plugins require minimum Maven version of: " + minMavenVersion ); if ( superPomDrivingMinVersion ) { getLog().info( "Note: the super-pom from Maven " + curMavenVersion + " defines some of the plugin" ); getLog().info( " versions and may be influencing the plugins required minimum Maven" ); getLog().info( " version." ); } getLog().info( "" ); if ( "maven-plugin".equals( getProject().getPackaging() ) ) { if ( noMavenMinVersion ) { getLog().warn( "Project (which is a Maven Plugin) does not define required minimum version of Maven." ); getLog().warn( "Update the pom.xml to contain" ); getLog().warn( " <prerequisites>" ); getLog().warn( " <maven><!-- minimum version of Maven that the plugin works with --></maven>" ); getLog().warn( " </prerequisites>" ); getLog().warn( "To build this plugin you need at least Maven " + minMavenVersion ); getLog().warn( "A Maven Enforcer rule can be used to enforce this if you have not already set one up" ); } else if ( minMavenVersion != null && specMavenVersion.compareTo( minMavenVersion ) < 0 ) { getLog().warn( "Project (which is a Maven Plugin) targets Maven " + specMavenVersion + " or newer" ); getLog().warn( "but requires Maven " + minMavenVersion + " or newer to build." ); getLog().warn( "This may or may not be a problem. A Maven Enforcer rule can help " ); getLog().warn( "enforce that the correct version of Maven is used to build this plugin." ); } else { getLog().info( "No plugins require a newer version of Maven than specified by the pom." ); } } else { if ( noMavenMinVersion ) { getLog().error( "Project does not define required minimum version of Maven." ); getLog().error( "Update the pom.xml to contain" ); getLog().error( " <prerequisites>" ); getLog().error( " <maven>" + minMavenVersion + "</maven>" ); getLog().error( " </prerequisites>" ); } else if ( minMavenVersion != null && specMavenVersion.compareTo( minMavenVersion ) < 0 ) { getLog().error( "Project requires an incorrect minimum version of Maven." ); getLog().error( "Either change plugin versions to those compatible with " + specMavenVersion ); getLog().error( "or update the pom.xml to contain" ); getLog().error( " <prerequisites>" ); getLog().error( " <maven>" + minMavenVersion + "</maven>" ); getLog().error( " </prerequisites>" ); } else { getLog().info( "No plugins require a newer version of Maven than specified by the pom." ); } } for ( Map.Entry<ArtifactVersion, Map<String, String>> mavenUpgrade : upgrades.entrySet() ) { ArtifactVersion mavenUpgradeVersion = (ArtifactVersion) mavenUpgrade.getKey(); Map<String, String> upgradePlugins = mavenUpgrade.getValue(); if ( upgradePlugins.isEmpty() || specMavenVersion.compareTo( mavenUpgradeVersion ) >= 0 ) { continue; } getLog().info( "" ); getLog().info( "Require Maven " + mavenUpgradeVersion + " to use the following plugin updates:" ); for ( Map.Entry<String, String> entry : upgradePlugins.entrySet() ) { StringBuilder buf = new StringBuilder( " " ); buf.append( entry.getKey() ); buf.append( ' ' ); String s = entry.getValue(); int padding = INFO_PAD_SIZE - s.length() + 2; while ( buf.length() < padding ) { buf.append( '.' ); } buf.append( ' ' ); buf.append( s ); getLog().info( buf.toString() ); } } getLog().info( "" ); } private String compactKey( String groupId, String artifactId ) { if ( PomHelper.APACHE_MAVEN_PLUGINS_GROUPID.equals( groupId ) ) { // a core plugin... group id is not needed return artifactId; } return groupId + ":" + artifactId; } private String getRequiredMavenVersion( MavenProject mavenProject, String defaultValue ) { ArtifactVersion requiredMavenVersion = null; while ( mavenProject != null ) { final Prerequisites prerequisites = mavenProject.getPrerequisites(); final String mavenVersion = prerequisites == null ? null : prerequisites.getMaven(); if ( mavenVersion != null ) { final ArtifactVersion v = new DefaultArtifactVersion( mavenVersion ); if ( requiredMavenVersion == null || requiredMavenVersion.compareTo( v ) < 0 ) { requiredMavenVersion = v; } } mavenProject = mavenProject.getParent(); } return requiredMavenVersion == null ? defaultValue : requiredMavenVersion.toString(); } private static final class StackState { private final String path; private String groupId; private String artifactId; private String version; public StackState( String path ) { this.path = path; } public String toString() { return path + "[groupId=" + groupId + ", artifactId=" + artifactId + ", version=" + version + "]"; } } /** * Returns a set of Strings which correspond to the plugin coordinates where there is a version * specified. * * @param project The project to get the plugins with versions specified. * @return a set of Strings which correspond to the plugin coordinates where there is a version * specified. */ private Set<String> findPluginsWithVersionsSpecified( MavenProject project ) throws IOException, XMLStreamException { return findPluginsWithVersionsSpecified( PomHelper.readXmlFile( project.getFile() ) ); } /** * Returns a set of Strings which correspond to the plugin coordinates where there is a version * specified. * * @param pomContents The project to get the plugins with versions specified. * @return a set of Strings which correspond to the plugin coordinates where there is a version * specified. */ private Set<String> findPluginsWithVersionsSpecified( StringBuilder pomContents ) throws IOException, XMLStreamException { Set<String> result = new HashSet<String>(); ModifiedPomXMLEventReader pom = newModifiedPomXER( pomContents ); Pattern pathRegex = Pattern.compile( "/project(/profiles/profile)?" + "((/build(/pluginManagement)?)|(/reporting))" + "/plugins/plugin" ); Stack<StackState> pathStack = new Stack<StackState>(); StackState curState = null; while ( pom.hasNext() ) { XMLEvent event = pom.nextEvent(); if ( event.isStartDocument() ) { curState = new StackState( "" ); pathStack.clear(); } else if ( event.isStartElement() ) { String elementName = event.asStartElement().getName().getLocalPart(); if ( curState != null && pathRegex.matcher( curState.path ).matches() ) { if ( "groupId".equals( elementName ) ) { curState.groupId = pom.getElementText().trim(); continue; } else if ( "artifactId".equals( elementName ) ) { curState.artifactId = pom.getElementText().trim(); continue; } else if ( "version".equals( elementName ) ) { curState.version = pom.getElementText().trim(); continue; } } pathStack.push( curState ); curState = new StackState( curState.path + "/" + elementName ); } else if ( event.isEndElement() ) { if ( curState != null && pathRegex.matcher( curState.path ).matches() ) { if ( curState.artifactId != null && curState.version != null ) { if ( curState.groupId == null ) { curState.groupId = PomHelper.APACHE_MAVEN_PLUGINS_GROUPID; } result.add( curState.groupId + ":" + curState.artifactId ); } } curState = pathStack.pop(); } } return result; } // -------------------------- OTHER METHODS -------------------------- /** * Gets the build plugins of a specific project. * * @param model the model to get the build plugins from. * @param onlyIncludeInherited <code>true</code> to only return the plugins definitions that will be * inherited by child projects. * @return The map of effective plugin versions keyed by coordinates. * @since 1.0-alpha-1 */ private Map<String, String> getBuildPlugins( Model model, boolean onlyIncludeInherited ) { Map<String, String> buildPlugins = new HashMap(); try { for ( Plugin plugin : model.getBuild().getPlugins() ) { String coord = getPluginCoords( plugin ); String version = getPluginVersion( plugin ); if ( version != null && ( !onlyIncludeInherited || getPluginInherited( plugin ) ) ) { buildPlugins.put( coord, version ); } } } catch ( NullPointerException e ) { // guess there are no plugins here } try { for ( Profile profile : model.getProfiles() ) { try { for ( Plugin plugin : profile.getBuild().getPlugins() ) { String coord = getPluginCoords( plugin ); String version = getPluginVersion( plugin ); if ( version != null && ( !onlyIncludeInherited || getPluginInherited( plugin ) ) ) { buildPlugins.put( coord, version ); } } } catch ( NullPointerException e ) { // guess there are no plugins here } } } catch ( NullPointerException e ) { // guess there are no profiles here } return buildPlugins; } /** * Returns the Inherited of a {@link Plugin} or {@link ReportPlugin} * * @param plugin the {@link Plugin} or {@link ReportPlugin} * @return the Inherited of the {@link Plugin} or {@link ReportPlugin} * @since 1.0-alpha-1 */ private static boolean getPluginInherited( Object plugin ) { return "true".equalsIgnoreCase( plugin instanceof ReportPlugin ? ( (ReportPlugin) plugin ).getInherited() : ( (Plugin) plugin ).getInherited() ); } /** * Returns the lifecycle plugins of a specific project. * * @param project the project to get the lifecycle plugins from. * @return The map of effective plugin versions keyed by coordinates. * @throws org.apache.maven.plugin.MojoExecutionException * if things go wrong. * @since 1.0-alpha-1 */ private Map<String, Plugin> getLifecyclePlugins( MavenProject project ) throws MojoExecutionException { Map<String, Plugin> lifecyclePlugins = new HashMap<String, Plugin>(); try { Set<Plugin> plugins = getBoundPlugins( project, "clean,deploy,site" ); for ( Plugin plugin : plugins ) { lifecyclePlugins.put( getPluginCoords( plugin ), plugin ); } } catch ( PluginNotFoundException e ) { throw new MojoExecutionException( "Could not find plugin", e ); } catch ( LifecycleExecutionException e ) { throw new MojoExecutionException( "Could not determine lifecycle", e ); } catch ( IllegalAccessException e ) { throw new MojoExecutionException( "Could not determine lifecycles", e ); } catch ( NullPointerException e ) { // Maven 3.x } return lifecyclePlugins; } /** * Gets the plugins that are bound to the defined phases. This does not find plugins bound in the pom to a phase * later than the plugin is executing. * * @param project the project * @param thePhases the the phases * @return the bound plugins * @throws org.apache.maven.plugin.PluginNotFoundException * the plugin not found exception * @throws LifecycleExecutionException the lifecycle execution exception * @throws IllegalAccessException the illegal access exception */ // pilfered this from enforcer-rules // TODO coordinate with Brian Fox to remove the duplicate code private Set<Plugin> getBoundPlugins( MavenProject project, String thePhases ) throws PluginNotFoundException, LifecycleExecutionException, IllegalAccessException { if ( new DefaultArtifactVersion( "3.0" ).compareTo( runtimeInformation.getApplicationVersion() ) <= 0 ) { getLog().debug( "Using Maven 3.0+ strategy to determine lifecycle defined plugins" ); try { Method getPluginsBoundByDefaultToAllLifecycles = LifecycleExecutor.class.getMethod( "getPluginsBoundByDefaultToAllLifecycles", new Class[]{ String.class } ); Set<Plugin> plugins = (Set<Plugin>) getPluginsBoundByDefaultToAllLifecycles.invoke( lifecycleExecutor, new Object[]{ project.getPackaging() == null ? "jar" : project.getPackaging() } ); // we need to provide a copy with the version blanked out so that inferring from super-pom // works as for 2.x as 3.x fills in the version on us! Set<Plugin> result = new LinkedHashSet<Plugin>( plugins.size() ); for ( Plugin plugin : plugins ) { Plugin dup = new Plugin(); dup.setGroupId( plugin.getGroupId() ); dup.setArtifactId( plugin.getArtifactId() ); result.add( dup ); } return result; } catch ( NoSuchMethodException e1 ) { // no much we can do here } catch ( InvocationTargetException e1 ) { // no much we can do here } catch ( IllegalAccessException e1 ) { // no much we can do here } } List lifecycles = null; getLog().debug( "Using Maven 2.0.10+ strategy to determine lifecycle defined plugins" ); try { Method getLifecycles = LifecycleExecutor.class.getMethod( "getLifecycles", new Class[0] ); lifecycles = (List) getLifecycles.invoke( lifecycleExecutor, new Object[0] ); } catch ( NoSuchMethodException e1 ) { // no much we can do here } catch ( InvocationTargetException e1 ) { // no much we can do here } catch ( IllegalAccessException e1 ) { // no much we can do here } Set<Plugin> allPlugins = new HashSet<Plugin>(); // lookup the bindings for all the passed in phases for ( String lifecyclePhase : thePhases.split( "," ) ) { if ( StringUtils.isNotEmpty( lifecyclePhase ) ) { try { Lifecycle lifecycle = getLifecycleForPhase( lifecycles, lifecyclePhase ); allPlugins.addAll( getAllPlugins( project, lifecycle ) ); } catch ( BuildFailureException e ) { // i'm going to swallow this because the // user may have declared a phase that // doesn't exist for every module. } } } return allPlugins; } /** * Gets the lifecycle for phase. * * @param lifecycles The list of lifecycles. * @param phase the phase * @return the lifecycle for phase * @throws BuildFailureException the build failure exception * @throws LifecycleExecutionException the lifecycle execution exception */ private Lifecycle getLifecycleForPhase( List lifecycles, String phase ) throws BuildFailureException, LifecycleExecutionException { Lifecycle lifecycle = (Lifecycle) getPhaseToLifecycleMap( lifecycles ).get( phase ); if ( lifecycle == null ) { throw new BuildFailureException( "Unable to find lifecycle for phase '" + phase + "'" ); } return lifecycle; } /* * Uses borrowed lifecycle code to get a list of all plugins bound to the lifecycle. */ /** * Gets the all plugins. * * @param project the project * @param lifecycle the lifecycle * @return the all plugins * @throws PluginNotFoundException the plugin not found exception * @throws LifecycleExecutionException the lifecycle execution exception */ private Set<Plugin> getAllPlugins( MavenProject project, Lifecycle lifecycle ) throws PluginNotFoundException, LifecycleExecutionException { Set<Plugin> plugins = new HashSet<Plugin>(); // first, bind those associated with the packaging Map mappings = findMappingsForLifecycle( project, lifecycle ); Iterator iter = mappings.entrySet().iterator(); while ( iter.hasNext() ) { Map.Entry entry = (Map.Entry) iter.next(); String value = (String) entry.getValue(); String[] tokens = value.split( ":" ); Plugin plugin = new Plugin(); plugin.setGroupId( tokens[0] ); plugin.setArtifactId( tokens[1] ); plugins.add( plugin ); } for ( String value : findOptionalMojosForLifecycle( project, lifecycle ) ) { String[] tokens = value.split( ":" ); Plugin plugin = new Plugin(); plugin.setGroupId( tokens[0] ); plugin.setArtifactId( tokens[1] ); plugins.add( plugin ); } plugins.addAll( (List<Plugin>) project.getBuildPlugins() ); return plugins; } /** * Find mappings for lifecycle. * * @param project the project * @param lifecycle the lifecycle * @return the map * @throws LifecycleExecutionException the lifecycle execution exception * @throws PluginNotFoundException the plugin not found exception */ private Map findMappingsForLifecycle( MavenProject project, Lifecycle lifecycle ) throws LifecycleExecutionException, PluginNotFoundException { String packaging = project.getPackaging(); Map mappings = null; LifecycleMapping m = (LifecycleMapping) findExtension( project, LifecycleMapping.ROLE, packaging, session.getSettings(), session.getLocalRepository() ); if ( m != null ) { mappings = m.getPhases( lifecycle.getId() ); } Map defaultMappings = lifecycle.getDefaultPhases(); if ( mappings == null ) { try { m = (LifecycleMapping) session.lookup( LifecycleMapping.ROLE, packaging ); mappings = m.getPhases( lifecycle.getId() ); } catch ( ComponentLookupException e ) { if ( defaultMappings == null ) { throw new LifecycleExecutionException( "Cannot find lifecycle mapping for packaging: \'" + packaging + "\'.", e ); } } } if ( mappings == null ) { if ( defaultMappings == null ) { throw new LifecycleExecutionException( "Cannot find lifecycle mapping for packaging: \'" + packaging + "\', and there is no default" ); } else { mappings = defaultMappings; } } return mappings; } /** * Find optional mojos for lifecycle. * * @param project the project * @param lifecycle the lifecycle * @return the list * @throws LifecycleExecutionException the lifecycle execution exception * @throws PluginNotFoundException the plugin not found exception */ private List<String> findOptionalMojosForLifecycle( MavenProject project, Lifecycle lifecycle ) throws LifecycleExecutionException, PluginNotFoundException { String packaging = project.getPackaging(); List<String> optionalMojos = null; LifecycleMapping m = (LifecycleMapping) findExtension( project, LifecycleMapping.ROLE, packaging, session.getSettings(), session.getLocalRepository() ); if ( m != null ) { optionalMojos = m.getOptionalMojos( lifecycle.getId() ); } if ( optionalMojos == null ) { try { m = (LifecycleMapping) session.lookup( LifecycleMapping.ROLE, packaging ); optionalMojos = m.getOptionalMojos( lifecycle.getId() ); } catch ( ComponentLookupException e ) { getLog().debug( "Error looking up lifecycle mapping to retrieve optional mojos. Lifecycle ID: " + lifecycle.getId() + ". Error: " + e.getMessage(), e ); } } if ( optionalMojos == null ) { optionalMojos = Collections.emptyList(); } return optionalMojos; } /** * Find extension. * * @param project the project * @param role the role * @param roleHint the role hint * @param settings the settings * @param localRepository the local repository * @return the object * @throws LifecycleExecutionException the lifecycle execution exception * @throws PluginNotFoundException the plugin not found exception */ private Object findExtension( MavenProject project, String role, String roleHint, Settings settings, ArtifactRepository localRepository ) throws LifecycleExecutionException, PluginNotFoundException { Object pluginComponent = null; for ( Iterator i = project.getBuildPlugins().iterator(); i.hasNext() && pluginComponent == null; ) { Plugin plugin = (Plugin) i.next(); if ( plugin.isExtensions() ) { loadPluginDescriptor( plugin, project, session ); // TODO: if moved to the plugin manager we // already have the descriptor from above // and so do can lookup the container // directly try { pluginComponent = pluginManager.getPluginComponent( plugin, role, roleHint ); } catch ( ComponentLookupException e ) { getLog().debug( "Unable to find the lifecycle component in the extension", e ); } catch ( PluginManagerException e ) { throw new LifecycleExecutionException( "Error getting extensions from the plugin '" + plugin.getKey() + "': " + e.getMessage(), e ); } } } return pluginComponent; } /** * Verify plugin. * * @param plugin the plugin * @param project the project * @param session the session * @return the plugin descriptor * @throws LifecycleExecutionException the lifecycle execution exception * @throws PluginNotFoundException the plugin not found exception */ private PluginDescriptor loadPluginDescriptor( Plugin plugin, MavenProject project, MavenSession session ) throws LifecycleExecutionException, PluginNotFoundException { PluginDescriptor pluginDescriptor; try { pluginDescriptor = pluginManager.loadPluginDescriptor( plugin, project, session ); } catch ( PluginManagerException e ) { throw new LifecycleExecutionException( "Internal error in the plugin manager getting plugin '" + plugin.getKey() + "': " + e.getMessage(), e ); } catch ( PluginVersionResolutionException e ) { throw new LifecycleExecutionException( e.getMessage(), e ); } catch ( InvalidVersionSpecificationException e ) { throw new LifecycleExecutionException( e.getMessage(), e ); } catch ( InvalidPluginException e ) { throw new LifecycleExecutionException( e.getMessage(), e ); } catch ( ArtifactNotFoundException e ) { throw new LifecycleExecutionException( e.getMessage(), e ); } catch ( ArtifactResolutionException e ) { throw new LifecycleExecutionException( e.getMessage(), e ); } catch ( PluginVersionNotFoundException e ) { throw new LifecycleExecutionException( e.getMessage(), e ); } return pluginDescriptor; } /** * Returns all the parent projects of the specified project, with the root project first. * * @param project The maven project to get the parents of * @return the parent projects of the specified project, with the root project first. * @throws org.apache.maven.plugin.MojoExecutionException * if the super-pom could not be created. * @since 1.0-alpha-1 */ private List<MavenProject> getParentProjects( MavenProject project ) throws MojoExecutionException { List<MavenProject> parents = new ArrayList<MavenProject>(); while ( project.getParent() != null ) { project = project.getParent(); parents.add( 0, project ); } return parents; } /* * NOTE: All the code following this point was scooped from the DefaultLifecycleExecutor. There must be a better way * but for now it should work. */ /** * Gets the phase to lifecycle map. * * @param lifecycles The list of lifecycles. * @return the phase to lifecycle map. * @throws LifecycleExecutionException the lifecycle execution exception. */ public Map getPhaseToLifecycleMap( List lifecycles ) throws LifecycleExecutionException { Map phaseToLifecycleMap = new HashMap(); for ( Iterator i = lifecycles.iterator(); i.hasNext(); ) { Lifecycle lifecycle = (Lifecycle) i.next(); for ( Iterator p = lifecycle.getPhases().iterator(); p.hasNext(); ) { String phase = (String) p.next(); if ( phaseToLifecycleMap.containsKey( phase ) ) { Lifecycle prevLifecycle = (Lifecycle) phaseToLifecycleMap.get( phase ); throw new LifecycleExecutionException( "Phase '" + phase + "' is defined in more than one lifecycle: '" + lifecycle.getId() + "' and '" + prevLifecycle.getId() + "'" ); } else { phaseToLifecycleMap.put( phase, lifecycle ); } } } return phaseToLifecycleMap; } /** * Returns the set of all plugins used by the project. * * @param superPomPluginManagement the super pom's pluginManagement plugins. * @param parentPluginManagement the parent pom's pluginManagement plugins. * @param parentBuildPlugins the parent pom's build plugins. * @param parentReportPlugins the parent pom's report plugins. * @param pluginsWithVersionsSpecified the plugin coords that have a version defined in the project. * @return the set of plugins used by the project. * @throws org.apache.maven.plugin.MojoExecutionException * if things go wrong. */ private Set<Plugin> getProjectPlugins( Map<String, String> superPomPluginManagement, Map<String, String> parentPluginManagement, Map<String, String> parentBuildPlugins, Map<String, String> parentReportPlugins, Set<String> pluginsWithVersionsSpecified ) throws MojoExecutionException { Map<String, Plugin> plugins = new HashMap<String, Plugin>(); getLog().debug( "Building list of project plugins..." ); if ( getLog().isDebugEnabled() ) { StringWriter origModel = new StringWriter(); try { origModel.write( "Original model:\n" ); getProject().writeOriginalModel( origModel ); getLog().debug( origModel.toString() ); } catch ( IOException e ) { // ignore } } debugVersionMap( "super-pom version map", superPomPluginManagement ); debugVersionMap( "parent version map", parentPluginManagement ); Map<String, String> excludePluginManagement = new HashMap<String, String>( superPomPluginManagement ); excludePluginManagement.putAll( parentPluginManagement ); debugVersionMap( "aggregate version map", excludePluginManagement ); excludePluginManagement.keySet().removeAll( pluginsWithVersionsSpecified ); debugVersionMap( "final aggregate version map", excludePluginManagement ); Model originalModel; try { originalModel = modelInterpolator.interpolate( getProject().getOriginalModel(), getProject().getBasedir(), new DefaultProjectBuilderConfiguration().setExecutionProperties( getProject().getProperties() ), true ); } catch ( ModelInterpolationException e ) { throw new MojoExecutionException( e.getMessage(), e ); } try { addProjectPlugins( plugins, originalModel.getBuild().getPluginManagement().getPlugins(), excludePluginManagement ); } catch ( NullPointerException e ) { // guess there are no plugins here } debugPluginMap( "after adding local pluginManagement", plugins ); try { List<Plugin> lifecyclePlugins = new ArrayList<Plugin>( getLifecyclePlugins( getProject() ).values() ); for ( Iterator<Plugin> i = lifecyclePlugins.iterator(); i.hasNext(); ) { Plugin lifecyclePlugin = i.next(); if ( getPluginVersion( lifecyclePlugin ) != null ) { // version comes from lifecycle, therefore cannot modify i.remove(); } else { // lifecycle leaves version open String parentVersion = parentPluginManagement.get( getPluginCoords( lifecyclePlugin ) ); if ( parentVersion != null ) { // parent controls version i.remove(); } } } addProjectPlugins( plugins, lifecyclePlugins, parentPluginManagement ); debugPluginMap( "after adding lifecycle plugins", plugins ); } catch ( NullPointerException e ) { // using maven 3.x or newer } try { List<Plugin> buildPlugins = new ArrayList<Plugin>( originalModel.getBuild().getPlugins() ); for ( Iterator<Plugin> i = buildPlugins.iterator(); i.hasNext(); ) { Plugin buildPlugin = i.next(); if ( getPluginVersion( buildPlugin ) == null ) { String parentVersion = parentPluginManagement.get( getPluginCoords( buildPlugin ) ); if ( parentVersion != null ) { // parent controls version i.remove(); } } } addProjectPlugins( plugins, buildPlugins, parentBuildPlugins ); } catch ( NullPointerException e ) { // guess there are no plugins here } debugPluginMap( "after adding build plugins", plugins ); try { List<ReportPlugin> reportPlugins = new ArrayList<ReportPlugin>( originalModel.getReporting().getPlugins() ); for ( Iterator<ReportPlugin> i = reportPlugins.iterator(); i.hasNext(); ) { ReportPlugin reportPlugin = i.next(); if ( getPluginVersion( reportPlugin ) == null ) { String parentVersion = parentPluginManagement.get( getPluginCoords( reportPlugin ) ); if ( parentVersion != null ) { // parent controls version i.remove(); } } } addProjectPlugins( plugins, toPlugins( reportPlugins ), parentReportPlugins ); } catch ( NullPointerException e ) { // guess there are no plugins here } debugPluginMap( "after adding reporting plugins", plugins ); for ( Profile profile : originalModel.getProfiles() ) { try { addProjectPlugins( plugins, profile.getBuild().getPluginManagement().getPlugins(), excludePluginManagement ); } catch ( NullPointerException e ) { // guess there are no plugins here } debugPluginMap( "after adding build pluginManagement for profile " + profile.getId(), plugins ); try { addProjectPlugins( plugins, profile.getBuild().getPlugins(), parentBuildPlugins ); } catch ( NullPointerException e ) { // guess there are no plugins here } debugPluginMap( "after adding build plugins for profile " + profile.getId(), plugins ); try { addProjectPlugins( plugins, toPlugins( profile.getReporting().getPlugins() ), parentReportPlugins ); } catch ( NullPointerException e ) { // guess there are no plugins here } debugPluginMap( "after adding reporting plugins for profile " + profile.getId(), plugins ); } Set<Plugin> result = new TreeSet<Plugin>( new PluginComparator() ); result.addAll( plugins.values() ); return result; } /** * Adds those project plugins which are not inherited from the parent definitions to the list of plugins. * * @param plugins The list of plugins. * @param projectPlugins The project's plugins. * @param parentDefinitions The parent plugin definitions. * @since 1.0-alpha-1 */ private void addProjectPlugins( Map<String, Plugin> plugins, Collection<Plugin> projectPlugins, Map<String, String> parentDefinitions ) { for ( Plugin plugin : projectPlugins ) { String coord = getPluginCoords( plugin ); String version = getPluginVersion( plugin ); String parentVersion = parentDefinitions.get( coord ); if ( version == null && ( !plugins.containsKey( coord ) || getPluginVersion( plugins.get( coord ) ) == null ) && parentVersion != null ) { Plugin parentPlugin = new Plugin(); parentPlugin.setGroupId( getPluginGroupId( plugin ) ); parentPlugin.setArtifactId( getPluginArtifactId( plugin ) ); parentPlugin.setVersion( parentVersion ); plugins.put( coord, parentPlugin ); } else if ( parentVersion == null || !parentVersion.equals( version ) ) { if ( !plugins.containsKey( coord ) || getPluginVersion( plugins.get( coord ) ) == null ) { plugins.put( coord, plugin ); } } if ( !plugins.containsKey( coord ) ) { plugins.put( coord, plugin ); } } } /** * Logs at debug level a map of plugins keyed by versionless key. * * @param description log description * @param plugins a map with keys being the {@link String} corresponding to the versionless artifact key and * values being {@link Plugin} or {@link ReportPlugin}. */ private void debugPluginMap( String description, Map plugins ) { if ( getLog().isDebugEnabled() ) { Set sorted = new TreeSet( new PluginComparator() ); sorted.addAll( plugins.values() ); StringBuilder buf = new StringBuilder( description ); Iterator i = sorted.iterator(); while ( i.hasNext() ) { Object plugin = i.next(); buf.append( "\n " ); buf.append( getPluginCoords( plugin ) ); buf.append( ":" ); buf.append( getPluginVersion( plugin ) ); } getLog().debug( buf.toString() ); } } /** * Logs at debug level a map of plugin versions keyed by versionless key. * * @param description log description * @param plugins a map with keys being the {@link String} corresponding to the versionless artifact key and * values being {@link String} plugin version. */ private void debugVersionMap( String description, Map plugins ) { if ( getLog().isDebugEnabled() ) { StringBuilder buf = new StringBuilder( description ); Iterator i = plugins.entrySet().iterator(); while ( i.hasNext() ) { Map.Entry plugin = (Map.Entry) i.next(); buf.append( "\n " ); buf.append( plugin.getKey() ); buf.append( ":" ); buf.append( plugin.getValue() ); } getLog().debug( buf.toString() ); } } /** * Returns the coordinates of a plugin. * * @param plugin The plugin * @return The groupId and artifactId separated by a colon. * @since 1.0-alpha-1 */ private static String getPluginCoords( Object plugin ) { return getPluginGroupId( plugin ) + ":" + getPluginArtifactId( plugin ); } /** * Returns the ArtifactId of a {@link Plugin} or {@link ReportPlugin} * * @param plugin the {@link Plugin} or {@link ReportPlugin} * @return the ArtifactId of the {@link Plugin} or {@link ReportPlugin} * @since 1.0-alpha-1 */ private static String getPluginArtifactId( Object plugin ) { return plugin instanceof ReportPlugin ? ( (ReportPlugin) plugin ).getArtifactId() : ( (Plugin) plugin ).getArtifactId(); } private static Plugin toPlugin( ReportPlugin reportPlugin ) { Plugin plugin = new Plugin(); plugin.setGroupId( reportPlugin.getGroupId() ); plugin.setArtifactId( reportPlugin.getArtifactId() ); plugin.setVersion( reportPlugin.getVersion() ); return plugin; } private static ReportPlugin toReportPlugin( Plugin plugin ) { ReportPlugin reportPlugin = new ReportPlugin(); reportPlugin.setGroupId( plugin.getGroupId() ); reportPlugin.setArtifactId( plugin.getArtifactId() ); reportPlugin.setVersion( plugin.getVersion() ); return reportPlugin; } private static Set<Plugin> toPlugins( Set<ReportPlugin> reportPlugins ) { Set<Plugin> result; if ( reportPlugins instanceof LinkedHashSet ) { result = new LinkedHashSet<Plugin>( reportPlugins.size() ); } else if ( reportPlugins instanceof SortedSet ) { final Comparator<? super ReportPlugin> comparator = ( (SortedSet<ReportPlugin>) reportPlugins ).comparator(); result = new TreeSet<Plugin>( new Comparator<Plugin>() { public int compare( Plugin o1, Plugin o2 ) { return comparator.compare( toReportPlugin( o1 ), toReportPlugin( o2 ) ); } } ); } else { result = new HashSet<Plugin>( reportPlugins.size() ); } for ( ReportPlugin reportPlugin : reportPlugins ) { result.add( toPlugin( reportPlugin ) ); } return result; } private static List<Plugin> toPlugins( List<ReportPlugin> reportPlugins ) { List<Plugin> result = new ArrayList<Plugin>( reportPlugins.size() ); for ( ReportPlugin reportPlugin : reportPlugins ) { result.add( toPlugin( reportPlugin ) ); } return result; } private static Collection<Plugin> toPlugins( Collection<ReportPlugin> reportPlugins ) { if ( reportPlugins instanceof Set ) { return toPlugins( (Set<ReportPlugin>) reportPlugins ); } if ( reportPlugins instanceof List ) { return toPlugins( (List<ReportPlugin>) reportPlugins ); } return toPlugins( new ArrayList<ReportPlugin>( reportPlugins ) ); } /** * Returns the GroupId of a {@link Plugin} or {@link ReportPlugin} * * @param plugin the {@link Plugin} or {@link ReportPlugin} * @return the GroupId of the {@link Plugin} or {@link ReportPlugin} * @since 1.0-alpha-1 */ private static String getPluginGroupId( Object plugin ) { return plugin instanceof ReportPlugin ? ( (ReportPlugin) plugin ).getGroupId() : ( (Plugin) plugin ).getGroupId(); } /** * Returns the Version of a {@link Plugin} or {@link ReportPlugin} * * @param plugin the {@link Plugin} or {@link ReportPlugin} * @return the Version of the {@link Plugin} or {@link ReportPlugin} * @since 1.0-alpha-1 */ private static String getPluginVersion( Object plugin ) { return plugin instanceof ReportPlugin ? ( (ReportPlugin) plugin ).getVersion() : ( (Plugin) plugin ).getVersion(); } /** * Gets the report plugins of a specific project. * * @param model the model to get the report plugins from. * @param onlyIncludeInherited <code>true</code> to only return the plugins definitions that will be * inherited by child projects. * @return The map of effective plugin versions keyed by coordinates. * @since 1.0-alpha-1 */ private Map<String, String> getReportPlugins( Model model, boolean onlyIncludeInherited ) { Map<String, String> reportPlugins = new HashMap<String, String>(); try { for ( ReportPlugin plugin : model.getReporting().getPlugins() ) { String coord = getPluginCoords( plugin ); String version = getPluginVersion( plugin ); if ( version != null && ( !onlyIncludeInherited || getPluginInherited( plugin ) ) ) { reportPlugins.put( coord, version ); } } } catch ( NullPointerException e ) { // guess there are no plugins here } try { for ( Profile profile : model.getProfiles() ) { try { for ( ReportPlugin plugin : profile.getReporting().getPlugins() ) { String coord = getPluginCoords( plugin ); String version = getPluginVersion( plugin ); if ( version != null && ( !onlyIncludeInherited || getPluginInherited( plugin ) ) ) { reportPlugins.put( coord, version ); } } } catch ( NullPointerException e ) { // guess there are no plugins here } } } catch ( NullPointerException e ) { // guess there are no profiles here } return reportPlugins; } /** * @param pom the pom to update. * @throws MojoExecutionException when things go wrong * @throws MojoFailureException when things go wrong in a very bad way * @throws XMLStreamException when things go wrong with XML streaming * @see AbstractVersionsUpdaterMojo#update(ModifiedPomXMLEventReader) * @since 1.0-alpha-1 */ protected void update( ModifiedPomXMLEventReader pom ) throws MojoExecutionException, MojoFailureException, XMLStreamException { // do nothing } }
src/main/java/org/codehaus/mojo/versions/DisplayPluginUpdatesMojo.java
package org.codehaus.mojo.versions; /* * 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 org.apache.maven.BuildFailureException; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException; 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.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.RuntimeInformation; import org.apache.maven.lifecycle.Lifecycle; import org.apache.maven.lifecycle.LifecycleExecutionException; import org.apache.maven.lifecycle.LifecycleExecutor; import org.apache.maven.lifecycle.mapping.LifecycleMapping; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.model.Prerequisites; import org.apache.maven.model.Profile; import org.apache.maven.model.ReportPlugin; import org.apache.maven.model.io.xpp3.MavenXpp3Writer; import org.apache.maven.plugin.InvalidPluginException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.PluginManager; import org.apache.maven.plugin.PluginManagerException; import org.apache.maven.plugin.PluginNotFoundException; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.plugin.version.PluginVersionNotFoundException; import org.apache.maven.plugin.version.PluginVersionResolutionException; import org.apache.maven.project.DefaultProjectBuilderConfiguration; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.interpolation.ModelInterpolationException; import org.apache.maven.project.interpolation.ModelInterpolator; import org.apache.maven.settings.Settings; import org.codehaus.mojo.versions.api.ArtifactVersions; import org.codehaus.mojo.versions.api.PomHelper; import org.codehaus.mojo.versions.ordering.MavenVersionComparator; import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; import org.codehaus.mojo.versions.utils.PluginComparator; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.StringUtils; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import java.io.IOException; import java.io.Reader; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Pattern; /** * Displays all plugins that have newer versions available. * * @author Stephen Connolly * @goal display-plugin-updates * @requiresProject true * @requiresDirectInvocation false * @since 1.0-alpha-1 */ public class DisplayPluginUpdatesMojo extends AbstractVersionsUpdaterMojo { // ------------------------------ FIELDS ------------------------------ /** * The width to pad warn messages. * * @since 1.0-alpha-1 */ private static final int WARN_PAD_SIZE = 65; /** * The width to pad info messages. * * @since 1.0-alpha-1 */ private static final int INFO_PAD_SIZE = 68; /** * String to flag a plugin version being forced by the super-pom. * * @since 1.0-alpha-1 */ private static final String FROM_SUPER_POM = "(from super-pom) "; /** * @component * @since 1.0-alpha-1 */ private LifecycleExecutor lifecycleExecutor; /** * @component * @since 1.0-alpha-3 */ private ModelInterpolator modelInterpolator; /** * The plugin manager. * * @component * @since 1.0-alpha-1 */ private PluginManager pluginManager; /** * @component * @since 1.3 */ private RuntimeInformation runtimeInformation; // --------------------- GETTER / SETTER METHODS --------------------- /** * Returns the pluginManagement section of the super-pom. * * @return Returns the pluginManagement section of the super-pom. * @throws MojoExecutionException when things go wrong. */ private Map<String, String> getSuperPomPluginManagement() throws MojoExecutionException { if ( new DefaultArtifactVersion( "3.0" ).compareTo( runtimeInformation.getApplicationVersion() ) <= 0 ) { getLog().debug( "Using Maven 3.x strategy to determine superpom defined plugins" ); try { Method getPluginsBoundByDefaultToAllLifecycles = LifecycleExecutor.class.getMethod( "getPluginsBoundByDefaultToAllLifecycles", new Class[]{ String.class } ); Set<Plugin> plugins = (Set<Plugin>) getPluginsBoundByDefaultToAllLifecycles.invoke( lifecycleExecutor, new Object[]{ getProject().getPackaging() } ); // we need to provide a copy with the version blanked out so that inferring from super-pom // works as for 2.x as 3.x fills in the version on us! Map<String, String> result = new LinkedHashMap<String, String>( plugins.size() ); for ( Plugin plugin : plugins ) { result.put( getPluginCoords( plugin ), getPluginVersion( plugin ) ); } URL superPom = getClass().getClassLoader().getResource( "org/apache/maven/model/pom-4.0.0.xml" ); if ( superPom != null ) { try { Reader reader = ReaderFactory.newXmlReader( superPom ); try { StringBuilder buf = new StringBuilder( IOUtil.toString( reader ) ); ModifiedPomXMLEventReader pom = newModifiedPomXER( buf ); Pattern pathRegex = Pattern.compile( "/project(/profiles/profile)?" + "((/build(/pluginManagement)?)|(/reporting))" + "/plugins/plugin" ); Stack<StackState> pathStack = new Stack<StackState>(); StackState curState = null; while ( pom.hasNext() ) { XMLEvent event = pom.nextEvent(); if ( event.isStartDocument() ) { curState = new StackState( "" ); pathStack.clear(); } else if ( event.isStartElement() ) { String elementName = event.asStartElement().getName().getLocalPart(); if ( curState != null && pathRegex.matcher( curState.path ).matches() ) { if ( "groupId".equals( elementName ) ) { curState.groupId = pom.getElementText().trim(); continue; } else if ( "artifactId".equals( elementName ) ) { curState.artifactId = pom.getElementText().trim(); continue; } else if ( "version".equals( elementName ) ) { curState.version = pom.getElementText().trim(); continue; } } pathStack.push( curState ); curState = new StackState( curState.path + "/" + elementName ); } else if ( event.isEndElement() ) { if ( curState != null && pathRegex.matcher( curState.path ).matches() ) { if ( curState.artifactId != null ) { Plugin plugin = new Plugin(); plugin.setArtifactId( curState.artifactId ); plugin.setGroupId( curState.groupId == null ? PomHelper.APACHE_MAVEN_PLUGINS_GROUPID : curState.groupId ); plugin.setVersion( curState.version ); if ( !result.containsKey( getPluginCoords( plugin ) ) ) { result.put( getPluginCoords( plugin ), getPluginVersion( plugin ) ); } } } curState = pathStack.pop(); } } } finally { IOUtil.close( reader ); } } catch ( IOException e ) { // ignore } catch ( XMLStreamException e ) { // ignore } } return result; } catch ( NoSuchMethodException e1 ) { // no much we can do here } catch ( InvocationTargetException e1 ) { // no much we can do here } catch ( IllegalAccessException e1 ) { // no much we can do here } } getLog().debug( "Using Maven 2.x strategy to determine superpom defined plugins" ); Map<String, String> superPomPluginManagement = new HashMap(); try { MavenProject superProject = projectBuilder.buildStandaloneSuperProject( new DefaultProjectBuilderConfiguration() ); superPomPluginManagement.putAll( getPluginManagement( superProject.getOriginalModel() ) ); } catch ( ProjectBuildingException e ) { throw new MojoExecutionException( "Could not determine the super pom.xml", e ); } return superPomPluginManagement; } /** * Gets the plugin management plugins of a specific project. * * @param model the model to get the plugin management plugins from. * @return The map of effective plugin versions keyed by coordinates. * @since 1.0-alpha-1 */ private Map<String, String> getPluginManagement( Model model ) { // we want only those parts of pluginManagement that are defined in this project Map<String, String> pluginManagement = new HashMap<String, String>(); try { for ( Plugin plugin : model.getBuild().getPluginManagement().getPlugins() ) { String coord = getPluginCoords( plugin ); String version = getPluginVersion( plugin ); if ( version != null ) { pluginManagement.put( coord, version ); } } } catch ( NullPointerException e ) { // guess there are no plugins here } try { for ( Profile profile : model.getProfiles() ) { try { for ( Plugin plugin : profile.getBuild().getPluginManagement().getPlugins() ) { String coord = getPluginCoords( plugin ); String version = getPluginVersion( plugin ); if ( version != null ) { pluginManagement.put( coord, version ); } } } catch ( NullPointerException e ) { // guess there are no plugins here } } } catch ( NullPointerException e ) { // guess there are no profiles here } return pluginManagement; } // ------------------------ INTERFACE METHODS ------------------------ // --------------------- Interface Mojo --------------------- /** * @throws MojoExecutionException when things go wrong * @throws MojoFailureException when things go wrong in a very bad way * @see AbstractVersionsUpdaterMojo#execute() * @since 1.0-alpha-1 */ public void execute() throws MojoExecutionException, MojoFailureException { Set<String> pluginsWithVersionsSpecified; try { pluginsWithVersionsSpecified = findPluginsWithVersionsSpecified( getProject() ); } catch ( XMLStreamException e ) { throw new MojoExecutionException( e.getMessage(), e ); } catch ( IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } Map<String, String> superPomPluginManagement = getSuperPomPluginManagement(); getLog().debug( "superPom plugins = " + superPomPluginManagement ); Map<String, String> parentPluginManagement = new HashMap<String, String>(); Map<String, String> parentBuildPlugins = new HashMap<String, String>(); Map<String, String> parentReportPlugins = new HashMap<String, String>(); List<MavenProject> parents = getParentProjects( getProject() ); for ( MavenProject parentProject : parents ) { getLog().debug( "Processing parent: " + parentProject.getGroupId() + ":" + parentProject.getArtifactId() + ":" + parentProject.getVersion() + " -> " + parentProject.getFile() ); StringWriter writer = new StringWriter(); boolean havePom = false; Model interpolatedModel; try { Model originalModel = parentProject.getOriginalModel(); if ( originalModel == null ) { getLog().warn( "project.getOriginalModel()==null for " + parentProject.getGroupId() + ":" + parentProject.getArtifactId() + ":" + parentProject.getVersion() + " is null, substituting project.getModel()" ); originalModel = parentProject.getModel(); } try { new MavenXpp3Writer().write( writer, originalModel ); writer.close(); havePom = true; } catch ( IOException e ) { // ignore } interpolatedModel = modelInterpolator.interpolate( originalModel, null, new DefaultProjectBuilderConfiguration().setExecutionProperties( getProject().getProperties() ), false ); } catch ( ModelInterpolationException e ) { throw new MojoExecutionException( e.getMessage(), e ); } if ( havePom ) { try { Set<String> withVersionSpecified = findPluginsWithVersionsSpecified( new StringBuilder( writer.toString() ) ); Map<String, String> map = getPluginManagement( interpolatedModel ); map.keySet().retainAll( withVersionSpecified ); parentPluginManagement.putAll( map ); map = getBuildPlugins( interpolatedModel, true ); map.keySet().retainAll( withVersionSpecified ); parentPluginManagement.putAll( map ); map = getReportPlugins( interpolatedModel, true ); map.keySet().retainAll( withVersionSpecified ); parentPluginManagement.putAll( map ); } catch ( IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } catch ( XMLStreamException e ) { throw new MojoExecutionException( e.getMessage(), e ); } } else { parentPluginManagement.putAll( getPluginManagement( interpolatedModel ) ); parentPluginManagement.putAll( getBuildPlugins( interpolatedModel, true ) ); parentPluginManagement.putAll( getReportPlugins( interpolatedModel, true ) ); } } Set<Plugin> plugins = getProjectPlugins( superPomPluginManagement, parentPluginManagement, parentBuildPlugins, parentReportPlugins, pluginsWithVersionsSpecified ); List<String> updates = new ArrayList<String>(); List<String> lockdowns = new ArrayList<String>(); Map<ArtifactVersion, Map<String, String>> upgrades = new TreeMap<ArtifactVersion, Map<String, String>>( new MavenVersionComparator() ); ArtifactVersion curMavenVersion = runtimeInformation.getApplicationVersion(); ArtifactVersion specMavenVersion = new DefaultArtifactVersion( getRequiredMavenVersion( getProject(), "2.0" ) ); ArtifactVersion minMavenVersion = null; boolean superPomDrivingMinVersion = false; Iterator<Plugin> i = plugins.iterator(); while ( i.hasNext() ) { Object plugin = i.next(); String groupId = getPluginGroupId( plugin ); String artifactId = getPluginArtifactId( plugin ); String version = getPluginVersion( plugin ); String coords = ArtifactUtils.versionlessKey( groupId, artifactId ); if ( version == null ) { version = parentPluginManagement.get( coords ); } getLog().debug( new StringBuilder().append( "Checking " ).append( coords ).append( " for updates newer than " ).append( version ).toString() ); String effectiveVersion = version; VersionRange versionRange; boolean unspecified = version == null; try { versionRange = unspecified ? VersionRange.createFromVersionSpec( "[0,)" ) : VersionRange.createFromVersionSpec( version ); } catch ( InvalidVersionSpecificationException e ) { throw new MojoExecutionException( "Invalid version range specification: " + version, e ); } Artifact artifact = artifactFactory.createPluginArtifact( groupId, artifactId, versionRange ); ArtifactVersion artifactVersion = null; try { // now we want to find the newest version that is compatible with the invoking version of Maven ArtifactVersions artifactVersions = getHelper().lookupArtifactVersions( artifact, true ); ArtifactVersion[] newerVersions = artifactVersions.getVersions( Boolean.TRUE.equals( this.allowSnapshots ) ); ArtifactVersion minRequires = null; for ( int j = newerVersions.length - 1; j >= 0; j-- ) { Artifact probe = artifactFactory.createDependencyArtifact( groupId, artifactId, VersionRange.createFromVersion( newerVersions[j].toString() ), "pom", null, "runtime" ); try { getHelper().resolveArtifact( probe, true ); MavenProject mavenProject = projectBuilder.buildFromRepository( probe, remotePluginRepositories, localRepository ); ArtifactVersion requires = new DefaultArtifactVersion( getRequiredMavenVersion( mavenProject, "2.0" ) ); if ( specMavenVersion.compareTo( requires ) >= 0 && artifactVersion == null ) { artifactVersion = newerVersions[j]; } if ( effectiveVersion == null && curMavenVersion.compareTo( requires ) >= 0 ) { // version was unspecified, current version of maven thinks it should use this effectiveVersion = newerVersions[j].toString(); } if ( artifactVersion != null && effectiveVersion != null ) { // no need to look at any older versions. break; } if ( minRequires == null || minRequires.compareTo( requires ) > 0 ) { Map<String, String> upgradePlugins = upgrades.get( requires ); if ( upgradePlugins == null ) { upgrades.put( requires, upgradePlugins = new LinkedHashMap<String, String>() ); } String upgradePluginKey = compactKey( groupId, artifactId ); if ( !upgradePlugins.containsKey( upgradePluginKey ) ) { upgradePlugins.put( upgradePluginKey, newerVersions[j].toString() ); } minRequires = requires; } } catch ( ArtifactResolutionException e ) { // ignore bad version } catch ( ArtifactNotFoundException e ) { // ignore bad version } catch ( ProjectBuildingException e ) { // ignore bad version } } if ( effectiveVersion != null ) { VersionRange currentVersionRange = VersionRange.createFromVersion( effectiveVersion ); Artifact probe = artifactFactory.createDependencyArtifact( groupId, artifactId, currentVersionRange, "pom", null, "runtime" ); try { getHelper().resolveArtifact( probe, true ); MavenProject mavenProject = projectBuilder.buildFromRepository( probe, remotePluginRepositories, localRepository ); ArtifactVersion requires = new DefaultArtifactVersion( getRequiredMavenVersion( mavenProject, "2.0" ) ); if ( minMavenVersion == null || minMavenVersion.compareTo( requires ) < 0 ) { minMavenVersion = requires; } } catch ( ArtifactResolutionException e ) { // ignore bad version } catch ( ArtifactNotFoundException e ) { // ignore bad version } catch ( ProjectBuildingException e ) { // ignore bad version } } } catch ( ArtifactMetadataRetrievalException e ) { throw new MojoExecutionException( e.getMessage(), e ); } String newVersion; if ( version == null && pluginsWithVersionsSpecified.contains( coords ) ) { // Hack ALERT! // // All this should be re-written in a less "pom is xml" way... but it'll // work for now :-( // // we have removed the version information, as it was the same as from // the super-pom... but it actually was specified. version = artifactVersion != null ? artifactVersion.toString() : null; } getLog().debug( "[" + coords + "].version=" + version ); getLog().debug( "[" + coords + "].artifactVersion=" + artifactVersion ); getLog().debug( "[" + coords + "].effectiveVersion=" + effectiveVersion ); getLog().debug( "[" + coords + "].specified=" + pluginsWithVersionsSpecified.contains( coords ) ); if ( version == null || !pluginsWithVersionsSpecified.contains( coords ) ) { version = (String) superPomPluginManagement.get( ArtifactUtils.versionlessKey( artifact ) ); getLog().debug( "[" + coords + "].superPom.version=" + version ); newVersion = artifactVersion != null ? artifactVersion.toString() : ( version != null ? version : ( effectiveVersion != null ? effectiveVersion : "(unknown)" ) ); StringBuilder buf = new StringBuilder( compactKey( groupId, artifactId ) ); buf.append( ' ' ); int padding = WARN_PAD_SIZE - effectiveVersion.length() - ( version != null ? FROM_SUPER_POM.length() : 0 ); while ( buf.length() < padding ) { buf.append( '.' ); } buf.append( ' ' ); if ( version != null ) { buf.append( FROM_SUPER_POM ); superPomDrivingMinVersion = true; } buf.append( effectiveVersion ); lockdowns.add( buf.toString() ); } else if ( artifactVersion != null ) { newVersion = artifactVersion.toString(); } else { newVersion = null; } if ( version != null && artifactVersion != null && newVersion != null && new DefaultArtifactVersion( effectiveVersion ).compareTo( new DefaultArtifactVersion( newVersion ) ) < 0 ) { StringBuilder buf = new StringBuilder( compactKey( groupId, artifactId ) ); buf.append( ' ' ); int padding = INFO_PAD_SIZE - version.length() - newVersion.length() - 4; while ( buf.length() < padding ) { buf.append( '.' ); } buf.append( ' ' ); buf.append( effectiveVersion ); buf.append( " -> " ); buf.append( newVersion ); updates.add( buf.toString() ); } } getLog().info( "" ); if ( updates.isEmpty() ) { getLog().info( "All plugins with a version specified are using the latest versions." ); } else { getLog().info( "The following plugin updates are available:" ); for ( String update : updates ) { getLog().info( " " + update ); } } getLog().info( "" ); if ( lockdowns.isEmpty() ) { getLog().info( "All plugins have a version specified." ); } else { getLog().warn( "The following plugins do not have their version specified:" ); for ( String lockdown : lockdowns ) { getLog().warn( " " + lockdown ); } } getLog().info( "" ); boolean noMavenMinVersion = getRequiredMavenVersion( getProject(), null ) == null; boolean noExplicitMavenMinVersion = getProject().getPrerequisites() == null || getProject().getPrerequisites().getMaven() == null; if ( noMavenMinVersion ) { getLog().warn( "Project does not define minimum Maven version, default is: 2.0" ); } else if ( noExplicitMavenMinVersion ) { getLog().info( "Project inherits minimum Maven version as: " + specMavenVersion ); } else { ArtifactVersion explicitMavenVersion = new DefaultArtifactVersion( getProject().getPrerequisites().getMaven() ); if ( explicitMavenVersion.compareTo( specMavenVersion ) < 0 ) { getLog().error( "Project's effective minimum Maven (from parent) is: " + specMavenVersion ); getLog().error( "Project defines minimum Maven version as: " + explicitMavenVersion ); } else { getLog().info( "Project defines minimum Maven version as: " + specMavenVersion ); } } getLog().info( "Plugins require minimum Maven version of: " + minMavenVersion ); if ( superPomDrivingMinVersion ) { getLog().info( "Note: the super-pom from Maven " + curMavenVersion + " defines some of the plugin" ); getLog().info( " versions and may be influencing the plugins required minimum Maven" ); getLog().info( " version." ); } getLog().info( "" ); if ( "maven-plugin".equals( getProject().getPackaging() ) ) { if ( noMavenMinVersion ) { getLog().warn( "Project (which is a Maven Plugin) does not define required minimum version of Maven." ); getLog().warn( "Update the pom.xml to contain" ); getLog().warn( " <prerequisites>" ); getLog().warn( " <maven><!-- minimum version of Maven that the plugin works with --></maven>" ); getLog().warn( " </prerequisites>" ); getLog().warn( "To build this plugin you need at least Maven " + minMavenVersion ); getLog().warn( "A Maven Enforcer rule can be used to enforce this if you have not already set one up" ); } else if ( minMavenVersion != null && specMavenVersion.compareTo( minMavenVersion ) < 0 ) { getLog().warn( "Project (which is a Maven Plugin) targets Maven " + specMavenVersion + " or newer" ); getLog().warn( "but requires Maven " + minMavenVersion + " or newer to build." ); getLog().warn( "This may or may not be a problem. A Maven Enforcer rule can help " ); getLog().warn( "enforce that the correct version of Maven is used to build this plugin." ); } else { getLog().info( "No plugins require a newer version of Maven than specified by the pom." ); } } else { if ( noMavenMinVersion ) { getLog().error( "Project does not define required minimum version of Maven." ); getLog().error( "Update the pom.xml to contain" ); getLog().error( " <prerequisites>" ); getLog().error( " <maven>" + minMavenVersion + "</maven>" ); getLog().error( " </prerequisites>" ); } else if ( minMavenVersion != null && specMavenVersion.compareTo( minMavenVersion ) < 0 ) { getLog().error( "Project requires an incorrect minimum version of Maven." ); getLog().error( "Either change plugin versions to those compatible with " + specMavenVersion ); getLog().error( "or update the pom.xml to contain" ); getLog().error( " <prerequisites>" ); getLog().error( " <maven>" + minMavenVersion + "</maven>" ); getLog().error( " </prerequisites>" ); } else { getLog().info( "No plugins require a newer version of Maven than specified by the pom." ); } } for ( Map.Entry<ArtifactVersion, Map<String, String>> mavenUpgrade : upgrades.entrySet() ) { ArtifactVersion mavenUpgradeVersion = (ArtifactVersion) mavenUpgrade.getKey(); Map<String, String> upgradePlugins = mavenUpgrade.getValue(); if ( upgradePlugins.isEmpty() || specMavenVersion.compareTo( mavenUpgradeVersion ) >= 0 ) { continue; } getLog().info( "" ); getLog().info( "Require Maven " + mavenUpgradeVersion + " to use the following plugin updates:" ); for ( Map.Entry<String, String> entry : upgradePlugins.entrySet() ) { StringBuilder buf = new StringBuilder( " " ); buf.append( entry.getKey() ); buf.append( ' ' ); String s = entry.getValue(); int padding = INFO_PAD_SIZE - s.length() + 2; while ( buf.length() < padding ) { buf.append( '.' ); } buf.append( ' ' ); buf.append( s ); getLog().info( buf.toString() ); } } getLog().info( "" ); } private String compactKey( String groupId, String artifactId ) { if ( PomHelper.APACHE_MAVEN_PLUGINS_GROUPID.equals( groupId ) ) { // a core plugin... group id is not needed return artifactId; } return groupId + ":" + artifactId; } private String getRequiredMavenVersion( MavenProject mavenProject, String defaultValue ) { ArtifactVersion requiredMavenVersion = null; while ( mavenProject != null ) { final Prerequisites prerequisites = mavenProject.getPrerequisites(); final String mavenVersion = prerequisites == null ? null : prerequisites.getMaven(); if ( mavenVersion != null ) { final ArtifactVersion v = new DefaultArtifactVersion( mavenVersion ); if ( requiredMavenVersion == null || requiredMavenVersion.compareTo( v ) < 0 ) { requiredMavenVersion = v; } } mavenProject = mavenProject.getParent(); } return requiredMavenVersion == null ? defaultValue : requiredMavenVersion.toString(); } private static final class StackState { private final String path; private String groupId; private String artifactId; private String version; public StackState( String path ) { this.path = path; } public String toString() { return path + "[groupId=" + groupId + ", artifactId=" + artifactId + ", version=" + version + "]"; } } /** * Returns a set of Strings which correspond to the plugin coordinates where there is a version * specified. * * @param project The project to get the plugins with versions specified. * @return a set of Strings which correspond to the plugin coordinates where there is a version * specified. */ private Set<String> findPluginsWithVersionsSpecified( MavenProject project ) throws IOException, XMLStreamException { return findPluginsWithVersionsSpecified( PomHelper.readXmlFile( project.getFile() ) ); } /** * Returns a set of Strings which correspond to the plugin coordinates where there is a version * specified. * * @param pomContents The project to get the plugins with versions specified. * @return a set of Strings which correspond to the plugin coordinates where there is a version * specified. */ private Set<String> findPluginsWithVersionsSpecified( StringBuilder pomContents ) throws IOException, XMLStreamException { Set<String> result = new HashSet<String>(); ModifiedPomXMLEventReader pom = newModifiedPomXER( pomContents ); Pattern pathRegex = Pattern.compile( "/project(/profiles/profile)?" + "((/build(/pluginManagement)?)|(/reporting))" + "/plugins/plugin" ); Stack<StackState> pathStack = new Stack<StackState>(); StackState curState = null; while ( pom.hasNext() ) { XMLEvent event = pom.nextEvent(); if ( event.isStartDocument() ) { curState = new StackState( "" ); pathStack.clear(); } else if ( event.isStartElement() ) { String elementName = event.asStartElement().getName().getLocalPart(); if ( curState != null && pathRegex.matcher( curState.path ).matches() ) { if ( "groupId".equals( elementName ) ) { curState.groupId = pom.getElementText().trim(); continue; } else if ( "artifactId".equals( elementName ) ) { curState.artifactId = pom.getElementText().trim(); continue; } else if ( "version".equals( elementName ) ) { curState.version = pom.getElementText().trim(); continue; } } pathStack.push( curState ); curState = new StackState( curState.path + "/" + elementName ); } else if ( event.isEndElement() ) { if ( curState != null && pathRegex.matcher( curState.path ).matches() ) { if ( curState.artifactId != null && curState.version != null ) { if ( curState.groupId == null ) { curState.groupId = PomHelper.APACHE_MAVEN_PLUGINS_GROUPID; } result.add( curState.groupId + ":" + curState.artifactId ); } } curState = pathStack.pop(); } } return result; } // -------------------------- OTHER METHODS -------------------------- /** * Gets the build plugins of a specific project. * * @param model the model to get the build plugins from. * @param onlyIncludeInherited <code>true</code> to only return the plugins definitions that will be * inherited by child projects. * @return The map of effective plugin versions keyed by coordinates. * @since 1.0-alpha-1 */ private Map<String, String> getBuildPlugins( Model model, boolean onlyIncludeInherited ) { Map<String, String> buildPlugins = new HashMap(); try { for ( Plugin plugin : model.getBuild().getPlugins() ) { String coord = getPluginCoords( plugin ); String version = getPluginVersion( plugin ); if ( version != null && ( !onlyIncludeInherited || getPluginInherited( plugin ) ) ) { buildPlugins.put( coord, version ); } } } catch ( NullPointerException e ) { // guess there are no plugins here } try { for ( Profile profile : model.getProfiles() ) { try { for ( Plugin plugin : profile.getBuild().getPlugins() ) { String coord = getPluginCoords( plugin ); String version = getPluginVersion( plugin ); if ( version != null && ( !onlyIncludeInherited || getPluginInherited( plugin ) ) ) { buildPlugins.put( coord, version ); } } } catch ( NullPointerException e ) { // guess there are no plugins here } } } catch ( NullPointerException e ) { // guess there are no profiles here } return buildPlugins; } /** * Returns the Inherited of a {@link Plugin} or {@link ReportPlugin} * * @param plugin the {@link Plugin} or {@link ReportPlugin} * @return the Inherited of the {@link Plugin} or {@link ReportPlugin} * @since 1.0-alpha-1 */ private static boolean getPluginInherited( Object plugin ) { return "true".equalsIgnoreCase( plugin instanceof ReportPlugin ? ( (ReportPlugin) plugin ).getInherited() : ( (Plugin) plugin ).getInherited() ); } /** * Returns the lifecycle plugins of a specific project. * * @param project the project to get the lifecycle plugins from. * @return The map of effective plugin versions keyed by coordinates. * @throws org.apache.maven.plugin.MojoExecutionException * if things go wrong. * @since 1.0-alpha-1 */ private Map<String, Plugin> getLifecyclePlugins( MavenProject project ) throws MojoExecutionException { Map<String, Plugin> lifecyclePlugins = new HashMap<String, Plugin>(); try { Set<Plugin> plugins = getBoundPlugins( project, "clean,deploy,site" ); for ( Plugin plugin : plugins ) { lifecyclePlugins.put( getPluginCoords( plugin ), plugin ); } } catch ( PluginNotFoundException e ) { throw new MojoExecutionException( "Could not find plugin", e ); } catch ( LifecycleExecutionException e ) { throw new MojoExecutionException( "Could not determine lifecycle", e ); } catch ( IllegalAccessException e ) { throw new MojoExecutionException( "Could not determine lifecycles", e ); } catch ( NullPointerException e ) { // Maven 3.x } return lifecyclePlugins; } /** * Gets the plugins that are bound to the defined phases. This does not find plugins bound in the pom to a phase * later than the plugin is executing. * * @param project the project * @param thePhases the the phases * @return the bound plugins * @throws org.apache.maven.plugin.PluginNotFoundException * the plugin not found exception * @throws LifecycleExecutionException the lifecycle execution exception * @throws IllegalAccessException the illegal access exception */ // pilfered this from enforcer-rules // TODO coordinate with Brian Fox to remove the duplicate code private Set<Plugin> getBoundPlugins( MavenProject project, String thePhases ) throws PluginNotFoundException, LifecycleExecutionException, IllegalAccessException { if ( new DefaultArtifactVersion( "3.0" ).compareTo( runtimeInformation.getApplicationVersion() ) <= 0 ) { getLog().debug( "Using Maven 3.0+ strategy to determine lifecycle defined plugins" ); try { Method getPluginsBoundByDefaultToAllLifecycles = LifecycleExecutor.class.getMethod( "getPluginsBoundByDefaultToAllLifecycles", new Class[]{ String.class } ); Set<Plugin> plugins = (Set<Plugin>) getPluginsBoundByDefaultToAllLifecycles.invoke( lifecycleExecutor, new Object[]{ project.getPackaging() == null ? "jar" : project.getPackaging() } ); // we need to provide a copy with the version blanked out so that inferring from super-pom // works as for 2.x as 3.x fills in the version on us! Set<Plugin> result = new LinkedHashSet<Plugin>( plugins.size() ); for ( Plugin plugin : plugins ) { Plugin dup = new Plugin(); dup.setGroupId( plugin.getGroupId() ); dup.setArtifactId( plugin.getArtifactId() ); result.add( dup ); } return result; } catch ( NoSuchMethodException e1 ) { // no much we can do here } catch ( InvocationTargetException e1 ) { // no much we can do here } catch ( IllegalAccessException e1 ) { // no much we can do here } } List lifecycles = null; getLog().debug( "Using Maven 2.0.10+ strategy to determine lifecycle defined plugins" ); try { Method getLifecycles = LifecycleExecutor.class.getMethod( "getLifecycles", new Class[0] ); lifecycles = (List) getLifecycles.invoke( lifecycleExecutor, new Object[0] ); } catch ( NoSuchMethodException e1 ) { // no much we can do here } catch ( InvocationTargetException e1 ) { // no much we can do here } catch ( IllegalAccessException e1 ) { // no much we can do here } Set<Plugin> allPlugins = new HashSet<Plugin>(); // lookup the bindings for all the passed in phases for ( String lifecyclePhase : thePhases.split( "," ) ) { if ( StringUtils.isNotEmpty( lifecyclePhase ) ) { try { Lifecycle lifecycle = getLifecycleForPhase( lifecycles, lifecyclePhase ); allPlugins.addAll( getAllPlugins( project, lifecycle ) ); } catch ( BuildFailureException e ) { // i'm going to swallow this because the // user may have declared a phase that // doesn't exist for every module. } } } return allPlugins; } /** * Gets the lifecycle for phase. * * @param lifecycles The list of lifecycles. * @param phase the phase * @return the lifecycle for phase * @throws BuildFailureException the build failure exception * @throws LifecycleExecutionException the lifecycle execution exception */ private Lifecycle getLifecycleForPhase( List lifecycles, String phase ) throws BuildFailureException, LifecycleExecutionException { Lifecycle lifecycle = (Lifecycle) getPhaseToLifecycleMap( lifecycles ).get( phase ); if ( lifecycle == null ) { throw new BuildFailureException( "Unable to find lifecycle for phase '" + phase + "'" ); } return lifecycle; } /* * Uses borrowed lifecycle code to get a list of all plugins bound to the lifecycle. */ /** * Gets the all plugins. * * @param project the project * @param lifecycle the lifecycle * @return the all plugins * @throws PluginNotFoundException the plugin not found exception * @throws LifecycleExecutionException the lifecycle execution exception */ private Set<Plugin> getAllPlugins( MavenProject project, Lifecycle lifecycle ) throws PluginNotFoundException, LifecycleExecutionException { Set<Plugin> plugins = new HashSet<Plugin>(); // first, bind those associated with the packaging Map mappings = findMappingsForLifecycle( project, lifecycle ); Iterator iter = mappings.entrySet().iterator(); while ( iter.hasNext() ) { Map.Entry entry = (Map.Entry) iter.next(); String value = (String) entry.getValue(); String[] tokens = value.split( ":" ); Plugin plugin = new Plugin(); plugin.setGroupId( tokens[0] ); plugin.setArtifactId( tokens[1] ); plugins.add( plugin ); } for ( String value : findOptionalMojosForLifecycle( project, lifecycle ) ) { String[] tokens = value.split( ":" ); Plugin plugin = new Plugin(); plugin.setGroupId( tokens[0] ); plugin.setArtifactId( tokens[1] ); plugins.add( plugin ); } plugins.addAll( (List<Plugin>) project.getBuildPlugins() ); return plugins; } /** * Find mappings for lifecycle. * * @param project the project * @param lifecycle the lifecycle * @return the map * @throws LifecycleExecutionException the lifecycle execution exception * @throws PluginNotFoundException the plugin not found exception */ private Map findMappingsForLifecycle( MavenProject project, Lifecycle lifecycle ) throws LifecycleExecutionException, PluginNotFoundException { String packaging = project.getPackaging(); Map mappings = null; LifecycleMapping m = (LifecycleMapping) findExtension( project, LifecycleMapping.ROLE, packaging, session.getSettings(), session.getLocalRepository() ); if ( m != null ) { mappings = m.getPhases( lifecycle.getId() ); } Map defaultMappings = lifecycle.getDefaultPhases(); if ( mappings == null ) { try { m = (LifecycleMapping) session.lookup( LifecycleMapping.ROLE, packaging ); mappings = m.getPhases( lifecycle.getId() ); } catch ( ComponentLookupException e ) { if ( defaultMappings == null ) { throw new LifecycleExecutionException( "Cannot find lifecycle mapping for packaging: \'" + packaging + "\'.", e ); } } } if ( mappings == null ) { if ( defaultMappings == null ) { throw new LifecycleExecutionException( "Cannot find lifecycle mapping for packaging: \'" + packaging + "\', and there is no default" ); } else { mappings = defaultMappings; } } return mappings; } /** * Find optional mojos for lifecycle. * * @param project the project * @param lifecycle the lifecycle * @return the list * @throws LifecycleExecutionException the lifecycle execution exception * @throws PluginNotFoundException the plugin not found exception */ private List<String> findOptionalMojosForLifecycle( MavenProject project, Lifecycle lifecycle ) throws LifecycleExecutionException, PluginNotFoundException { String packaging = project.getPackaging(); List<String> optionalMojos = null; LifecycleMapping m = (LifecycleMapping) findExtension( project, LifecycleMapping.ROLE, packaging, session.getSettings(), session.getLocalRepository() ); if ( m != null ) { optionalMojos = m.getOptionalMojos( lifecycle.getId() ); } if ( optionalMojos == null ) { try { m = (LifecycleMapping) session.lookup( LifecycleMapping.ROLE, packaging ); optionalMojos = m.getOptionalMojos( lifecycle.getId() ); } catch ( ComponentLookupException e ) { getLog().debug( "Error looking up lifecycle mapping to retrieve optional mojos. Lifecycle ID: " + lifecycle.getId() + ". Error: " + e.getMessage(), e ); } } if ( optionalMojos == null ) { optionalMojos = Collections.emptyList(); } return optionalMojos; } /** * Find extension. * * @param project the project * @param role the role * @param roleHint the role hint * @param settings the settings * @param localRepository the local repository * @return the object * @throws LifecycleExecutionException the lifecycle execution exception * @throws PluginNotFoundException the plugin not found exception */ private Object findExtension( MavenProject project, String role, String roleHint, Settings settings, ArtifactRepository localRepository ) throws LifecycleExecutionException, PluginNotFoundException { Object pluginComponent = null; for ( Iterator i = project.getBuildPlugins().iterator(); i.hasNext() && pluginComponent == null; ) { Plugin plugin = (Plugin) i.next(); if ( plugin.isExtensions() ) { loadPluginDescriptor( plugin, project, session ); // TODO: if moved to the plugin manager we // already have the descriptor from above // and so do can lookup the container // directly try { pluginComponent = pluginManager.getPluginComponent( plugin, role, roleHint ); } catch ( ComponentLookupException e ) { getLog().debug( "Unable to find the lifecycle component in the extension", e ); } catch ( PluginManagerException e ) { throw new LifecycleExecutionException( "Error getting extensions from the plugin '" + plugin.getKey() + "': " + e.getMessage(), e ); } } } return pluginComponent; } /** * Verify plugin. * * @param plugin the plugin * @param project the project * @param session the session * @return the plugin descriptor * @throws LifecycleExecutionException the lifecycle execution exception * @throws PluginNotFoundException the plugin not found exception */ private PluginDescriptor loadPluginDescriptor( Plugin plugin, MavenProject project, MavenSession session ) throws LifecycleExecutionException, PluginNotFoundException { PluginDescriptor pluginDescriptor; try { pluginDescriptor = pluginManager.loadPluginDescriptor( plugin, project, session ); } catch ( PluginManagerException e ) { throw new LifecycleExecutionException( "Internal error in the plugin manager getting plugin '" + plugin.getKey() + "': " + e.getMessage(), e ); } catch ( PluginVersionResolutionException e ) { throw new LifecycleExecutionException( e.getMessage(), e ); } catch ( InvalidVersionSpecificationException e ) { throw new LifecycleExecutionException( e.getMessage(), e ); } catch ( InvalidPluginException e ) { throw new LifecycleExecutionException( e.getMessage(), e ); } catch ( ArtifactNotFoundException e ) { throw new LifecycleExecutionException( e.getMessage(), e ); } catch ( ArtifactResolutionException e ) { throw new LifecycleExecutionException( e.getMessage(), e ); } catch ( PluginVersionNotFoundException e ) { throw new LifecycleExecutionException( e.getMessage(), e ); } return pluginDescriptor; } /** * Returns all the parent projects of the specified project, with the root project first. * * @param project The maven project to get the parents of * @return the parent projects of the specified project, with the root project first. * @throws org.apache.maven.plugin.MojoExecutionException * if the super-pom could not be created. * @since 1.0-alpha-1 */ private List<MavenProject> getParentProjects( MavenProject project ) throws MojoExecutionException { List<MavenProject> parents = new ArrayList<MavenProject>(); while ( project.getParent() != null ) { project = project.getParent(); parents.add( 0, project ); } return parents; } /* * NOTE: All the code following this point was scooped from the DefaultLifecycleExecutor. There must be a better way * but for now it should work. */ /** * Gets the phase to lifecycle map. * * @param lifecycles The list of lifecycles. * @return the phase to lifecycle map. * @throws LifecycleExecutionException the lifecycle execution exception. */ public Map getPhaseToLifecycleMap( List lifecycles ) throws LifecycleExecutionException { Map phaseToLifecycleMap = new HashMap(); for ( Iterator i = lifecycles.iterator(); i.hasNext(); ) { Lifecycle lifecycle = (Lifecycle) i.next(); for ( Iterator p = lifecycle.getPhases().iterator(); p.hasNext(); ) { String phase = (String) p.next(); if ( phaseToLifecycleMap.containsKey( phase ) ) { Lifecycle prevLifecycle = (Lifecycle) phaseToLifecycleMap.get( phase ); throw new LifecycleExecutionException( "Phase '" + phase + "' is defined in more than one lifecycle: '" + lifecycle.getId() + "' and '" + prevLifecycle.getId() + "'" ); } else { phaseToLifecycleMap.put( phase, lifecycle ); } } } return phaseToLifecycleMap; } /** * Returns the set of all plugins used by the project. * * @param superPomPluginManagement the super pom's pluginManagement plugins. * @param parentPluginManagement the parent pom's pluginManagement plugins. * @param parentBuildPlugins the parent pom's build plugins. * @param parentReportPlugins the parent pom's report plugins. * @param pluginsWithVersionsSpecified the plugin coords that have a version defined in the project. * @return the set of plugins used by the project. * @throws org.apache.maven.plugin.MojoExecutionException * if things go wrong. */ private Set<Plugin> getProjectPlugins( Map<String, String> superPomPluginManagement, Map<String, String> parentPluginManagement, Map<String, String> parentBuildPlugins, Map<String, String> parentReportPlugins, Set<String> pluginsWithVersionsSpecified ) throws MojoExecutionException { Map<String, Plugin> plugins = new HashMap<String, Plugin>(); getLog().debug( "Building list of project plugins..." ); if ( getLog().isDebugEnabled() ) { StringWriter origModel = new StringWriter(); try { origModel.write( "Original model:\n" ); getProject().writeOriginalModel( origModel ); getLog().debug( origModel.toString() ); } catch ( IOException e ) { // ignore } } debugVersionMap( "super-pom version map", superPomPluginManagement ); debugVersionMap( "parent version map", parentPluginManagement ); Map<String, String> excludePluginManagement = new HashMap<String, String>( superPomPluginManagement ); excludePluginManagement.putAll( parentPluginManagement ); debugVersionMap( "aggregate version map", excludePluginManagement ); excludePluginManagement.keySet().removeAll( pluginsWithVersionsSpecified ); debugVersionMap( "final aggregate version map", excludePluginManagement ); Model originalModel; try { originalModel = modelInterpolator.interpolate( getProject().getOriginalModel(), getProject().getBasedir(), new DefaultProjectBuilderConfiguration().setExecutionProperties( getProject().getProperties() ), true ); } catch ( ModelInterpolationException e ) { throw new MojoExecutionException( e.getMessage(), e ); } try { addProjectPlugins( plugins, originalModel.getBuild().getPluginManagement().getPlugins(), excludePluginManagement ); } catch ( NullPointerException e ) { // guess there are no plugins here } debugPluginMap( "after adding local pluginManagement", plugins ); try { List<Plugin> lifecyclePlugins = new ArrayList<Plugin>( getLifecyclePlugins( getProject() ).values() ); for ( Iterator<Plugin> i = lifecyclePlugins.iterator(); i.hasNext(); ) { Plugin lifecyclePlugin = i.next(); if ( getPluginVersion( lifecyclePlugin ) != null ) { // version comes from lifecycle, therefore cannot modify i.remove(); } else { // lifecycle leaves version open String parentVersion = parentPluginManagement.get( getPluginCoords( lifecyclePlugin ) ); if ( parentVersion != null ) { // parent controls version i.remove(); } } } addProjectPlugins( plugins, lifecyclePlugins, parentPluginManagement ); debugPluginMap( "after adding lifecycle plugins", plugins ); } catch ( NullPointerException e ) { // using maven 3.x or newer } try { List<Plugin> buildPlugins = new ArrayList<Plugin>( originalModel.getBuild().getPlugins() ); for ( Iterator<Plugin> i = buildPlugins.iterator(); i.hasNext(); ) { Plugin buildPlugin = i.next(); if ( getPluginVersion( buildPlugin ) == null ) { String parentVersion = parentPluginManagement.get( getPluginCoords( buildPlugin ) ); if ( parentVersion != null ) { // parent controls version i.remove(); } } } addProjectPlugins( plugins, buildPlugins, parentBuildPlugins ); } catch ( NullPointerException e ) { // guess there are no plugins here } debugPluginMap( "after adding build plugins", plugins ); try { List<ReportPlugin> reportPlugins = new ArrayList<ReportPlugin>( originalModel.getReporting().getPlugins() ); for ( Iterator<ReportPlugin> i = reportPlugins.iterator(); i.hasNext(); ) { ReportPlugin reportPlugin = i.next(); if ( getPluginVersion( reportPlugin ) == null ) { String parentVersion = parentPluginManagement.get( getPluginCoords( reportPlugin ) ); if ( parentVersion != null ) { // parent controls version i.remove(); } } } addProjectPlugins( plugins, toPlugins( reportPlugins ), parentReportPlugins ); } catch ( NullPointerException e ) { // guess there are no plugins here } debugPluginMap( "after adding reporting plugins", plugins ); for ( Profile profile : originalModel.getProfiles() ) { try { addProjectPlugins( plugins, profile.getBuild().getPluginManagement().getPlugins(), excludePluginManagement ); } catch ( NullPointerException e ) { // guess there are no plugins here } debugPluginMap( "after adding build pluginManagement for profile " + profile.getId(), plugins ); try { addProjectPlugins( plugins, profile.getBuild().getPlugins(), parentBuildPlugins ); } catch ( NullPointerException e ) { // guess there are no plugins here } debugPluginMap( "after adding build plugins for profile " + profile.getId(), plugins ); try { addProjectPlugins( plugins, toPlugins( profile.getReporting().getPlugins() ), parentReportPlugins ); } catch ( NullPointerException e ) { // guess there are no plugins here } debugPluginMap( "after adding reporting plugins for profile " + profile.getId(), plugins ); } Set<Plugin> result = new TreeSet<Plugin>( new PluginComparator() ); result.addAll( plugins.values() ); return result; } /** * Adds those project plugins which are not inherited from the parent definitions to the list of plugins. * * @param plugins The list of plugins. * @param projectPlugins The project's plugins. * @param parentDefinitions The parent plugin definitions. * @since 1.0-alpha-1 */ private void addProjectPlugins( Map<String, Plugin> plugins, Collection<Plugin> projectPlugins, Map<String, String> parentDefinitions ) { for ( Plugin plugin : projectPlugins ) { String coord = getPluginCoords( plugin ); String version = getPluginVersion( plugin ); String parentVersion = parentDefinitions.get( coord ); if ( version == null && ( !plugins.containsKey( coord ) || getPluginVersion( plugins.get( coord ) ) == null ) && parentVersion != null ) { Plugin parentPlugin = new Plugin(); parentPlugin.setGroupId( getPluginGroupId( plugin ) ); parentPlugin.setArtifactId( getPluginArtifactId( plugin ) ); parentPlugin.setVersion( parentVersion ); plugins.put( coord, parentPlugin ); } else if ( parentVersion == null || !parentVersion.equals( version ) ) { if ( !plugins.containsKey( coord ) || getPluginVersion( plugins.get( coord ) ) == null ) { plugins.put( coord, plugin ); } } if ( !plugins.containsKey( coord ) ) { plugins.put( coord, plugin ); } } } /** * Logs at debug level a map of plugins keyed by versionless key. * * @param description log description * @param plugins a map with keys being the {@link String} corresponding to the versionless artifact key and * values being {@link Plugin} or {@link ReportPlugin}. */ private void debugPluginMap( String description, Map plugins ) { if ( getLog().isDebugEnabled() ) { Set sorted = new TreeSet( new PluginComparator() ); sorted.addAll( plugins.values() ); StringBuilder buf = new StringBuilder( description ); Iterator i = sorted.iterator(); while ( i.hasNext() ) { Object plugin = i.next(); buf.append( "\n " ); buf.append( getPluginCoords( plugin ) ); buf.append( ":" ); buf.append( getPluginVersion( plugin ) ); } getLog().debug( buf.toString() ); } } /** * Logs at debug level a map of plugin versions keyed by versionless key. * * @param description log description * @param plugins a map with keys being the {@link String} corresponding to the versionless artifact key and * values being {@link String} plugin version. */ private void debugVersionMap( String description, Map plugins ) { if ( getLog().isDebugEnabled() ) { StringBuilder buf = new StringBuilder( description ); Iterator i = plugins.entrySet().iterator(); while ( i.hasNext() ) { Map.Entry plugin = (Map.Entry) i.next(); buf.append( "\n " ); buf.append( plugin.getKey() ); buf.append( ":" ); buf.append( plugin.getValue() ); } getLog().debug( buf.toString() ); } } /** * Returns the coordinates of a plugin. * * @param plugin The plugin * @return The groupId and artifactId separated by a colon. * @since 1.0-alpha-1 */ private static String getPluginCoords( Object plugin ) { return getPluginGroupId( plugin ) + ":" + getPluginArtifactId( plugin ); } /** * Returns the ArtifactId of a {@link Plugin} or {@link ReportPlugin} * * @param plugin the {@link Plugin} or {@link ReportPlugin} * @return the ArtifactId of the {@link Plugin} or {@link ReportPlugin} * @since 1.0-alpha-1 */ private static String getPluginArtifactId( Object plugin ) { return plugin instanceof ReportPlugin ? ( (ReportPlugin) plugin ).getArtifactId() : ( (Plugin) plugin ).getArtifactId(); } private static Plugin toPlugin( ReportPlugin reportPlugin ) { Plugin plugin = new Plugin(); plugin.setGroupId( reportPlugin.getGroupId() ); plugin.setArtifactId( reportPlugin.getArtifactId() ); plugin.setVersion( reportPlugin.getVersion() ); return plugin; } private static ReportPlugin toReportPlugin( Plugin plugin ) { ReportPlugin reportPlugin = new ReportPlugin(); reportPlugin.setGroupId( plugin.getGroupId() ); reportPlugin.setArtifactId( plugin.getArtifactId() ); reportPlugin.setVersion( plugin.getVersion() ); return reportPlugin; } private static Set<Plugin> toPlugins( Set<ReportPlugin> reportPlugins ) { Set<Plugin> result; if ( reportPlugins instanceof LinkedHashSet ) { result = new LinkedHashSet<Plugin>( reportPlugins.size() ); } else if ( reportPlugins instanceof SortedSet ) { final Comparator<? super ReportPlugin> comparator = ( (SortedSet<ReportPlugin>) reportPlugins ).comparator(); result = new TreeSet<Plugin>( new Comparator<Plugin>() { public int compare( Plugin o1, Plugin o2 ) { return comparator.compare( toReportPlugin( o1 ), toReportPlugin( o2 ) ); } } ); } else { result = new HashSet<Plugin>( reportPlugins.size() ); } for ( ReportPlugin reportPlugin : reportPlugins ) { result.add( toPlugin( reportPlugin ) ); } return result; } private static List<Plugin> toPlugins( List<ReportPlugin> reportPlugins ) { List<Plugin> result = new ArrayList<Plugin>( reportPlugins.size() ); for ( ReportPlugin reportPlugin : reportPlugins ) { result.add( toPlugin( reportPlugin ) ); } return result; } private static Collection<Plugin> toPlugins( Collection<ReportPlugin> reportPlugins ) { if ( reportPlugins instanceof Set ) { return toPlugins( (Set<ReportPlugin>) reportPlugins ); } if ( reportPlugins instanceof List ) { return toPlugins( (List<ReportPlugin>) reportPlugins ); } return toPlugins( new ArrayList<ReportPlugin>( reportPlugins ) ); } /** * Returns the GroupId of a {@link Plugin} or {@link ReportPlugin} * * @param plugin the {@link Plugin} or {@link ReportPlugin} * @return the GroupId of the {@link Plugin} or {@link ReportPlugin} * @since 1.0-alpha-1 */ private static String getPluginGroupId( Object plugin ) { return plugin instanceof ReportPlugin ? ( (ReportPlugin) plugin ).getGroupId() : ( (Plugin) plugin ).getGroupId(); } /** * Returns the Version of a {@link Plugin} or {@link ReportPlugin} * * @param plugin the {@link Plugin} or {@link ReportPlugin} * @return the Version of the {@link Plugin} or {@link ReportPlugin} * @since 1.0-alpha-1 */ private static String getPluginVersion( Object plugin ) { return plugin instanceof ReportPlugin ? ( (ReportPlugin) plugin ).getVersion() : ( (Plugin) plugin ).getVersion(); } /** * Gets the report plugins of a specific project. * * @param model the model to get the report plugins from. * @param onlyIncludeInherited <code>true</code> to only return the plugins definitions that will be * inherited by child projects. * @return The map of effective plugin versions keyed by coordinates. * @since 1.0-alpha-1 */ private Map<String, String> getReportPlugins( Model model, boolean onlyIncludeInherited ) { Map<String, String> reportPlugins = new HashMap<String, String>(); try { for ( ReportPlugin plugin : model.getReporting().getPlugins() ) { String coord = getPluginCoords( plugin ); String version = getPluginVersion( plugin ); if ( version != null && ( !onlyIncludeInherited || getPluginInherited( plugin ) ) ) { reportPlugins.put( coord, version ); } } } catch ( NullPointerException e ) { // guess there are no plugins here } try { for ( Profile profile : model.getProfiles() ) { try { for ( ReportPlugin plugin : profile.getReporting().getPlugins() ) { String coord = getPluginCoords( plugin ); String version = getPluginVersion( plugin ); if ( version != null && ( !onlyIncludeInherited || getPluginInherited( plugin ) ) ) { reportPlugins.put( coord, version ); } } } catch ( NullPointerException e ) { // guess there are no plugins here } } } catch ( NullPointerException e ) { // guess there are no profiles here } return reportPlugins; } /** * @param pom the pom to update. * @throws MojoExecutionException when things go wrong * @throws MojoFailureException when things go wrong in a very bad way * @throws XMLStreamException when things go wrong with XML streaming * @see AbstractVersionsUpdaterMojo#update(ModifiedPomXMLEventReader) * @since 1.0-alpha-1 */ protected void update( ModifiedPomXMLEventReader pom ) throws MojoExecutionException, MojoFailureException, XMLStreamException { // do nothing } }
[MVERSIONS-207] No longer print "missing version #" warnings for plugins defined via parent <pluginManagement/> Submitted by Glen Mazza. git-svn-id: df642a57b9f2e77ee4dd3a375e98e3d2af96799d@17824 52ab4f32-60fc-0310-b215-8acea882cd1b
src/main/java/org/codehaus/mojo/versions/DisplayPluginUpdatesMojo.java
[MVERSIONS-207] No longer print "missing version #" warnings for plugins defined via parent <pluginManagement/> Submitted by Glen Mazza.
<ide><path>rc/main/java/org/codehaus/mojo/versions/DisplayPluginUpdatesMojo.java <ide> if ( version == null || !pluginsWithVersionsSpecified.contains( coords ) ) <ide> { <ide> version = (String) superPomPluginManagement.get( ArtifactUtils.versionlessKey( artifact ) ); <add> Boolean fromSuperPom = (version != null); <ide> getLog().debug( "[" + coords + "].superPom.version=" + version ); <ide> <ide> newVersion = artifactVersion != null <ide> ? artifactVersion.toString() <del> : ( version != null ? version : ( effectiveVersion != null ? effectiveVersion : "(unknown)" ) ); <del> StringBuilder buf = new StringBuilder( compactKey( groupId, artifactId ) ); <del> buf.append( ' ' ); <del> int padding = <del> WARN_PAD_SIZE - effectiveVersion.length() - ( version != null ? FROM_SUPER_POM.length() : 0 ); <del> while ( buf.length() < padding ) <del> { <del> buf.append( '.' ); <del> } <del> buf.append( ' ' ); <del> if ( version != null ) <del> { <del> buf.append( FROM_SUPER_POM ); <del> superPomDrivingMinVersion = true; <del> } <del> buf.append( effectiveVersion ); <del> lockdowns.add( buf.toString() ); <add> : ( fromSuperPom ? version : ( effectiveVersion != null ? effectiveVersion : "(unknown)" ) ); <add> if ( fromSuperPom || "(unknown)".equals(newVersion) ) { <add> StringBuilder buf = new StringBuilder( compactKey( groupId, artifactId ) ); <add> buf.append( ' ' ); <add> int padding = <add> WARN_PAD_SIZE - effectiveVersion.length() - ( fromSuperPom ? FROM_SUPER_POM.length() : 0 ); <add> while ( buf.length() < padding ) <add> { <add> buf.append( '.' ); <add> } <add> buf.append( ' ' ); <add> if ( fromSuperPom ) <add> { <add> buf.append( FROM_SUPER_POM ); <add> superPomDrivingMinVersion = true; <add> } <add> buf.append( effectiveVersion ); <add> lockdowns.add( buf.toString() ); <add> } <ide> } <ide> else if ( artifactVersion != null ) <ide> {
Java
apache-2.0
0bb16cf64f086f59171fca99adeec9458158447c
0
Gebon/jsflight,d0k1/jsflight,Gebon/jsflight,d0k1/jsflight,Gebon/jsflight,d0k1/jsflight,Gebon/jsflight,d0k1/jsflight
package com.focusit.jsflight.recorder.internalevent; import java.io.*; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.zip.GZIPOutputStream; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.FastOutput; /** * Recorder for special server event that must be recorded to get correct overall recording. * For example if you record only user interaction and miss same important server state changes, * so it might get very hard to replay that recording * <p> * Created by doki on 30.07.16. */ public class InternalEventRecorder { private static final InternalEventRecorder instance = new InternalEventRecorder(); private final int maxElementsBeforeFlush; private final boolean storeInGzip; private ArrayBlockingQueue<InternalEventRecord> records; private AtomicLong lastId = new AtomicLong(-1); private AtomicLong timestampNs = new AtomicLong(0); private AtomicBoolean recording = new AtomicBoolean(false); private volatile String eventsFilename = "internal.data"; private StorageThread storageThread; private AtomicBoolean shuttingDown = new AtomicBoolean(false); private AtomicBoolean newFile = new AtomicBoolean(false); private WallClock wallClock = new WallClock(); private InternalEventRecorder() { this(-1, 4096, "internal-event-storage", false); } private InternalEventRecorder(int maxElementsBeforeFlush, int maxQueueSize, String storagePrefix, boolean storeInGzip) { this.maxElementsBeforeFlush = maxElementsBeforeFlush; this.records = new ArrayBlockingQueue<>(maxQueueSize); this.storeInGzip = storeInGzip; this.storageThread = new StorageThread(storagePrefix); wallClock.start(); storageThread.start(); } public static InternalEventRecorder getInstance() { return instance; } public static InternalEventRecorder build(int maxElementsBeforeFlush, int maxQueueSize, String storagePrefix, boolean storeInGzip) { return new InternalEventRecorder(maxElementsBeforeFlush, maxQueueSize, storagePrefix, storeInGzip); } public long getWallTime() { return timestampNs.get(); } public void openFileForWriting(String filename) { this.eventsFilename = filename; storageThread.openFileForWriting(); } public void push(String tag, Object data) throws UnsupportedEncodingException, InterruptedException { if (!recording.get()) { return; } InternalEventRecord record = new InternalEventRecord(); record.id = lastId.incrementAndGet(); String tagValue = tag.trim(); if (!tagValue.isEmpty()) { tagValue.getChars(0, tagValue.length() > 64 ? 64 : tagValue.length(), record.tag, 0); } if (data != null) { record.data = data; } record.timestampNs = timestampNs.get(); records.put(record); } public void shutdown() throws InterruptedException { shuttingDown.set(true); storageThread.join(2000); wallClock.join(2000); storageThread.flush(); } public void recordToNewFile() { storageThread.toNewFile(); } public void startRecording() { recording.set(true); } public void stopRecording() { recording.set(false); } public void setWallClockInterval(long interval) { this.wallClock.setNewInterval(interval); } /** * Internal event representation */ public static class InternalEventRecord { public long id; public long timestampNs; public char tag[] = new char[64]; public Object data; } class StorageThread extends Thread { private Kryo kryo; private FastOutput output; private int filesCounter = 1; public StorageThread(String storagePrefix) { super(storagePrefix); setPriority(NORM_PRIORITY); kryo = new Kryo(); } public void flush() { output.flush(); } public void openFileForWriting() { openFile(eventsFilename); } private void openFile(String fileName) { try { File destinationFile = new File(fileName); System.out.println("Storing internal events to " + destinationFile.getAbsolutePath()); FileOutputStream fos = new FileOutputStream(fileName); OutputStream out = storeInGzip ? new GZIPOutputStream(fos) : fos; output = new FastOutput(out); } catch (IOException e) { e.printStackTrace(); } } public void toNewFile() { newFile.set(true); } private void reOpenFile() { try { output.close(); openFile(eventsFilename + filesCounter++); } finally { newFile.set(false); } } @Override public void run() { boolean needFlush = false; int flushedObjects = 0; while (isAlive() && !isInterrupted() && !shuttingDown.get()) { try { if (recording.get()) { InternalEventRecord record; if (flushedObjects != maxElementsBeforeFlush && (record = records.poll()) != null) { kryo.writeObject(output, record); needFlush = true; flushedObjects++; yield(); } else { if (needFlush) { output.flush(); flushedObjects = 0; needFlush = false; } if (newFile.get()) { reOpenFile(); } sleep(100); } } else { sleep(1000); } } catch (Exception e) { // no Exception could break this thread. only Error } } } } class WallClock extends Thread { //defaults to 10 milliseconds private long interval = 10; public WallClock() { super("internal-event-clock"); setPriority(MAX_PRIORITY); } public void setNewInterval(long interval) { this.interval = interval; } @Override public void run() { while (isAlive() && !isInterrupted() && !shuttingDown.get()) { timestampNs.set(System.nanoTime()); try { if (interval <= 0) { Thread.yield(); } else { Thread.sleep(interval); } } catch (InterruptedException e) { break; } } } } }
recorder/src/main/java/com/focusit/jsflight/recorder/internalevent/InternalEventRecorder.java
package com.focusit.jsflight.recorder.internalevent; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.FastOutput; /** * Recorder for special server event that must be recorded to get correct overall recording. * For example if you record only user interaction and miss same important server state changes, * so it might get very hard to replay that recording * <p> * Created by doki on 30.07.16. */ public class InternalEventRecorder { private static final InternalEventRecorder instance = new InternalEventRecorder(); private final int maxElementsBeforeFlush; private ArrayBlockingQueue<InternalEventRecord> records; private AtomicLong lastId = new AtomicLong(-1); private AtomicLong timestampNs = new AtomicLong(0); private AtomicBoolean recording = new AtomicBoolean(false); private volatile String eventsFilename = "internal.data"; private StorageThread storageThread; private AtomicBoolean shuttingDown = new AtomicBoolean(false); private AtomicBoolean newFile = new AtomicBoolean(false); private WallClock wallClock = new WallClock(); private InternalEventRecorder() { this(-1, 4096, "internal-event-storage"); } private InternalEventRecorder(int maxElementsBeforeFlush, int maxQueueSize, String storagePrefix) { this.maxElementsBeforeFlush = maxElementsBeforeFlush; this.records = new ArrayBlockingQueue<>(maxQueueSize); this.storageThread = new StorageThread(storagePrefix); wallClock.start(); storageThread.start(); } public static InternalEventRecorder getInstance() { return instance; } public static InternalEventRecorder build(int maxElementsBeforeFlush, int maxQueueSize, String storagePrefix) { return new InternalEventRecorder(maxElementsBeforeFlush, maxQueueSize, storagePrefix); } public long getWallTime() { return timestampNs.get(); } public void openFileForWriting(String filename) { this.eventsFilename = filename; storageThread.openFileForWriting(); } public void push(String tag, Object data) throws UnsupportedEncodingException, InterruptedException { if (!recording.get()) { return; } InternalEventRecord record = new InternalEventRecord(); record.id = lastId.incrementAndGet(); String tagValue = tag.trim(); if (!tagValue.isEmpty()) { tagValue.getChars(0, tagValue.length() > 64 ? 64 : tagValue.length(), record.tag, 0); } if (data != null) { record.data = data; } record.timestampNs = timestampNs.get(); records.put(record); } public void shutdown() throws InterruptedException { shuttingDown.set(true); storageThread.join(2000); wallClock.join(2000); storageThread.flush(); } public void recordToNewFile() { storageThread.toNewFile(); } public void startRecording() { recording.set(true); } public void stopRecording() { recording.set(false); } public void setWallClockInterval(long interval) { this.wallClock.setNewInterval(interval); } /** * Internal event representation */ public static class InternalEventRecord { public long id; public long timestampNs; public char tag[] = new char[64]; public Object data; } class StorageThread extends Thread { private Kryo kryo; private FastOutput output; private int filesCounter = 1; public StorageThread(String storagePrefix) { super(storagePrefix); setPriority(NORM_PRIORITY); kryo = new Kryo(); } public void flush() { output.flush(); } public void openFileForWriting() { openFile(eventsFilename); } private void openFile(String fileName) { try { File destinationFile = new File(fileName); System.out.println("Storing internal events to " + destinationFile.getAbsolutePath()); output = new FastOutput(new FileOutputStream(fileName)); } catch (IOException e) { e.printStackTrace(); } } public void toNewFile() { newFile.set(true); } private void reOpenFile() { try { output.close(); openFile(eventsFilename + filesCounter++); } finally { newFile.set(false); } } @Override public void run() { boolean needFlush = false; int flushedObjects = 0; while (isAlive() && !isInterrupted() && !shuttingDown.get()) { try { if (recording.get()) { InternalEventRecord record; if (flushedObjects != maxElementsBeforeFlush && (record = records.poll()) != null) { kryo.writeObject(output, record); needFlush = true; flushedObjects++; yield(); } else { if (needFlush) { output.flush(); flushedObjects = 0; needFlush = false; } if (newFile.get()) { reOpenFile(); } sleep(100); } } else { sleep(1000); } } catch (Exception e) { // no Exception could break this thread. only Error } } } } class WallClock extends Thread { //defaults to 10 milliseconds private long interval = 10; public WallClock() { super("internal-event-clock"); setPriority(MAX_PRIORITY); } public void setNewInterval(long interval) { this.interval = interval; } @Override public void run() { while (isAlive() && !isInterrupted() && !shuttingDown.get()) { timestampNs.set(System.nanoTime()); try { if (interval <= 0) { Thread.yield(); } else { Thread.sleep(interval); } } catch (InterruptedException e) { break; } } } } }
ability to store in gzip
recorder/src/main/java/com/focusit/jsflight/recorder/internalevent/InternalEventRecorder.java
ability to store in gzip
<ide><path>ecorder/src/main/java/com/focusit/jsflight/recorder/internalevent/InternalEventRecorder.java <ide> package com.focusit.jsflight.recorder.internalevent; <ide> <del>import java.io.File; <del>import java.io.FileOutputStream; <del>import java.io.IOException; <del>import java.io.UnsupportedEncodingException; <add>import java.io.*; <ide> import java.util.concurrent.ArrayBlockingQueue; <ide> import java.util.concurrent.atomic.AtomicBoolean; <ide> import java.util.concurrent.atomic.AtomicLong; <add>import java.util.zip.GZIPOutputStream; <ide> <ide> import com.esotericsoftware.kryo.Kryo; <ide> import com.esotericsoftware.kryo.io.FastOutput; <ide> { <ide> private static final InternalEventRecorder instance = new InternalEventRecorder(); <ide> private final int maxElementsBeforeFlush; <add> private final boolean storeInGzip; <ide> private ArrayBlockingQueue<InternalEventRecord> records; <ide> private AtomicLong lastId = new AtomicLong(-1); <ide> private AtomicLong timestampNs = new AtomicLong(0); <ide> <ide> private InternalEventRecorder() <ide> { <del> this(-1, 4096, "internal-event-storage"); <del> } <del> <del> private InternalEventRecorder(int maxElementsBeforeFlush, int maxQueueSize, String storagePrefix) <add> this(-1, 4096, "internal-event-storage", false); <add> } <add> <add> private InternalEventRecorder(int maxElementsBeforeFlush, int maxQueueSize, String storagePrefix, <add> boolean storeInGzip) <ide> { <ide> this.maxElementsBeforeFlush = maxElementsBeforeFlush; <ide> this.records = new ArrayBlockingQueue<>(maxQueueSize); <add> this.storeInGzip = storeInGzip; <ide> this.storageThread = new StorageThread(storagePrefix); <ide> wallClock.start(); <ide> storageThread.start(); <ide> return instance; <ide> } <ide> <del> public static InternalEventRecorder build(int maxElementsBeforeFlush, int maxQueueSize, String storagePrefix) <del> { <del> return new InternalEventRecorder(maxElementsBeforeFlush, maxQueueSize, storagePrefix); <add> public static InternalEventRecorder build(int maxElementsBeforeFlush, int maxQueueSize, String storagePrefix, <add> boolean storeInGzip) <add> { <add> return new InternalEventRecorder(maxElementsBeforeFlush, maxQueueSize, storagePrefix, storeInGzip); <ide> } <ide> <ide> public long getWallTime() <ide> { <ide> File destinationFile = new File(fileName); <ide> System.out.println("Storing internal events to " + destinationFile.getAbsolutePath()); <del> output = new FastOutput(new FileOutputStream(fileName)); <add> FileOutputStream fos = new FileOutputStream(fileName); <add> OutputStream out = storeInGzip ? new GZIPOutputStream(fos) : fos; <add> output = new FastOutput(out); <ide> } <ide> catch (IOException e) <ide> {
Java
mpl-2.0
20c822a1b80819c77e051b9a44aec42a052dc5f5
0
msteinhoff/hello-world
73499c42-cb8e-11e5-bb14-00264a111016
src/main/java/HelloWorld.java
733f556e-cb8e-11e5-b45d-00264a111016
Hey we can now do a thing
src/main/java/HelloWorld.java
Hey we can now do a thing
<ide><path>rc/main/java/HelloWorld.java <del>733f556e-cb8e-11e5-b45d-00264a111016 <add>73499c42-cb8e-11e5-bb14-00264a111016
JavaScript
mit
9aad2a0de9f58401367610cd7d53233d6eb89125
0
heintsi/rpi-climate-sensor
var _merge = require('lodash.merge'), path = require('path'), lowdb = require('lowdb') module.exports = new function() { var db = lowdb(path.resolve(__dirname) + '/data.json') var collectionKey = 'data' db(collectionKey) this.add = function(data) { var entry = _merge({}, data, { timestamp: new Date().toISOString() } ) db.object[collectionKey].push(entry) db.save() } }
db.js
var _merge = require('lodash.merge'), path = require('path'), lowdb = require('lowdb') module.exports = new function() { var db = lowdb(path.resolve(__dirname) + '/data.json') var collectionKey = 'data' db(collectionKey) this.add = function(data) { var entry = _merge({}, data, { timestamp: new Date().getTime() } ) db.object[collectionKey].push(entry) db.save() } }
Change saved time format
db.js
Change saved time format
<ide><path>b.js <ide> <ide> this.add = function(data) { <ide> var entry = _merge({}, data, { <del> timestamp: new Date().getTime() <add> timestamp: new Date().toISOString() <ide> } <ide> ) <ide> db.object[collectionKey].push(entry)
Java
apache-2.0
ba2ea486aae08137db6d22d9fbaf645a25997d38
0
mesosphere/hdfs,Banno/hdfs,nalingarg2/hdfs,edgefox/hdfs,jan-zajic/mesos-hbase,jmlvanre/hdfs,mesosphere/hdfs,andrewrothstein/hdfs,Banno/hdfs,jan-zajic/mesos-hdfs,ryane/hdfs,dmitrypekar/hdfs,jan-zajic/mesos-hbase,dmitrypekar/hdfs,jan-zajic/mesos-hdfs,LLParse/hdfs,LLParse/hdfs,andrewrothstein/hdfs,nalingarg2/hdfs,kensipe/hdfs,edgefox/hdfs,jmlvanre/hdfs,smorin/hdfs,kensipe/hdfs,smorin/hdfs,ryane/hdfs
package org.apache.mesos.hdfs; import com.google.inject.Inject; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.mesos.MesosSchedulerDriver; import org.apache.mesos.Protos; import org.apache.mesos.Protos.*; import org.apache.mesos.SchedulerDriver; import org.apache.mesos.hdfs.config.SchedulerConf; import org.apache.mesos.hdfs.state.AcquisitionPhase; import org.apache.mesos.hdfs.state.LiveState; import org.apache.mesos.hdfs.state.PersistentState; import org.apache.mesos.hdfs.util.HDFSConstants; import org.apache.mesos.hdfs.util.DnsResolver; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.HashMap; import java.util.Timer; import java.util.TimerTask; import java.util.Collection; import java.util.Collections; import java.util.concurrent.ExecutionException; //TODO remove as much logic as possible from Scheduler to clean up code public class Scheduler implements org.apache.mesos.Scheduler, Runnable { public static final Log log = LogFactory.getLog(Scheduler.class); private final SchedulerConf conf; private final LiveState liveState; private final PersistentState persistentState; private final DnsResolver dnsResolver; private boolean reconciliationCompleted; @Inject public Scheduler(SchedulerConf conf, LiveState liveState, PersistentState persistentState) { this.conf = conf; this.liveState = liveState; this.persistentState = persistentState; this.dnsResolver = new DnsResolver(this, conf, persistentState); } @Override public void disconnected(SchedulerDriver driver) { log.info("Scheduler driver disconnected"); } @Override public void error(SchedulerDriver driver, String message) { log.error("Scheduler driver error: " + message); } @Override public void executorLost(SchedulerDriver driver, ExecutorID executorID, SlaveID slaveID, int status) { log.info("Executor lost: executorId=" + executorID.getValue() + " slaveId=" + slaveID.getValue() + " status=" + status); } @Override public void frameworkMessage(SchedulerDriver driver, ExecutorID executorID, SlaveID slaveID, byte[] data) { log.info("Framework message: executorId=" + executorID.getValue() + " slaveId=" + slaveID.getValue() + " data='" + Arrays.toString(data) + "'"); } @Override public void offerRescinded(SchedulerDriver driver, OfferID offerId) { log.info("Offer rescinded: offerId=" + offerId.getValue()); } @Override public void registered(SchedulerDriver driver, FrameworkID frameworkId, MasterInfo masterInfo) { try { persistentState.setFrameworkId(frameworkId); } catch (InterruptedException | ExecutionException e) { log.error("Error setting framework id in persistent state", e); throw new RuntimeException(e); } log.info("Registered framework frameworkId=" + frameworkId.getValue()); //reconcile tasks upon registration reconcileTasks(driver); } @Override public void reregistered(SchedulerDriver driver, MasterInfo masterInfo) { log.info("Reregistered framework: starting task reconciliation"); // reconcile tasks upon reregistration reconcileTasks(driver); } @Override public void statusUpdate(SchedulerDriver driver, TaskStatus status) { log.info(String.format( "Received status update for taskId=%s state=%s message='%s' stagingTasks.size=%d", status.getTaskId().getValue(), status.getState().toString(), status.getMessage(), liveState.getStagingTasksSize())); if (!isStagingState(status)) { liveState.removeStagingTask(status.getTaskId()); } if (isTerminalState(status)) { liveState.removeRunningTask(status.getTaskId()); persistentState.removeTaskId(status.getTaskId().getValue()); // Correct the phase when a task dies after the reconcile period is over if (reconciliationComplete()) { correctCurrentPhase(); } } else if (isRunningState(status)) { liveState.updateTaskForStatus(status); log.info(String.format("Current Acquisition Phase: %s", liveState .getCurrentAcquisitionPhase().toString())); switch (liveState.getCurrentAcquisitionPhase()) { case RECONCILING_TASKS : if (reconciliationComplete()) { correctCurrentPhase(); } break; case JOURNAL_NODES : if (liveState.getJournalNodeSize() == conf.getJournalNodeCount()) { correctCurrentPhase(); } break; case START_NAME_NODES : if (liveState.getNameNodeSize() == (HDFSConstants.TOTAL_NAME_NODES)) { // TODO move the reload to correctCurrentPhase and make it idempotent reloadConfigsOnAllRunningTasks(driver); correctCurrentPhase(); } break; case FORMAT_NAME_NODES : if (!liveState.isNameNode1Initialized() && !liveState.isNameNode2Initialized()) { dnsResolver.sendMessageAfterNNResolvable( driver, liveState.getFirstNameNodeTaskId(), liveState.getFirstNameNodeSlaveId(), HDFSConstants.NAME_NODE_INIT_MESSAGE); } else if (!liveState.isNameNode1Initialized()) { dnsResolver.sendMessageAfterNNResolvable( driver, liveState.getFirstNameNodeTaskId(), liveState.getFirstNameNodeSlaveId(), HDFSConstants.NAME_NODE_BOOTSTRAP_MESSAGE); } else if (!liveState.isNameNode2Initialized()) { dnsResolver.sendMessageAfterNNResolvable( driver, liveState.getSecondNameNodeTaskId(), liveState.getSecondNameNodeSlaveId(), HDFSConstants.NAME_NODE_BOOTSTRAP_MESSAGE); } else { correctCurrentPhase(); } break; // TODO (elingg) add a configurable number of data nodes case DATA_NODES : break; } } else { log.warn(String.format("Don't know how to handle state=%s for taskId=%s", status.getState(), status.getTaskId().getValue())); } } @Override public void resourceOffers(SchedulerDriver driver, List<Offer> offers) { log.info(String.format("Received %d offers", offers.size())); if (liveState.getCurrentAcquisitionPhase().equals(AcquisitionPhase.RECONCILING_TASKS) && reconciliationComplete()) { correctCurrentPhase(); } // TODO within each phase, accept offers based on the number of nodes you need boolean acceptedOffer = false; for (Offer offer : offers) { if (acceptedOffer) { driver.declineOffer(offer.getId()); } else { switch (liveState.getCurrentAcquisitionPhase()) { case RECONCILING_TASKS : log.info("Declining offers while reconciling tasks"); driver.declineOffer(offer.getId()); break; case JOURNAL_NODES : if (tryToLaunchJournalNode(driver, offer)) { acceptedOffer = true; } else { driver.declineOffer(offer.getId()); } break; case START_NAME_NODES : if (dnsResolver.journalNodesResolvable() && tryToLaunchNameNode(driver, offer)) { acceptedOffer = true; } else { driver.declineOffer(offer.getId()); } break; case FORMAT_NAME_NODES : driver.declineOffer(offer.getId()); break; case DATA_NODES : if (tryToLaunchDataNode(driver, offer)) { acceptedOffer = true; } else { driver.declineOffer(offer.getId()); } break; } } } } @Override public void slaveLost(SchedulerDriver driver, SlaveID slaveId) { log.info("Slave lost slaveId=" + slaveId.getValue()); } @Override public void run() { FrameworkInfo.Builder frameworkInfo = FrameworkInfo.newBuilder() .setName(conf.getFrameworkName()) .setFailoverTimeout(conf.getFailoverTimeout()) .setUser(conf.getHdfsUser()) .setRole(conf.getHdfsRole()) .setCheckpoint(true); try { FrameworkID frameworkID = persistentState.getFrameworkID(); if (frameworkID != null) { frameworkInfo.setId(frameworkID); } } catch (InterruptedException | ExecutionException | InvalidProtocolBufferException e) { log.error("Error recovering framework id", e); throw new RuntimeException(e); } MesosSchedulerDriver driver = new MesosSchedulerDriver(this, frameworkInfo.build(), conf.getMesosMasterUri()); driver.run(); } private boolean launchNode(SchedulerDriver driver, Offer offer, String nodeName, List<String> taskTypes, String executorName) { log.info(String.format("Launching node of type %s with tasks %s", nodeName, taskTypes.toString())); String taskIdName = String.format("%s.%s.%d", nodeName, executorName, System.currentTimeMillis()); List<Resource> resources = getExecutorResources(); ExecutorInfo executorInfo = createExecutor(taskIdName, nodeName, executorName, resources); List<TaskInfo> tasks = new ArrayList<>(); for (String taskType : taskTypes) { List<Resource> taskResources = getTaskResources(taskType); String taskName = getNodeName(taskType); if (taskName.isEmpty()) return false; TaskID taskId = TaskID.newBuilder() .setValue(String.format("task.%s.%s", taskType, taskIdName)) .build(); TaskInfo task = TaskInfo.newBuilder() .setExecutor(executorInfo) .setName(taskName) .setTaskId(taskId) .setSlaveId(offer.getSlaveId()) .addAllResources(taskResources) .setData(ByteString.copyFromUtf8( String.format("bin/hdfs-mesos-%s", taskType))) .build(); tasks.add(task); liveState.addStagingTask(task.getTaskId(), taskName); persistentState.addHdfsNode(taskId, offer.getHostname(), taskType); } driver.launchTasks(Arrays.asList(offer.getId()), tasks); return true; } private String getNodeName(String taskType) { if (taskType.equals(HDFSConstants.NAME_NODE_ID)) { for (int i = HDFSConstants.TOTAL_NAME_NODES; i > 0; i--) { if (!liveState.getNameNodeNames().containsValue(HDFSConstants.NAME_NODE_ID + i)) { return HDFSConstants.NAME_NODE_ID + i; } } return ""; // we couldn't find a node name, we must have started enough. } if (taskType.equals(HDFSConstants.JOURNAL_NODE_ID)) { for (int i = conf.getJournalNodeCount(); i > 0; i--) { if (!liveState.getJournalNodeNames().containsValue(HDFSConstants.JOURNAL_NODE_ID + i)) { return HDFSConstants.JOURNAL_NODE_ID + i; } } return ""; // we couldn't find a node name, we must have started enough. } return taskType; } private ExecutorInfo createExecutor(String taskIdName, String nodeName, String executorName, List<Resource> resources) { int confServerPort = conf.getConfigServerPort(); return ExecutorInfo .newBuilder() .setName(nodeName + " executor") .setExecutorId(ExecutorID.newBuilder().setValue("executor." + taskIdName).build()) .addAllResources(resources) .setCommand( CommandInfo .newBuilder() .addAllUris( Arrays.asList( CommandInfo.URI .newBuilder() .setValue( String.format("http://%s:%d/%s", conf.getFrameworkHostAddress(), confServerPort, HDFSConstants.HDFS_BINARY_FILE_NAME)) .build(), CommandInfo.URI .newBuilder() .setValue( String.format("http://%s:%d/%s", conf.getFrameworkHostAddress(), confServerPort, HDFSConstants.HDFS_CONFIG_FILE_NAME)) .build())) .setEnvironment(Environment.newBuilder() .addAllVariables(Arrays.asList( Environment.Variable.newBuilder() .setName("HADOOP_OPTS") .setValue(conf.getJvmOpts()).build(), Environment.Variable.newBuilder() .setName("HADOOP_HEAPSIZE") .setValue(String.format("%d", conf.getHadoopHeapSize())).build(), Environment.Variable.newBuilder() .setName("HADOOP_NAMENODE_OPTS") .setValue("-Xmx" + conf.getNameNodeHeapSize() + "m -Xms" + conf.getNameNodeHeapSize() + "m").build(), Environment.Variable.newBuilder() .setName("HADOOP_DATANODE_OPTS") .setValue("-Xmx" + conf.getDataNodeHeapSize() + "m -Xms" + conf.getDataNodeHeapSize() + "m").build(), Environment.Variable.newBuilder() .setName("EXECUTOR_OPTS") .setValue("-Xmx" + conf.getExecutorHeap() + "m -Xms" + conf.getExecutorHeap() + "m").build()))) .setValue( "env ; cd hdfs-mesos-* && " + "exec `if [ -z \"$JAVA_HOME\" ]; then echo java; " + "else echo $JAVA_HOME/bin/java; fi` " + "$HADOOP_OPTS " + "$EXECUTOR_OPTS " + "-cp lib/*.jar org.apache.mesos.hdfs.executor." + executorName).build()) .build(); } private List<Resource> getExecutorResources() { return Arrays.asList( Resource.newBuilder() .setName("cpus") .setType(Value.Type.SCALAR) .setScalar(Value.Scalar.newBuilder() .setValue(conf.getExecutorCpus()).build()) .setRole(conf.getHdfsRole()) .build(), Resource.newBuilder() .setName("mem") .setType(Value.Type.SCALAR) .setScalar(Value.Scalar.newBuilder() .setValue(conf.getExecutorHeap() * conf.getJvmOverhead()).build()) .setRole(conf.getHdfsRole()) .build()); } private List<Resource> getTaskResources(String taskName) { return Arrays.asList( Resource.newBuilder() .setName("cpus") .setType(Value.Type.SCALAR) .setScalar(Value.Scalar.newBuilder() .setValue(conf.getTaskCpus(taskName)).build()) .setRole(conf.getHdfsRole()) .build(), Resource.newBuilder() .setName("mem") .setType(Value.Type.SCALAR) .setScalar(Value.Scalar.newBuilder() .setValue(conf.getTaskHeapSize(taskName)).build()) .setRole(conf.getHdfsRole()) .build()); } private boolean tryToLaunchJournalNode(SchedulerDriver driver, Offer offer) { if (offerNotEnoughResources(offer, conf.getJournalNodeCpus(), conf.getJournalNodeHeapSize())) { log.info("Offer does not have enough resources"); return false; } boolean launch = false; List<String> deadJournalNodes = persistentState.getDeadJournalNodes(); log.info(deadJournalNodes); if (deadJournalNodes.isEmpty()) { if (liveState.getJournalNodeSize() == conf.getJournalNodeCount()) { log.info(String.format("Already running %s journalnodes", conf.getJournalNodeCount())); } else if (persistentState.journalNodeRunningOnSlave(offer.getHostname())) { log.info(String.format("Already running journalnode on %s", offer.getHostname())); } else if (persistentState.dataNodeRunningOnSlave(offer.getHostname())) { log.info(String.format("Cannot colocate journalnode and datanode on %s", offer.getHostname())); } else { launch = true; } } else if (deadJournalNodes.contains(offer.getHostname())) { // TODO (elingg) we don't want to wait forever to launch a dead JN/ add a time out launch = true; } if (launch) { return launchNode( driver, offer, HDFSConstants.JOURNAL_NODE_ID, Arrays.asList(HDFSConstants.JOURNAL_NODE_ID), HDFSConstants.NODE_EXECUTOR_ID); } return false; } private boolean tryToLaunchNameNode(SchedulerDriver driver, Offer offer) { if (offerNotEnoughResources(offer, (conf.getNameNodeCpus() + conf.getZkfcCpus()), (conf.getNameNodeHeapSize() + conf.getZkfcHeapSize()))) { log.info("Offer does not have enough resources"); return false; } boolean launch = false; List<String> deadNameNodes = persistentState.getDeadNameNodes(); if (deadNameNodes.isEmpty()) { if (liveState.getNameNodeSize() == HDFSConstants.TOTAL_NAME_NODES) { log.info(String.format("Already running %s namenodes", HDFSConstants.TOTAL_NAME_NODES)); } else if (persistentState.nameNodeRunningOnSlave(offer.getHostname())) { log.info(String.format("Already running namenode on %s", offer.getHostname())); } else if (persistentState.dataNodeRunningOnSlave(offer.getHostname())) { log.info(String.format("Cannot colocate namenode and datanode on %s", offer.getHostname())); } else if (!persistentState.journalNodeRunningOnSlave(offer.getHostname())) { log.info(String.format("We need to coloate the namenode with a journalnode and there is" + "no journalnode running on this host. %s", offer.getHostname())); } else { // TODO (elingg) we don't want to wait forever to launch a dead NN/ add a time out launch = true; } } else if (deadNameNodes.contains(offer.getHostname())) { launch = true; } if (launch) { return launchNode( driver, offer, HDFSConstants.NAME_NODE_ID, Arrays.asList(HDFSConstants.NAME_NODE_ID, HDFSConstants.ZKFC_NODE_ID), HDFSConstants.NAME_NODE_EXECUTOR_ID); } return false; } private boolean tryToLaunchDataNode(SchedulerDriver driver, Offer offer) { if (offerNotEnoughResources(offer, conf.getDataNodeCpus(), conf.getDataNodeHeapSize())) { log.info("Offer does not have enough resources"); return false; } boolean launch = false; List<String> deadDataNodes = persistentState.getDeadDataNodes(); if (deadDataNodes.isEmpty()) { if (persistentState.dataNodeRunningOnSlave(offer.getHostname()) || persistentState.nameNodeRunningOnSlave(offer.getHostname()) || persistentState.journalNodeRunningOnSlave(offer.getHostname())) { log.info(String.format("Already running hdfs task on %s", offer.getHostname())); } else { launch = true; } } else if (deadDataNodes.contains(offer.getHostname())) { // TODO (elingg) we don't want to wait forever to launch a dead DN/ add a timeout. Also, // DN's are not too important to recover due to replication if there is more than 1 launch = true; } if (launch) { return launchNode( driver, offer, HDFSConstants.DATA_NODE_ID, Arrays.asList(HDFSConstants.DATA_NODE_ID), HDFSConstants.NODE_EXECUTOR_ID); } return false; } public void sendMessageTo(SchedulerDriver driver, TaskID taskId, SlaveID slaveID, String message) { log.info(String.format("Sending message '%s' to taskId=%s, slaveId=%s", message, taskId.getValue(), slaveID.getValue())); String postfix = taskId.getValue(); postfix = postfix.substring(postfix.indexOf(".") + 1, postfix.length()); postfix = postfix.substring(postfix.indexOf(".") + 1, postfix.length()); driver.sendFrameworkMessage( ExecutorID.newBuilder().setValue("executor." + postfix).build(), slaveID, message.getBytes()); } private boolean isTerminalState(TaskStatus taskStatus) { return (taskStatus.getState().equals(TaskState.TASK_FAILED) || taskStatus.getState().equals(TaskState.TASK_FINISHED) || taskStatus.getState().equals(TaskState.TASK_KILLED) || taskStatus.getState().equals(TaskState.TASK_LOST) || taskStatus.getState().equals(TaskState.TASK_ERROR)); } private boolean isRunningState(TaskStatus taskStatus) { return (taskStatus.getState().equals(TaskState.TASK_RUNNING)); } private boolean isStagingState(TaskStatus taskStatus) { return (taskStatus.getState().equals(TaskState.TASK_STAGING)); } private void reloadConfigsOnAllRunningTasks(SchedulerDriver driver) { for (Protos.TaskStatus taskStatus : liveState.getRunningTasks().values()) { sendMessageTo(driver, taskStatus.getTaskId(), taskStatus.getSlaveId(), HDFSConstants.RELOAD_CONFIG); } } private void correctCurrentPhase() { if (liveState.getJournalNodeSize() < conf.getJournalNodeCount()) { liveState.transitionTo(AcquisitionPhase.JOURNAL_NODES); } else if (liveState.getNameNodeSize() < HDFSConstants.TOTAL_NAME_NODES) { liveState.transitionTo(AcquisitionPhase.START_NAME_NODES); } else if (!liveState.isNameNode1Initialized() || !liveState.isNameNode2Initialized()) { liveState.transitionTo(AcquisitionPhase.FORMAT_NAME_NODES); } else { liveState.transitionTo(AcquisitionPhase.DATA_NODES); } } private boolean offerNotEnoughResources(Offer offer, double cpus, int mem) { for (Resource offerResource : offer.getResourcesList()) { if (offerResource.getName().equals("cpus") && cpus > offerResource.getScalar().getValue()) { return true; } if (offerResource.getName().equals("mem") && mem > offerResource.getScalar().getValue()) { return true; } } return false; } private void reconcileTasks(SchedulerDriver driver) { // TODO run this method repeatedly with exponential backoff in the case that it takes time for // different slaves to reregister upon master failover. reconciliationCompleted = false; driver.reconcileTasks(Collections.<Protos.TaskStatus> emptyList()); Timer timer = new Timer(); timer.schedule(new ReconcileStateTask(), conf.getReconciliationTimeout() * 1000); } private boolean reconciliationComplete() { return reconciliationCompleted; } private class ReconcileStateTask extends TimerTask { @Override public void run() { log.info("Current persistent state:"); log.info(String.format("JournalNodes: %s", persistentState.getJournalNodes())); log.info(String.format("NameNodes: %s", persistentState.getNameNodes())); log.info(String.format("DataNodes: %s", persistentState.getDataNodes())); Collection<String> taskIds = persistentState.getAllTaskIds(); HashMap<String, Protos.TaskStatus> runningTaskIds = liveState.getRunningTasks(); for (String taskId : taskIds) { if (!runningTaskIds.containsKey(taskId)) persistentState.removeTaskId(taskId); } reconciliationCompleted = true; } } }
src/main/java/org/apache/mesos/hdfs/Scheduler.java
package org.apache.mesos.hdfs; import com.google.inject.Inject; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.mesos.MesosSchedulerDriver; import org.apache.mesos.Protos; import org.apache.mesos.Protos.*; import org.apache.mesos.SchedulerDriver; import org.apache.mesos.hdfs.config.SchedulerConf; import org.apache.mesos.hdfs.state.AcquisitionPhase; import org.apache.mesos.hdfs.state.LiveState; import org.apache.mesos.hdfs.state.PersistentState; import org.apache.mesos.hdfs.util.HDFSConstants; import org.apache.mesos.hdfs.util.DnsResolver; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.HashMap; import java.util.Timer; import java.util.TimerTask; import java.util.Collection; import java.util.Collections; import java.util.concurrent.ExecutionException; //TODO remove as much logic as possible from Scheduler to clean up code public class Scheduler implements org.apache.mesos.Scheduler, Runnable { public static final Log log = LogFactory.getLog(Scheduler.class); private final SchedulerConf conf; private final LiveState liveState; private final PersistentState persistentState; private final DnsResolver dnsResolver; private boolean reconciliationCompleted; @Inject public Scheduler(SchedulerConf conf, LiveState liveState, PersistentState persistentState) { this.conf = conf; this.liveState = liveState; this.persistentState = persistentState; this.dnsResolver = new DnsResolver(this, conf, persistentState); } @Override public void disconnected(SchedulerDriver driver) { log.info("Scheduler driver disconnected"); } @Override public void error(SchedulerDriver driver, String message) { log.error("Scheduler driver error: " + message); } @Override public void executorLost(SchedulerDriver driver, ExecutorID executorID, SlaveID slaveID, int status) { log.info("Executor lost: executorId=" + executorID.getValue() + " slaveId=" + slaveID.getValue() + " status=" + status); } @Override public void frameworkMessage(SchedulerDriver driver, ExecutorID executorID, SlaveID slaveID, byte[] data) { log.info("Framework message: executorId=" + executorID.getValue() + " slaveId=" + slaveID.getValue() + " data='" + Arrays.toString(data) + "'"); } @Override public void offerRescinded(SchedulerDriver driver, OfferID offerId) { log.info("Offer rescinded: offerId=" + offerId.getValue()); } @Override public void registered(SchedulerDriver driver, FrameworkID frameworkId, MasterInfo masterInfo) { try { persistentState.setFrameworkId(frameworkId); } catch (InterruptedException | ExecutionException e) { log.error("Error setting framework id in persistent state", e); throw new RuntimeException(e); } log.info("Registered framework frameworkId=" + frameworkId.getValue()); //reconcile tasks upon registration reconcileTasks(driver); } @Override public void reregistered(SchedulerDriver driver, MasterInfo masterInfo) { log.info("Reregistered framework: starting task reconciliation"); // reconcile tasks upon reregistration reconcileTasks(driver); } @Override public void statusUpdate(SchedulerDriver driver, TaskStatus status) { log.info(String.format( "Received status update for taskId=%s state=%s message='%s' stagingTasks.size=%d", status.getTaskId().getValue(), status.getState().toString(), status.getMessage(), liveState.getStagingTasksSize())); if (!isStagingState(status)) { liveState.removeStagingTask(status.getTaskId()); } if (isTerminalState(status)) { liveState.removeRunningTask(status.getTaskId()); persistentState.removeTaskId(status.getTaskId().getValue()); // Correct the phase when a task dies after the reconcile period is over if (reconciliationComplete()) { correctCurrentPhase(); } } else if (isRunningState(status)) { liveState.updateTaskForStatus(status); log.info(String.format("Current Acquisition Phase: %s", liveState .getCurrentAcquisitionPhase().toString())); switch (liveState.getCurrentAcquisitionPhase()) { case RECONCILING_TASKS : if (reconciliationComplete()) { correctCurrentPhase(); } break; case JOURNAL_NODES : if (liveState.getJournalNodeSize() == conf.getJournalNodeCount()) { correctCurrentPhase(); } break; case START_NAME_NODES : if (liveState.getNameNodeSize() == (HDFSConstants.TOTAL_NAME_NODES)) { // TODO move the reload to correctCurrentPhase and make it idempotent reloadConfigsOnAllRunningTasks(driver); correctCurrentPhase(); } break; case FORMAT_NAME_NODES : if (!liveState.isNameNode1Initialized() && !liveState.isNameNode2Initialized()) { dnsResolver.sendMessageAfterNNResolvable( driver, liveState.getFirstNameNodeTaskId(), liveState.getFirstNameNodeSlaveId(), HDFSConstants.NAME_NODE_INIT_MESSAGE); } else if (!liveState.isNameNode1Initialized()) { dnsResolver.sendMessageAfterNNResolvable( driver, liveState.getFirstNameNodeTaskId(), liveState.getFirstNameNodeSlaveId(), HDFSConstants.NAME_NODE_BOOTSTRAP_MESSAGE); } else if (!liveState.isNameNode2Initialized()) { dnsResolver.sendMessageAfterNNResolvable( driver, liveState.getSecondNameNodeTaskId(), liveState.getSecondNameNodeSlaveId(), HDFSConstants.NAME_NODE_BOOTSTRAP_MESSAGE); } else { correctCurrentPhase(); } break; // TODO (elingg) add a configurable number of data nodes case DATA_NODES : break; } } else { log.warn(String.format("Don't know how to handle state=%s for taskId=%s", status.getState(), status.getTaskId().getValue())); } } @Override public void resourceOffers(SchedulerDriver driver, List<Offer> offers) { log.info(String.format("Received %d offers", offers.size())); if (liveState.getCurrentAcquisitionPhase().equals(AcquisitionPhase.RECONCILING_TASKS) && reconciliationComplete()) { correctCurrentPhase(); } // TODO within each phase, accept offers based on the number of nodes you need boolean acceptedOffer = false; for (Offer offer : offers) { if (acceptedOffer) { driver.declineOffer(offer.getId()); } else { switch (liveState.getCurrentAcquisitionPhase()) { case RECONCILING_TASKS : log.info("Declining offers while reconciling tasks"); driver.declineOffer(offer.getId()); break; case JOURNAL_NODES : if (tryToLaunchJournalNode(driver, offer)) { acceptedOffer = true; } else { driver.declineOffer(offer.getId()); } break; case START_NAME_NODES : if (dnsResolver.journalNodesResolvable() && tryToLaunchNameNode(driver, offer)) { acceptedOffer = true; } else { driver.declineOffer(offer.getId()); } break; case FORMAT_NAME_NODES : driver.declineOffer(offer.getId()); break; case DATA_NODES : if (tryToLaunchDataNode(driver, offer)) { acceptedOffer = true; } else { driver.declineOffer(offer.getId()); } break; } } } } @Override public void slaveLost(SchedulerDriver driver, SlaveID slaveId) { log.info("Slave lost slaveId=" + slaveId.getValue()); } @Override public void run() { FrameworkInfo.Builder frameworkInfo = FrameworkInfo.newBuilder() .setName(conf.getFrameworkName()) .setFailoverTimeout(conf.getFailoverTimeout()) .setUser(conf.getHdfsUser()) .setRole(conf.getHdfsRole()) .setCheckpoint(true); try { FrameworkID frameworkID = persistentState.getFrameworkID(); if (frameworkID != null) { frameworkInfo.setId(frameworkID); } } catch (InterruptedException | ExecutionException | InvalidProtocolBufferException e) { log.error("Error recovering framework id", e); throw new RuntimeException(e); } MesosSchedulerDriver driver = new MesosSchedulerDriver(this, frameworkInfo.build(), conf.getMesosMasterUri()); driver.run(); } private boolean launchNode(SchedulerDriver driver, Offer offer, String nodeName, List<String> taskTypes, String executorName) { log.info(String.format("Launching node of type %s with tasks %s", nodeName, taskTypes.toString())); String taskIdName = String.format("%s.%s.%d", nodeName, executorName, System.currentTimeMillis()); List<Resource> resources = getExecutorResources(); ExecutorInfo executorInfo = createExecutor(taskIdName, nodeName, executorName, resources); List<TaskInfo> tasks = new ArrayList<>(); for (String taskType : taskTypes) { List<Resource> taskResources = getTaskResources(taskType); String taskName = getNodeName(taskType); if (taskName.isEmpty()) return false; TaskID taskId = TaskID.newBuilder() .setValue(String.format("task.%s.%s", taskType, taskIdName)) .build(); TaskInfo task = TaskInfo.newBuilder() .setExecutor(executorInfo) .setName(taskName) .setTaskId(taskId) .setSlaveId(offer.getSlaveId()) .addAllResources(taskResources) .setData(ByteString.copyFromUtf8( String.format("bin/hdfs-mesos-%s", taskType))) .build(); tasks.add(task); liveState.addStagingTask(task.getTaskId(), taskName); persistentState.addHdfsNode(taskId, offer.getHostname(), taskType); } driver.launchTasks(Arrays.asList(offer.getId()), tasks); return true; } private String getNodeName(String taskType) { if (taskType.equals(HDFSConstants.NAME_NODE_ID)) { for (int i = HDFSConstants.TOTAL_NAME_NODES; i > 0; i--) { if (!liveState.getNameNodeNames().containsValue(HDFSConstants.NAME_NODE_ID + i)) { return HDFSConstants.NAME_NODE_ID + i; } } return ""; // we couldn't find a node name, we must have started enough. } if (taskType.equals(HDFSConstants.JOURNAL_NODE_ID)) { for (int i = conf.getJournalNodeCount(); i > 0; i--) { if (!liveState.getJournalNodeNames().containsValue(HDFSConstants.JOURNAL_NODE_ID + i)) { return HDFSConstants.JOURNAL_NODE_ID + i; } } return ""; // we couldn't find a node name, we must have started enough. } return taskType; } private ExecutorInfo createExecutor(String taskIdName, String nodeName, String executorName, List<Resource> resources) { int confServerPort = conf.getConfigServerPort(); return ExecutorInfo .newBuilder() .setName(nodeName + " executor") .setExecutorId(ExecutorID.newBuilder().setValue("executor." + taskIdName).build()) .addAllResources(resources) .setCommand( CommandInfo .newBuilder() .addAllUris( Arrays.asList( CommandInfo.URI .newBuilder() .setValue( String.format("http://%s:%d/%s", conf.getFrameworkHostAddress(), confServerPort, HDFSConstants.HDFS_BINARY_FILE_NAME)) .build(), CommandInfo.URI .newBuilder() .setValue( String.format("http://%s:%d/%s", conf.getFrameworkHostAddress(), confServerPort, HDFSConstants.HDFS_CONFIG_FILE_NAME)) .build())) .setEnvironment(Environment.newBuilder() .addAllVariables(Arrays.asList( Environment.Variable.newBuilder() .setName("HADOOP_OPTS") .setValue(conf.getJvmOpts()).build(), Environment.Variable.newBuilder() .setName("HADOOP_HEAPSIZE") .setValue(String.format("%d", conf.getHadoopHeapSize())).build(), Environment.Variable.newBuilder() .setName("HADOOP_NAMENODE_OPTS") .setValue("-Xmx" + conf.getNameNodeHeapSize() + "m -Xms" + conf.getNameNodeHeapSize() + "m").build(), Environment.Variable.newBuilder() .setName("HADOOP_DATANODE_OPTS") .setValue("-Xmx" + conf.getDataNodeHeapSize() + "m -Xms" + conf.getDataNodeHeapSize() + "m").build(), Environment.Variable.newBuilder() .setName("EXECUTOR_OPTS") .setValue("-Xmx" + conf.getExecutorHeap() + "m -Xms" + conf.getExecutorHeap() + "m").build()))) .setValue( "env ; cd hdfs-mesos-* && " + "exec `if [ -z \"$JAVA_HOME\" ]; then echo java; " + "else echo $JAVA_HOME/bin/java; fi` " + "$HADOOP_OPTS " + "$EXECUTOR_OPTS " + "-cp lib/*.jar org.apache.mesos.hdfs.executor." + executorName).build()) .build(); } private List<Resource> getExecutorResources() { return Arrays.asList( Resource.newBuilder() .setName("cpus") .setType(Value.Type.SCALAR) .setScalar(Value.Scalar.newBuilder() .setValue(conf.getExecutorCpus()).build()) .setRole(conf.getHdfsRole()) .build(), Resource.newBuilder() .setName("mem") .setType(Value.Type.SCALAR) .setScalar(Value.Scalar.newBuilder() .setValue(conf.getExecutorHeap() * conf.getJvmOverhead()).build()) .setRole(conf.getHdfsRole()) .build()); } private List<Resource> getTaskResources(String taskName) { return Arrays.asList( Resource.newBuilder() .setName("cpus") .setType(Value.Type.SCALAR) .setScalar(Value.Scalar.newBuilder() .setValue(conf.getTaskCpus(taskName)).build()) .setRole(conf.getHdfsRole()) .build(), Resource.newBuilder() .setName("mem") .setType(Value.Type.SCALAR) .setScalar(Value.Scalar.newBuilder() .setValue(conf.getTaskHeapSize(taskName)).build()) .setRole(conf.getHdfsRole()) .build()); } private boolean tryToLaunchJournalNode(SchedulerDriver driver, Offer offer) { if (offerNotEnoughResources(offer, conf.getJournalNodeCpus(), conf.getJournalNodeHeapSize())) { log.info("Offer does not have enough resources"); return false; } boolean launch = false; List<String> deadJournalNodes = persistentState.getDeadJournalNodes(); log.info(deadJournalNodes); if (deadJournalNodes.isEmpty()) { if (liveState.getJournalNodeSize() == conf.getJournalNodeCount()) { log.info(String.format("Already running %s journalnodes", conf.getJournalNodeCount())); } else if (persistentState.journalNodeRunningOnSlave(offer.getHostname())) { log.info(String.format("Already running journalnode on %s", offer.getHostname())); } else if (persistentState.dataNodeRunningOnSlave(offer.getHostname())) { log.info(String.format("Cannot colocate journalnode and datanode on %s", offer.getHostname())); } else { launch = true; } } else if (deadJournalNodes.contains(offer.getHostname())) { // TODO (elingg) we don't want to wait forever to launch a dead JN/ add a time out launch = true; } if (launch) { return launchNode( driver, offer, HDFSConstants.JOURNAL_NODE_ID, Arrays.asList(HDFSConstants.JOURNAL_NODE_ID), HDFSConstants.NODE_EXECUTOR_ID); } return false; } private boolean tryToLaunchNameNode(SchedulerDriver driver, Offer offer) { if (offerNotEnoughResources(offer, (conf.getNameNodeCpus() + conf.getZkfcCpus()), (conf.getNameNodeHeapSize() + conf.getZkfcHeapSize()))) { log.info("Offer does not have enough resources"); return false; } boolean launch = false; List<String> deadNameNodes = persistentState.getDeadNameNodes(); if (deadNameNodes.isEmpty()) { if (liveState.getNameNodeSize() == HDFSConstants.TOTAL_NAME_NODES) { log.info(String.format("Already running %s namenodes", HDFSConstants.TOTAL_NAME_NODES)); } else if (persistentState.nameNodeRunningOnSlave(offer.getHostname())) { log.info(String.format("Already running namenode on %s", offer.getHostname())); } else if (persistentState.dataNodeRunningOnSlave(offer.getHostname())) { log.info(String.format("Cannot colocate namenode and datanode on %s", offer.getHostname())); } else if (!persistentState.journalNodeRunningOnSlave(offer.getHostname())) { log.info(String.format("We need to coloate the namenode with a journalnode and there is" + "no journalnode running on this host. %s", offer.getHostname())); } else { // TODO (elingg) we don't want to wait forever to launch a dead NN/ add a time out launch = true; } } else if (deadNameNodes.contains(offer.getHostname())) { launch = true; } if (launch) { return launchNode( driver, offer, HDFSConstants.NAME_NODE_ID, Arrays.asList(HDFSConstants.NAME_NODE_ID, HDFSConstants.ZKFC_NODE_ID), HDFSConstants.NAME_NODE_EXECUTOR_ID); } return false; } private boolean tryToLaunchDataNode(SchedulerDriver driver, Offer offer) { if (offerNotEnoughResources(offer, conf.getDataNodeCpus(), conf.getDataNodeHeapSize())) { log.info("Offer does not have enough resources"); return false; } boolean launch = false; List<String> deadDataNodes = persistentState.getDeadDataNodes(); if (deadDataNodes.isEmpty()) { if (persistentState.dataNodeRunningOnSlave(offer.getHostname()) || persistentState.nameNodeRunningOnSlave(offer.getHostname()) || persistentState.journalNodeRunningOnSlave(offer.getHostname())) { log.info(String.format("Already running hdfs task on %s", offer.getHostname())); } else { launch = true; } } else if (deadDataNodes.contains(offer.getHostname())) { // TODO (elingg) we don't want to wait forever to launch a dead DN/ add a timeout. Also, // DN's are not too important to recover due to replication if there is more than 1 launch = true; } if (launch) { return launchNode( driver, offer, HDFSConstants.DATA_NODE_ID, Arrays.asList(HDFSConstants.DATA_NODE_ID), HDFSConstants.NODE_EXECUTOR_ID); } return false; } public void sendMessageTo(SchedulerDriver driver, TaskID taskId, SlaveID slaveID, String message) { log.info(String.format("Sending message '%s' to taskId=%s, slaveId=%s", message, taskId.getValue(), slaveID.getValue())); String postfix = taskId.getValue(); postfix = postfix.substring(postfix.indexOf(".") + 1, postfix.length()); postfix = postfix.substring(postfix.indexOf(".") + 1, postfix.length()); driver.sendFrameworkMessage( ExecutorID.newBuilder().setValue("executor." + postfix).build(), slaveID, message.getBytes()); } private boolean isTerminalState(TaskStatus taskStatus) { return (taskStatus.getState().equals(TaskState.TASK_FAILED) || taskStatus.getState().equals(TaskState.TASK_FINISHED) || taskStatus.getState().equals(TaskState.TASK_KILLED) || taskStatus.getState().equals(TaskState.TASK_LOST) || taskStatus.getState().equals(TaskState.TASK_ERROR)); } private boolean isRunningState(TaskStatus taskStatus) { return (taskStatus.getState().equals(TaskState.TASK_RUNNING)); } private boolean isStagingState(TaskStatus taskStatus) { return (taskStatus.getState().equals(TaskState.TASK_STAGING)); } private void reloadConfigsOnAllRunningTasks(SchedulerDriver driver) { for (Protos.TaskStatus taskStatus : liveState.getRunningTasks().values()) { sendMessageTo(driver, taskStatus.getTaskId(), taskStatus.getSlaveId(), HDFSConstants.RELOAD_CONFIG); } } private void correctCurrentPhase() { if (liveState.getJournalNodeSize() < conf.getJournalNodeCount()) { // need to add journal nodes liveState.transitionTo(AcquisitionPhase.JOURNAL_NODES); } else if (liveState.getNameNodeSize() < HDFSConstants.TOTAL_NAME_NODES) { // Start the name nodes liveState.transitionTo(AcquisitionPhase.START_NAME_NODES); } else if (!liveState.isNameNode1Initialized() || !liveState.isNameNode2Initialized()) { // start formatting nodes liveState.transitionTo(AcquisitionPhase.FORMAT_NAME_NODES); } else { liveState.transitionTo(AcquisitionPhase.DATA_NODES); } } private boolean offerNotEnoughResources(Offer offer, double cpus, int mem) { for (Resource offerResource : offer.getResourcesList()) { if (offerResource.getName().equals("cpus") && cpus > offerResource.getScalar().getValue()) { return true; } if (offerResource.getName().equals("mem") && mem > offerResource.getScalar().getValue()) { return true; } } return false; } private void reconcileTasks(SchedulerDriver driver) { // TODO run this method repeatedly with exponential backoff in the case that it takes time for // different slaves to reregister upon master failover. reconciliationCompleted = false; driver.reconcileTasks(Collections.<Protos.TaskStatus> emptyList()); Timer timer = new Timer(); timer.schedule(new ReconcileStateTask(), conf.getReconciliationTimeout() * 1000); } private boolean reconciliationComplete() { return reconciliationCompleted; } private class ReconcileStateTask extends TimerTask { @Override public void run() { log.info("Current persistent state:"); log.info(String.format("JournalNodes: %s", persistentState.getJournalNodes())); log.info(String.format("NameNodes: %s", persistentState.getNameNodes())); log.info(String.format("DataNodes: %s", persistentState.getDataNodes())); Collection<String> taskIds = persistentState.getAllTaskIds(); HashMap<String, Protos.TaskStatus> runningTaskIds = liveState.getRunningTasks(); for (String taskId : taskIds) { if (!runningTaskIds.containsKey(taskId)) persistentState.removeTaskId(taskId); } reconciliationCompleted = true; } } }
removed comments.
src/main/java/org/apache/mesos/hdfs/Scheduler.java
removed comments.
<ide><path>rc/main/java/org/apache/mesos/hdfs/Scheduler.java <ide> <ide> private void correctCurrentPhase() { <ide> if (liveState.getJournalNodeSize() < conf.getJournalNodeCount()) { <del> // need to add journal nodes <ide> liveState.transitionTo(AcquisitionPhase.JOURNAL_NODES); <ide> } else if (liveState.getNameNodeSize() < HDFSConstants.TOTAL_NAME_NODES) { <del> // Start the name nodes <ide> liveState.transitionTo(AcquisitionPhase.START_NAME_NODES); <ide> } else if (!liveState.isNameNode1Initialized() <ide> || !liveState.isNameNode2Initialized()) { <del> // start formatting nodes <ide> liveState.transitionTo(AcquisitionPhase.FORMAT_NAME_NODES); <ide> } else { <ide> liveState.transitionTo(AcquisitionPhase.DATA_NODES); <ide> } <add> <ide> } <ide> <ide> private boolean offerNotEnoughResources(Offer offer, double cpus, int mem) {
Java
apache-2.0
c710f4fcd7d64b8aaeb52741bbcef18c627daea5
0
feer921/BaseProject
package common.base.utils; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; /** * 关于时间信息的工具类 * <br/> * 2015年12月25日-下午2:53:50 * @author lifei */ public class TimeUtil { /** * 一般的格式化时间样式:年月日 时分秒 eg.: 2016-09-09 13:28:20 */ public static final String NORMAL_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** * 只需要年月日的时间格式 eg.: 2016-09-09 */ public static final String YMD_TIME_FORMAT = "yyyy-MM-dd"; /** * * @param timePattern 时间正则格式 eg. yyyy-MM-dd HH:mm:ss * @return */ public static String getFormatTimeForNow(String timePattern){ SimpleDateFormat sdf = new SimpleDateFormat(timePattern,Locale.getDefault()); return sdf.format(new Date()); } /** * 获取当前时间 *以yyyy-MM-dd HH:mm:ss eg.: 1988-11-08 18:08:08的方式显示 * @return */ public static String geNowTimeStr() { return getFormatTimeForNow(NORMAL_TIME_FORMAT); } public static String formatMillsTimes(String millsTime, String timeFormat) { if (millsTime == null) { return ""; } if (timeFormat == null) { timeFormat = NORMAL_TIME_FORMAT; } // int serverTimeLen = millsTime.length(); // long localSystemTime = System.currentTimeMillis(); // int localSystemTimeLen = (localSystemTime + "").length(); // int timeGap = localSystemTimeLen - serverTimeLen; // String appendedZero = ""; // while (timeGap-- > 0) { // appendedZero += "0"; // } // millsTime+= appendedZero; SimpleDateFormat sdf = new SimpleDateFormat(timeFormat,Locale.getDefault()); return sdf.format(convetStr2Date(diffLocalMillisTimeAndAppend0(millsTime))); } /** * 以年月日 时分秒 的样式{@linkplain #NORMAL_TIME_FORMAT}格式化 * @param millsTime * @return */ public static String formatMillsTimes(String millsTime) { return formatMillsTimes(millsTime, NORMAL_TIME_FORMAT); } public static Date convetStr2Date(String dateStr) { Date theDate = new Date(Long.parseLong(dateStr)); return theDate; } /*** * 将一个毫秒表示的时间字符串与系统本地的毫秒时间字符串比较,如果参数的毫秒时间比本地的毫秒时间字符数短,则补全相差数量的“0”字符 * 以供本地系统能正确解析完整时间 * @param maybeShortMillisTime 字符长度可能短于本地的毫秒时间字符串的毫秒时间字符串 * @return 原字符串后补全"0"的新毫秒时间字符串 */ private static String diffLocalMillisTimeAndAppend0(String maybeShortMillisTime) { String resultMillisTime = ""; if (maybeShortMillisTime != null && maybeShortMillisTime.trim().length() > 0) { String localMillisTime = System.currentTimeMillis() + ""; resultMillisTime = maybeShortMillisTime; int maybeShortMillisTimeStrLen = maybeShortMillisTime.length(); int timeStrLenGap = localMillisTime.length() - maybeShortMillisTimeStrLen; String appendedZero = ""; while (timeStrLenGap-- > 0) { appendedZero += "0"; } resultMillisTime += appendedZero; } return resultMillisTime; } /*** * 根据一个毫秒时间字符串,获取这个时间的二维信息描述 * 这里只获取1、该时间距离本地系统当前时间是今天、昨天、然后星期;2、月-日信息 * 注:如果是服务器给的时间,则本地去获取是否为今天、昨天,有不准的风险,因为当前系统时间用户可以随便调整,导致比较时间基线变化 * @param theGiveMillisTime 所给的毫秒时间串 * @return new String[]{"今天","11-25"} */ public static String[] getTime2DDescInfos(String theGiveMillisTime) { // String[] twoDimensionDesc = { // "","" // }; // String standardMillisTime = diffLocalMillisTimeAndAppend0(theGiveMillisTime); // long standardMillis = 0; // try { // standardMillis = Long.parseLong(standardMillisTime); // Calendar calendar = Calendar.getInstance();//这里拿到的也就是系统当前日历时间 // long nowMillisTime = System.currentTimeMillis();//系统当前毫秒时间:距离(UTC时间)1970-1-1 00:00:00的毫秒数 // //本地系统的时间所在时区与UTC对比偏移的毫秒数,比如,当前系统时区为在中国,则所在时区为8,系统初始时间则为1970-1-1 08:00:00开始计算 // int curTimeZoneRawOffsetMillis = calendar.getTimeZone().getRawOffset(); // // //就是系统当前时间 距离所在时区的初始时间 偏移了多少天,说白了就是现在已经过了多少天 // long daysOffsetToday = (nowMillisTime + curTimeZoneRawOffsetMillis) / 86400000; // //所给出的时间距离 所在时区的初始时间 偏移了多少天,说白了就是所给出的时间已经过了多少天 // long theTimeOffsetDays = (standardMillis + curTimeZoneRawOffsetMillis)/86400000; // long gapDays = theTimeOffsetDays - daysOffsetToday; // calendar.setTimeInMillis(standardMillis);//把日历切换到参数所给的时间 // String desc1 = ""; // if (gapDays == 0) { // desc1 = "今天"; // } else if (gapDays == -1) { // desc1 = "昨天"; // } else if (gapDays == -2) { // desc1 = "前天"; // } // else{ // //拿到周几的信息 // int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); // desc1 = dayOfWeekDesc(dayOfWeek); // } // int minute = calendar.get(Calendar.MINUTE); // String desc2 = calendar.get(Calendar.HOUR_OF_DAY) + ":" + (minute < 10 ? "0" + minute : minute); // twoDimensionDesc[0] = desc1; // twoDimensionDesc[1] = desc2; // } catch (Exception ignored) { // // } return getTime2DDescInfos(theGiveMillisTime,3,true); } /** * 得到所给的参数时间与当前系统今天的间隔天数 * @param theMillisTime 所给的毫秒时间 注该毫秒需要与Java系统毫秒时间位数一致 * @return 0:所给的时间即为【今天】;1:所给的比今天还多一天,即为【明天】;2:后天;-1:所给的时间比今天少一天即为【昨天】;-2:前天; */ public static long getDiffNowDayNum(String theMillisTime){ Calendar nowCalendar = Calendar.getInstance();//这里拿到的也就是系统当前日历时间 //本地系统的时间所在时区与UTC对比偏移的毫秒数,比如,当前系统时区为在中国,则所在时区为8,系统初始时间则为1970-1-1 08:00:00开始计算 //则偏移的毫秒数应该为 8(时) * 60(分) * 60(秒) * 1000(毫秒) int curTimeZoneRawOffsetMillis = nowCalendar.getTimeZone().getRawOffset(); //就是系统当前时间 距离所在时区的初始时间 偏移了多少天,说白了就是现在已经过了多少天 long daysOffsetToday = (System.currentTimeMillis() + curTimeZoneRawOffsetMillis) / 86400000; long theTimeMilliSecends = Long.parseLong(theMillisTime); //计算参数中所给的时间距离所在时区的初始时间 偏移了多少天,说白了就是theMillisTime这个时间已经过了多少天 long theTimeOffsetDays = (theTimeMilliSecends + curTimeZoneRawOffsetMillis)/86400000; return theTimeOffsetDays - daysOffsetToday;//参数时间 的已过天数 - 现在已过的天数; } private static String dayOfWeekDesc(int dayOfWeek) { String desc = "周一"; switch (dayOfWeek) { case Calendar.MONDAY: break; case Calendar.TUESDAY: desc = "周二"; break; case Calendar.WEDNESDAY: desc = "周三"; break; case Calendar.THURSDAY: desc = "周四"; break; case Calendar.FRIDAY: desc = "周五"; break; case Calendar.SATURDAY: desc = "周六"; break; case Calendar.SUNDAY: desc = "周日"; break; } return desc; } /*** * 根据一个毫秒时间字符串,获取这个时间的二维信息描述 * 这里只获取1、该时间距离本地系统当前时间是今天、昨天、然后星期;2、月-日信息 * 注:如果是服务器给的时间,则本地去获取是否为今天、昨天,有不准的风险,因为当前系统时间用户可以随便调整,导致比较时间基线变化 * @param theGiveMillisTime 所给的毫秒时间串 * @param descTodayAndAfterNums 最好为2-3 要求描述含“今天在内的这种描述法,要描述几个,即:如果要描述三个,则为[今天、昨天、前天],依所传参数类推 * @param descDateAfterAWeek 除去前面描述了 ”今天“、”昨天”、“前天”后,距离一星期外的时间是否描述为年月日.为true时:以 * @return new String[]{"今天","11-25"} */ public static String[] getTime2DDescInfos(String theGiveMillisTime,int descTodayAndAfterNums,boolean descDateAfterAWeek) { String[] twoDimensionDesc = { "","" }; String standardMillisTime = diffLocalMillisTimeAndAppend0(theGiveMillisTime); long standardMillis = 0; try { standardMillis = Long.parseLong(standardMillisTime); Calendar calendar = Calendar.getInstance();//这里拿到的也就是系统当前日历时间 long nowMillisTime = System.currentTimeMillis();//系统当前毫秒时间:距离(UTC时间)1970-1-1 00:00:00的毫秒数 //本地系统的时间所在时区与UTC对比偏移的毫秒数,比如,当前系统时区为在中国,则所在时区为8,系统初始时间则为1970-1-1 08:00:00开始计算 int curTimeZoneRawOffsetMillis = calendar.getTimeZone().getRawOffset(); //就是系统当前时间 距离所在时区的初始时间 偏移了多少天,说白了就是现在已经过了多少天 long daysOffsetToday = (nowMillisTime + curTimeZoneRawOffsetMillis) / 86400000; //所给出的时间距离 所在时区的初始时间 偏移了多少天,说白了就是所给出的时间已经过了多少天 long theTimeOffsetDays = (standardMillis + curTimeZoneRawOffsetMillis)/86400000; long gapDays = theTimeOffsetDays - daysOffsetToday; calendar.setTimeInMillis(standardMillis);//把日历切换到参数所给的时间 String desc1 = ""; if (gapDays > -descTodayAndAfterNums) {//用来描述 距离今天(含)的总共几天 int dayGapPositiveIndex = (int) (gapDays * -1); desc1 = dayDesc[dayGapPositiveIndex]; } else{//eg.:前天之前了 if (descDateAfterAWeek) {//如果需要在时间过一周后用年月日描述 if (gapDays > -7) { int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); desc1 = dayOfWeekDesc(dayOfWeek); descDateAfterAWeek = false; } else{ descDateAfterAWeek = true; } } // else{//再描述了“今天”、“昨天”、“前天”等后,都一律用“年、月、日”描述 // // } if (descDateAfterAWeek) { StringBuilder sb = new StringBuilder(); sb.append(calendar.get(Calendar.YEAR)).append("年") .append(calendar.get(Calendar.MONTH)).append("月") .append(calendar.get(Calendar.DATE)).append("日"); desc1 = sb.toString(); } } // else if(gapDays > -7){//除去,"今天",”昨天“,”前天“ 外剩下的在一周之前内的用 ["周X”][10:30]描述 // int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); // desc1 = dayOfWeekDesc(dayOfWeek); // } // else{//用[年月日] [10:30] 描述了 // StringBuilder sb = new StringBuilder(); // sb.append(calendar.get(Calendar.YEAR)).append("年") // .append(calendar.get(Calendar.MONTH)).append("月") // .append(calendar.get(Calendar.DATE)).append("日"); // desc1 = sb.toString(); // } int minute = calendar.get(Calendar.MINUTE); String desc2 = calendar.get(Calendar.HOUR_OF_DAY) + ":" + (minute < 10 ? "0" + minute : minute); twoDimensionDesc[0] = desc1; twoDimensionDesc[1] = desc2; } catch (Exception ignored) { } return twoDimensionDesc; } private static final String[] dayDesc = {"今天","昨天","前天","大前天"}; }
src/main/java/common/base/utils/TimeUtil.java
package common.base.utils; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; /** * 关于时间信息的工具类 * <br/> * 2015年12月25日-下午2:53:50 * @author lifei */ public class TimeUtil { /** * 一般的格式化时间样式:年月日 时分秒 eg.: 2016-09-09 13:28:20 */ public static final String NORMAL_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** * 只需要年月日的时间格式 eg.: 2016-09-09 */ public static final String YMD_TIME_FORMAT = "yyyy-MM-dd"; /** * * @param timePattern 时间正则格式 eg. yyyy-MM-dd HH:mm:ss * @return */ public static String getFormatTimeForNow(String timePattern){ SimpleDateFormat sdf = new SimpleDateFormat(timePattern,Locale.getDefault()); return sdf.format(new Date()); } /** * 获取当前时间 *以yyyy-MM-dd HH:mm:ss eg.: 1988-11-08 18:08:08的方式显示 * @return */ public static String geNowTimeStr() { return getFormatTimeForNow(NORMAL_TIME_FORMAT); } public static String formatMillsTimes(String millsTime, String timeFormat) { if (millsTime == null) { return ""; } if (timeFormat == null) { timeFormat = NORMAL_TIME_FORMAT; } // int serverTimeLen = millsTime.length(); // long localSystemTime = System.currentTimeMillis(); // int localSystemTimeLen = (localSystemTime + "").length(); // int timeGap = localSystemTimeLen - serverTimeLen; // String appendedZero = ""; // while (timeGap-- > 0) { // appendedZero += "0"; // } // millsTime+= appendedZero; SimpleDateFormat sdf = new SimpleDateFormat(timeFormat,Locale.getDefault()); return sdf.format(convetStr2Date(diffLocalMillisTimeAndAppend0(millsTime))); } /** * 以年月日 时分秒 的样式{@linkplain #NORMAL_TIME_FORMAT}格式化 * @param millsTime * @return */ public static String formatMillsTimes(String millsTime) { return formatMillsTimes(millsTime, NORMAL_TIME_FORMAT); } public static Date convetStr2Date(String dateStr) { Date theDate = new Date(Long.parseLong(dateStr)); return theDate; } /*** * 将一个毫秒表示的时间字符串与系统本地的毫秒时间字符串比较,如果参数的毫秒时间比本地的毫秒时间字符数短,则补全相差数量的“0”字符 * 以供本地系统能正确解析完整时间 * @param maybeShortMillisTime 字符长度可能短于本地的毫秒时间字符串的毫秒时间字符串 * @return 原字符串后补全"0"的新毫秒时间字符串 */ private static String diffLocalMillisTimeAndAppend0(String maybeShortMillisTime) { String resultMillisTime = ""; if (maybeShortMillisTime != null && maybeShortMillisTime.trim().length() > 0) { String localMillisTime = System.currentTimeMillis() + ""; resultMillisTime = maybeShortMillisTime; int maybeShortMillisTimeStrLen = maybeShortMillisTime.length(); int timeStrLenGap = localMillisTime.length() - maybeShortMillisTimeStrLen; String appendedZero = ""; while (timeStrLenGap-- > 0) { appendedZero += "0"; } resultMillisTime += appendedZero; } return resultMillisTime; } /*** * 根据一个毫秒时间字符串,获取这个时间的二维信息描述 * 这里只获取1、该时间距离本地系统当前时间是今天、昨天、然后星期;2、月-日信息 * 注:如果是服务器给的时间,则本地去获取是否为今天、昨天,有不准的风险,因为当前系统时间用户可以随便调整,导致比较时间基线变化 * @param theGiveMillisTime 所给的毫秒时间串 * @return new String[]{"今天","11-25"} */ public static String[] getTime2DDescInfos(String theGiveMillisTime) { String[] twoDimensionDesc = { "","" }; String standardMillisTime = diffLocalMillisTimeAndAppend0(theGiveMillisTime); long standardMillis = 0; try { standardMillis = Long.parseLong(standardMillisTime); Calendar calendar = Calendar.getInstance();//这里拿到的也就是系统当前日历时间 long nowMillisTime = System.currentTimeMillis();//系统当前毫秒时间:距离(UTC时间)1970-1-1 00:00:00的毫秒数 //本地系统的时间所在时区与UTC对比偏移的毫秒数,比如,当前系统时区为在中国,则所在时区为8,系统初始时间则为1970-1-1 08:00:00开始计算 int curTimeZoneRawOffsetMillis = calendar.getTimeZone().getRawOffset(); //就是系统当前时间 距离所在时区的初始时间 偏移了多少天,说白了就是现在已经过了多少天 long daysOffsetToday = (nowMillisTime + curTimeZoneRawOffsetMillis) / 86400000; //所给出的时间距离 所在时区的初始时间 偏移了多少天,说白了就是所给出的时间已经过了多少天 long theTimeOffsetDays = (standardMillis + curTimeZoneRawOffsetMillis)/86400000; long gapDays = theTimeOffsetDays - daysOffsetToday; calendar.setTimeInMillis(standardMillis);//把日历切换到参数所给的时间 String desc1 = ""; if (gapDays == 0) { desc1 = "今天"; } else if (gapDays == -1) { desc1 = "昨天"; } else if (gapDays == -2) { desc1 = "前天"; } else{ //拿到周几的信息 int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); desc1 = dayOfWeekDesc(dayOfWeek); } int minute = calendar.get(Calendar.MINUTE); String desc2 = calendar.get(Calendar.HOUR_OF_DAY) + ":" + (minute < 10 ? "0" + minute : minute); twoDimensionDesc[0] = desc1; twoDimensionDesc[1] = desc2; } catch (Exception ignored) { } return twoDimensionDesc; } /** * 得到所给的参数时间与当前系统今天的间隔天数 * @param theMillisTime 所给的毫秒时间 注该毫秒需要与Java系统毫秒时间位数一致 * @return 0:所给的时间即为【今天】;1:所给的比今天还多一天,即为【明天】;2:后天;-1:所给的时间比今天少一天即为【昨天】;-2:前天; */ public static long getDiffNowDayNum(String theMillisTime){ Calendar nowCalendar = Calendar.getInstance();//这里拿到的也就是系统当前日历时间 //本地系统的时间所在时区与UTC对比偏移的毫秒数,比如,当前系统时区为在中国,则所在时区为8,系统初始时间则为1970-1-1 08:00:00开始计算 //则偏移的毫秒数应该为 8(时) * 60(分) * 60(秒) * 1000(毫秒) int curTimeZoneRawOffsetMillis = nowCalendar.getTimeZone().getRawOffset(); //就是系统当前时间 距离所在时区的初始时间 偏移了多少天,说白了就是现在已经过了多少天 long daysOffsetToday = (System.currentTimeMillis() + curTimeZoneRawOffsetMillis) / 86400000; long theTimeMilliSecends = Long.parseLong(theMillisTime); //计算参数中所给的时间距离所在时区的初始时间 偏移了多少天,说白了就是theMillisTime这个时间已经过了多少天 long theTimeOffsetDays = (theTimeMilliSecends + curTimeZoneRawOffsetMillis)/86400000; return theTimeOffsetDays - daysOffsetToday;//参数时间 的已过天数 - 现在已过的天数; } private static String dayOfWeekDesc(int dayOfWeek) { String desc = "周一"; switch (dayOfWeek) { case Calendar.MONDAY: break; case Calendar.TUESDAY: desc = "周二"; break; case Calendar.WEDNESDAY: desc = "周三"; break; case Calendar.THURSDAY: desc = "周四"; break; case Calendar.FRIDAY: desc = "周五"; break; case Calendar.SATURDAY: desc = "周六"; break; case Calendar.SUNDAY: desc = "周日"; break; } return desc; } }
TimeUtil完善通过给定毫秒时间计划出该时间距离当前设备的其他时间信息
src/main/java/common/base/utils/TimeUtil.java
TimeUtil完善通过给定毫秒时间计划出该时间距离当前设备的其他时间信息
<ide><path>rc/main/java/common/base/utils/TimeUtil.java <ide> * @return new String[]{"今天","11-25"} <ide> */ <ide> public static String[] getTime2DDescInfos(String theGiveMillisTime) { <add>// String[] twoDimensionDesc = { <add>// "","" <add>// }; <add>// String standardMillisTime = diffLocalMillisTimeAndAppend0(theGiveMillisTime); <add>// long standardMillis = 0; <add>// try { <add>// standardMillis = Long.parseLong(standardMillisTime); <add>// Calendar calendar = Calendar.getInstance();//这里拿到的也就是系统当前日历时间 <add>// long nowMillisTime = System.currentTimeMillis();//系统当前毫秒时间:距离(UTC时间)1970-1-1 00:00:00的毫秒数 <add>// //本地系统的时间所在时区与UTC对比偏移的毫秒数,比如,当前系统时区为在中国,则所在时区为8,系统初始时间则为1970-1-1 08:00:00开始计算 <add>// int curTimeZoneRawOffsetMillis = calendar.getTimeZone().getRawOffset(); <add>// <add>// //就是系统当前时间 距离所在时区的初始时间 偏移了多少天,说白了就是现在已经过了多少天 <add>// long daysOffsetToday = (nowMillisTime + curTimeZoneRawOffsetMillis) / 86400000; <add>// //所给出的时间距离 所在时区的初始时间 偏移了多少天,说白了就是所给出的时间已经过了多少天 <add>// long theTimeOffsetDays = (standardMillis + curTimeZoneRawOffsetMillis)/86400000; <add>// long gapDays = theTimeOffsetDays - daysOffsetToday; <add>// calendar.setTimeInMillis(standardMillis);//把日历切换到参数所给的时间 <add>// String desc1 = ""; <add>// if (gapDays == 0) { <add>// desc1 = "今天"; <add>// } else if (gapDays == -1) { <add>// desc1 = "昨天"; <add>// } else if (gapDays == -2) { <add>// desc1 = "前天"; <add>// } <add>// else{ <add>// //拿到周几的信息 <add>// int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); <add>// desc1 = dayOfWeekDesc(dayOfWeek); <add>// } <add>// int minute = calendar.get(Calendar.MINUTE); <add>// String desc2 = calendar.get(Calendar.HOUR_OF_DAY) + ":" + (minute < 10 ? "0" + minute : minute); <add>// twoDimensionDesc[0] = desc1; <add>// twoDimensionDesc[1] = desc2; <add>// } catch (Exception ignored) { <add>// <add>// } <add> return getTime2DDescInfos(theGiveMillisTime,3,true); <add> } <add> <add> /** <add> * 得到所给的参数时间与当前系统今天的间隔天数 <add> * @param theMillisTime 所给的毫秒时间 注该毫秒需要与Java系统毫秒时间位数一致 <add> * @return 0:所给的时间即为【今天】;1:所给的比今天还多一天,即为【明天】;2:后天;-1:所给的时间比今天少一天即为【昨天】;-2:前天; <add> */ <add> public static long getDiffNowDayNum(String theMillisTime){ <add> Calendar nowCalendar = Calendar.getInstance();//这里拿到的也就是系统当前日历时间 <add> //本地系统的时间所在时区与UTC对比偏移的毫秒数,比如,当前系统时区为在中国,则所在时区为8,系统初始时间则为1970-1-1 08:00:00开始计算 <add> //则偏移的毫秒数应该为 8(时) * 60(分) * 60(秒) * 1000(毫秒) <add> int curTimeZoneRawOffsetMillis = nowCalendar.getTimeZone().getRawOffset(); <add> //就是系统当前时间 距离所在时区的初始时间 偏移了多少天,说白了就是现在已经过了多少天 <add> long daysOffsetToday = (System.currentTimeMillis() + curTimeZoneRawOffsetMillis) / 86400000; <add> <add> long theTimeMilliSecends = Long.parseLong(theMillisTime); <add> //计算参数中所给的时间距离所在时区的初始时间 偏移了多少天,说白了就是theMillisTime这个时间已经过了多少天 <add> long theTimeOffsetDays = (theTimeMilliSecends + curTimeZoneRawOffsetMillis)/86400000; <add> return theTimeOffsetDays - daysOffsetToday;//参数时间 的已过天数 - 现在已过的天数; <add> } <add> <add> private static String dayOfWeekDesc(int dayOfWeek) { <add> String desc = "周一"; <add> switch (dayOfWeek) { <add> case Calendar.MONDAY: <add> break; <add> case Calendar.TUESDAY: <add> desc = "周二"; <add> break; <add> case Calendar.WEDNESDAY: <add> desc = "周三"; <add> break; <add> case Calendar.THURSDAY: <add> desc = "周四"; <add> break; <add> case Calendar.FRIDAY: <add> desc = "周五"; <add> break; <add> case Calendar.SATURDAY: <add> desc = "周六"; <add> break; <add> case Calendar.SUNDAY: <add> desc = "周日"; <add> break; <add> } <add> return desc; <add> } <add> <add> /*** <add> * 根据一个毫秒时间字符串,获取这个时间的二维信息描述 <add> * 这里只获取1、该时间距离本地系统当前时间是今天、昨天、然后星期;2、月-日信息 <add> * 注:如果是服务器给的时间,则本地去获取是否为今天、昨天,有不准的风险,因为当前系统时间用户可以随便调整,导致比较时间基线变化 <add> * @param theGiveMillisTime 所给的毫秒时间串 <add> * @param descTodayAndAfterNums 最好为2-3 要求描述含“今天在内的这种描述法,要描述几个,即:如果要描述三个,则为[今天、昨天、前天],依所传参数类推 <add> * @param descDateAfterAWeek 除去前面描述了 ”今天“、”昨天”、“前天”后,距离一星期外的时间是否描述为年月日.为true时:以 <add> * @return new String[]{"今天","11-25"} <add> */ <add> public static String[] getTime2DDescInfos(String theGiveMillisTime,int descTodayAndAfterNums,boolean descDateAfterAWeek) { <ide> String[] twoDimensionDesc = { <del> "","" <add> "","" <ide> }; <ide> String standardMillisTime = diffLocalMillisTimeAndAppend0(theGiveMillisTime); <ide> long standardMillis = 0; <ide> long gapDays = theTimeOffsetDays - daysOffsetToday; <ide> calendar.setTimeInMillis(standardMillis);//把日历切换到参数所给的时间 <ide> String desc1 = ""; <del> if (gapDays == 0) { <del> desc1 = "今天"; <del> } else if (gapDays == -1) { <del> desc1 = "昨天"; <del> } else if (gapDays == -2) { <del> desc1 = "前天"; <add> <add> if (gapDays > -descTodayAndAfterNums) {//用来描述 距离今天(含)的总共几天 <add> int dayGapPositiveIndex = (int) (gapDays * -1); <add> desc1 = dayDesc[dayGapPositiveIndex]; <ide> } <del> else{ <del> //拿到周几的信息 <del> int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); <del> desc1 = dayOfWeekDesc(dayOfWeek); <add> else{//eg.:前天之前了 <add> if (descDateAfterAWeek) {//如果需要在时间过一周后用年月日描述 <add> if (gapDays > -7) { <add> int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); <add> desc1 = dayOfWeekDesc(dayOfWeek); <add> descDateAfterAWeek = false; <add> } <add> else{ <add> descDateAfterAWeek = true; <add> } <add> } <add>// else{//再描述了“今天”、“昨天”、“前天”等后,都一律用“年、月、日”描述 <add>// <add>// } <add> if (descDateAfterAWeek) { <add> StringBuilder sb = new StringBuilder(); <add> sb.append(calendar.get(Calendar.YEAR)).append("年") <add> .append(calendar.get(Calendar.MONTH)).append("月") <add> .append(calendar.get(Calendar.DATE)).append("日"); <add> desc1 = sb.toString(); <add> } <ide> } <add>// else if(gapDays > -7){//除去,"今天",”昨天“,”前天“ 外剩下的在一周之前内的用 ["周X”][10:30]描述 <add>// int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); <add>// desc1 = dayOfWeekDesc(dayOfWeek); <add>// } <add>// else{//用[年月日] [10:30] 描述了 <add>// StringBuilder sb = new StringBuilder(); <add>// sb.append(calendar.get(Calendar.YEAR)).append("年") <add>// .append(calendar.get(Calendar.MONTH)).append("月") <add>// .append(calendar.get(Calendar.DATE)).append("日"); <add>// desc1 = sb.toString(); <add>// } <ide> int minute = calendar.get(Calendar.MINUTE); <ide> String desc2 = calendar.get(Calendar.HOUR_OF_DAY) + ":" + (minute < 10 ? "0" + minute : minute); <ide> twoDimensionDesc[0] = desc1; <ide> } <ide> return twoDimensionDesc; <ide> } <del> <del> /** <del> * 得到所给的参数时间与当前系统今天的间隔天数 <del> * @param theMillisTime 所给的毫秒时间 注该毫秒需要与Java系统毫秒时间位数一致 <del> * @return 0:所给的时间即为【今天】;1:所给的比今天还多一天,即为【明天】;2:后天;-1:所给的时间比今天少一天即为【昨天】;-2:前天; <del> */ <del> public static long getDiffNowDayNum(String theMillisTime){ <del> Calendar nowCalendar = Calendar.getInstance();//这里拿到的也就是系统当前日历时间 <del> //本地系统的时间所在时区与UTC对比偏移的毫秒数,比如,当前系统时区为在中国,则所在时区为8,系统初始时间则为1970-1-1 08:00:00开始计算 <del> //则偏移的毫秒数应该为 8(时) * 60(分) * 60(秒) * 1000(毫秒) <del> int curTimeZoneRawOffsetMillis = nowCalendar.getTimeZone().getRawOffset(); <del> //就是系统当前时间 距离所在时区的初始时间 偏移了多少天,说白了就是现在已经过了多少天 <del> long daysOffsetToday = (System.currentTimeMillis() + curTimeZoneRawOffsetMillis) / 86400000; <del> <del> long theTimeMilliSecends = Long.parseLong(theMillisTime); <del> //计算参数中所给的时间距离所在时区的初始时间 偏移了多少天,说白了就是theMillisTime这个时间已经过了多少天 <del> long theTimeOffsetDays = (theTimeMilliSecends + curTimeZoneRawOffsetMillis)/86400000; <del> return theTimeOffsetDays - daysOffsetToday;//参数时间 的已过天数 - 现在已过的天数; <del> } <del> <del> private static String dayOfWeekDesc(int dayOfWeek) { <del> String desc = "周一"; <del> switch (dayOfWeek) { <del> case Calendar.MONDAY: <del> break; <del> case Calendar.TUESDAY: <del> desc = "周二"; <del> break; <del> case Calendar.WEDNESDAY: <del> desc = "周三"; <del> break; <del> case Calendar.THURSDAY: <del> desc = "周四"; <del> break; <del> case Calendar.FRIDAY: <del> desc = "周五"; <del> break; <del> case Calendar.SATURDAY: <del> desc = "周六"; <del> break; <del> case Calendar.SUNDAY: <del> desc = "周日"; <del> break; <del> } <del> return desc; <del> } <add> private static final String[] dayDesc = {"今天","昨天","前天","大前天"}; <ide> }
Java
apache-2.0
22962389bade67856b56180d9e376bd88df91601
0
RainerW/gitblit,firateren52/gitblit,yonglehou/gitblit,paladox/gitblit,mrjoel/gitblit,dispositional/gitblit,wellington-junio/gitblit,fzs/gitblit,culmat/gitblit,davideuler/gitblit,dispositional/gitblit,dispositional/gitblit,pombreda/gitblit,1234-/gitblit,RainerW/gitblit,paladox/gitblit,korealerts1/gitblit,lucamilanesio/gitblit,ahnjune881214/gitblit,fuero/gitblit,fuero/gitblit,lucamilanesio/gitblit,cesarmarinhorj/gitblit,vitalif/gitblit,gitblit/gitblit,mrjoel/gitblit,gzsombor/gitblit,wellington-junio/gitblit,hstonel/gitblit,dispositional/gitblit,cesarmarinhorj/gitblit,yonglehou/gitblit,yonglehou/gitblit,RainerW/gitblit,korealerts1/gitblit,vitalif/gitblit,lucamilanesio/gitblit,fzs/gitblit,Distrotech/gitblit,1234-/gitblit,hstonel/gitblit,yonglehou/gitblit,dispositional/gitblit,firateren52/gitblit,hstonel/gitblit,lucamilanesio/gitblit,mrjoel/gitblit,pombreda/gitblit,ahnjune881214/gitblit,Distrotech/gitblit,gitblit/gitblit,ahnjune881214/gitblit,vitalif/gitblit,firateren52/gitblit,1234-/gitblit,korealerts1/gitblit,paladox/gitblit,wellington-junio/gitblit,davideuler/gitblit,gitblit/gitblit,mystygage/gitblit,ahnjune881214/gitblit,gzsombor/gitblit,paulsputer/gitblit,fzs/gitblit,two-ack/gitblit,paulsputer/gitblit,cesarmarinhorj/gitblit,gitblit/gitblit,gzsombor/gitblit,davideuler/gitblit,firateren52/gitblit,Distrotech/gitblit,mystygage/gitblit,korealerts1/gitblit,lucamilanesio/gitblit,hstonel/gitblit,1234-/gitblit,firateren52/gitblit,culmat/gitblit,fuero/gitblit,paulsputer/gitblit,wellington-junio/gitblit,davideuler/gitblit,RainerW/gitblit,hstonel/gitblit,RainerW/gitblit,two-ack/gitblit,ahnjune881214/gitblit,two-ack/gitblit,wellington-junio/gitblit,davideuler/gitblit,fuero/gitblit,vitalif/gitblit,pombreda/gitblit,two-ack/gitblit,paulsputer/gitblit,fzs/gitblit,paladox/gitblit,culmat/gitblit,mystygage/gitblit,pombreda/gitblit,vitalif/gitblit,mrjoel/gitblit,gzsombor/gitblit,two-ack/gitblit,mrjoel/gitblit,korealerts1/gitblit,Distrotech/gitblit,cesarmarinhorj/gitblit,mystygage/gitblit,pombreda/gitblit,gitblit/gitblit,paulsputer/gitblit,fuero/gitblit,fzs/gitblit,cesarmarinhorj/gitblit,yonglehou/gitblit,mystygage/gitblit,paladox/gitblit,1234-/gitblit
/* * Copyright 2011 gitblit.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 com.gitblit.wicket.pages; import java.text.MessageFormat; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.wicket.PageParameters; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.protocol.http.WebRequest; import com.gitblit.models.RepositoryModel; import com.gitblit.models.RepositoryUrl; import com.gitblit.models.UserModel; import com.gitblit.wicket.GitBlitWebSession; import com.gitblit.wicket.GitblitRedirectException; import com.gitblit.wicket.WicketUtils; import com.gitblit.wicket.panels.RepositoryUrlPanel; public class EmptyRepositoryPage extends RootPage { public EmptyRepositoryPage(PageParameters params) { super(params); setVersioned(false); String repositoryName = WicketUtils.getRepositoryName(params); RepositoryModel repository = app().repositories().getRepositoryModel(repositoryName); if (repository == null) { error(getString("gb.canNotLoadRepository") + " " + repositoryName, true); } if (repository.hasCommits) { // redirect to the summary page if this repository is not empty throw new GitblitRedirectException(SummaryPage.class, params); } setupPage(repositoryName, getString("gb.emptyRepository")); UserModel user = GitBlitWebSession.get().getUser(); if (user == null) { user = UserModel.ANONYMOUS; } HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest(); List<RepositoryUrl> repositoryUrls = app().gitblit().getRepositoryUrls(req, user, repository); RepositoryUrl primaryUrl = repositoryUrls.size() == 0 ? null : repositoryUrls.get(0); String url = primaryUrl != null ? primaryUrl.url : ""; add(new Label("repository", repositoryName)); add(new RepositoryUrlPanel("pushurl", false, user, repository)); add(new Label("cloneSyntax", MessageFormat.format("git clone {0}", url))); add(new Label("remoteSyntax", MessageFormat.format("git remote add origin {0}\ngit push origin master", url))); } @Override protected Class<? extends BasePage> getRootNavPageClass() { return RepositoriesPage.class; } }
src/main/java/com/gitblit/wicket/pages/EmptyRepositoryPage.java
/* * Copyright 2011 gitblit.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 com.gitblit.wicket.pages; import java.text.MessageFormat; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.wicket.PageParameters; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.protocol.http.WebRequest; import com.gitblit.models.RepositoryModel; import com.gitblit.models.RepositoryUrl; import com.gitblit.models.UserModel; import com.gitblit.wicket.GitBlitWebSession; import com.gitblit.wicket.GitblitRedirectException; import com.gitblit.wicket.WicketUtils; import com.gitblit.wicket.panels.RepositoryUrlPanel; public class EmptyRepositoryPage extends RootPage { public EmptyRepositoryPage(PageParameters params) { super(params); setVersioned(false); String repositoryName = WicketUtils.getRepositoryName(params); RepositoryModel repository = app().repositories().getRepositoryModel(repositoryName); if (repository == null) { error(getString("gb.canNotLoadRepository") + " " + repositoryName, true); } if (repository.hasCommits) { // redirect to the summary page if this repository is not empty throw new GitblitRedirectException(SummaryPage.class, params); } setupPage(repositoryName, getString("gb.emptyRepository")); UserModel user = GitBlitWebSession.get().getUser(); if (user == null) { user = UserModel.ANONYMOUS; } HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest(); List<RepositoryUrl> repositoryUrls = app().gitblit().getRepositoryUrls(req, user, repository); RepositoryUrl primaryUrl = repositoryUrls.size() == 0 ? null : repositoryUrls.get(0); String url = primaryUrl != null ? primaryUrl.url : ""; add(new Label("repository", repositoryName)); add(new RepositoryUrlPanel("pushurl", false, user, repository)); add(new Label("cloneSyntax", MessageFormat.format("git clone {0}", url))); add(new Label("remoteSyntax", MessageFormat.format("git remote add gitblit {0}\ngit push gitblit master", url))); } @Override protected Class<? extends BasePage> getRootNavPageClass() { return RepositoriesPage.class; } }
Changing hardcoded `gitblit` origin into `origin`.
src/main/java/com/gitblit/wicket/pages/EmptyRepositoryPage.java
Changing hardcoded `gitblit` origin into `origin`.
<ide><path>rc/main/java/com/gitblit/wicket/pages/EmptyRepositoryPage.java <ide> add(new Label("repository", repositoryName)); <ide> add(new RepositoryUrlPanel("pushurl", false, user, repository)); <ide> add(new Label("cloneSyntax", MessageFormat.format("git clone {0}", url))); <del> add(new Label("remoteSyntax", MessageFormat.format("git remote add gitblit {0}\ngit push gitblit master", url))); <add> add(new Label("remoteSyntax", MessageFormat.format("git remote add origin {0}\ngit push origin master", url))); <ide> } <ide> <ide> @Override
Java
agpl-3.0
558ed3e28ce065e70085213278316deacf37d471
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
66baaa1c-2e62-11e5-9284-b827eb9e62be
hello.java
66b52c9a-2e62-11e5-9284-b827eb9e62be
66baaa1c-2e62-11e5-9284-b827eb9e62be
hello.java
66baaa1c-2e62-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>66b52c9a-2e62-11e5-9284-b827eb9e62be <add>66baaa1c-2e62-11e5-9284-b827eb9e62be
Java
mit
ef8a334a7c90adb0514c01a67e5e240890bbeeb7
0
DatabaseGroup/apted
// The MIT License (MIT) // Copyright (c) 2016 Mateusz Pawlik and Nikolaus Augsten // // 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 distance; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.Stack; import util.*; /** * Implements APTED algorithm from [2]. * * - Optimal strategy with all paths. * - Single-node single path function supports currently only unit cost. * - Two-node single path function not included. * - \Delta^L and \Delta^R based on Zhang and Shasha's algorithm for executing * left and right paths (as in [3]). If only left and right paths are used * in the strategy, the memory usage is reduced by one quadratic array. * - For any other path \Delta^A from [1] is used. * * [1] M. Pawlik and N. Augsten. Efficient Computation of the Tree Edit * Distance. ACM Transactions on Database Systems (TODS) 40(1). 2015. * [2] M. Pawlik and N. Augsten. Tree edit distance: Robust and memory- * efficient. Information Systems 56. 2016. * [3] M. Pawlik and N. Augsten. RTED: A Robust Algorithm for the Tree Edit * Distance. PVLDB 5(4). 2011. * * @author Mateusz Pawlik * */ public class APTED { private static final byte LEFT = 0; private static final byte RIGHT = 1; private static final byte INNER = 2; private static final byte HEAVY = 2; private InfoTree_PLUS it1; private InfoTree_PLUS it2; private int size1; private int size2; private LabelDictionary ld; private float delta[][]; public int initSCounter; public int initTCounter; private float q[]; int fn[]; int ft[]; private long counter; private float costDel; private float costIns; private float costMatch; public APTED(float delCost, float insCost, float matchCost) { counter = 0L; costDel = delCost; costIns = insCost; costMatch = matchCost; } public float nonNormalizedTreeDist(LblTree t1, LblTree t2) { // PRECOMPUTATION init(t1, t2); // STRATEGY COMPUTATION with heuristic described in [2] if (it1.lchl < it1.rchl) { delta = computeOptStrategyUsingAllPathsOn2_memopt_postL(it1, it2); } else { delta = computeOptStrategyUsingAllPathsOn2_memopt_postR(it1, it2); } // TED COMPUTATION tedInit(); float result = computeDistUsingLRHPathsStrArray(it1, it2); return result; } public void init(LblTree t1, LblTree t2) { ld = new LabelDictionary(); it1 = new InfoTree_PLUS(t1, ld); t1 = null; it2 = new InfoTree_PLUS(t2, ld); t2 = null; size1 = it1.getSize(); size2 = it2.getSize(); } private void tedInit() { initSCounter = 0; initTCounter = 0; counter = 0L; // Initialize arrays. int maxSize = Math.max(size1, size2) + 1; q = new float[maxSize]; fn = new int[maxSize + 1]; ft = new int[maxSize + 1]; // Compute subtree distances without the root nodes. for(int x = 0; x < size1; x++) { int sizeX = it1.getSizes(x); for(int y = 0; y < size2; y++) { int sizeY = it2.getSizes(y); if(sizeX == 1 || sizeY == 1) { delta[x][y] = (sizeX - 1) * costDel + (sizeY - 1) * costIns; } } } } public float[][] computeOptStrategyUsingAllPathsOn2_memopt_postL(InfoTree_PLUS it1, InfoTree_PLUS it2) { int size1 = it1.getSize(); int size2 = it2.getSize(); float strategy[][] = new float[size1][size2]; float cost1_L[][] = new float[size1][]; float cost1_R[][] = new float[size1][]; float cost1_I[][] = new float[size1][]; float cost2_L[] = new float[size2]; float cost2_R[] = new float[size2]; float cost2_I[] = new float[size2]; int cost2_path[] = new int[size2]; float leafRow[] = new float[size2]; int pathIDOffset = size1; float minCost = 0x7fffffffffffffffL; int strategyPath = -1; int[] pre2size1 = it1.sizes; int[] pre2size2 = it2.sizes; int[] pre2descSum1 = it1.preL_to_desc_sum; int[] pre2descSum2 = it2.preL_to_desc_sum; int[] pre2krSum1 = it1.preL_to_kr_sum; int[] pre2krSum2 = it2.preL_to_kr_sum; int[] pre2revkrSum1 = it1.preL_to_rev_kr_sum; int[] pre2revkrSum2 = it2.preL_to_rev_kr_sum; int[] preL_to_preR_1 = it1.preL_to_preR; int[] preL_to_preR_2 = it2.preL_to_preR; int[] preR_to_preL_1 = it1.preR_to_preL; int[] preR_to_preL_2 = it2.preR_to_preL; int[] pre2parent1 = it1.parents; int[] pre2parent2 = it2.parents; int[] preL_to_postL_1 = it1.preL_to_postL; int[] preL_to_postL_2 = it2.preL_to_postL; int[] postL_to_preL_1 = it1.postL_to_preL; int[] postL_to_preL_2 = it2.postL_to_preL; int size_v, parent_v_preL, parent_w_preL, parent_w_postL = -1, size_w, parent_v_postL = -1; int leftPath_v, rightPath_v; float[] cost_Lpointer_v, cost_Rpointer_v, cost_Ipointer_v; float[] strategypointer_v; float[] cost_Lpointer_parent_v = null, cost_Rpointer_parent_v = null, cost_Ipointer_parent_v = null; float[] strategypointer_parent_v = null; int krSum_v, revkrSum_v, descSum_v; boolean is_v_leaf; int v_in_preL; int w_in_preL; Stack<float[]> rowsToReuse_L = new Stack<float[]>(); Stack<float[]> rowsToReuse_R = new Stack<float[]>(); Stack<float[]> rowsToReuse_I = new Stack<float[]>(); for(int v = 0; v < size1; v++) { v_in_preL = postL_to_preL_1[v]; is_v_leaf = it1.isLeaf(v_in_preL); parent_v_preL = pre2parent1[v_in_preL]; if (parent_v_preL != -1) parent_v_postL = preL_to_postL_1[parent_v_preL]; strategypointer_v = strategy[v_in_preL]; size_v = pre2size1[v_in_preL]; leftPath_v = -(preR_to_preL_1[preL_to_preR_1[v_in_preL] + size_v - 1] + 1);// this is the left path's ID which is the leftmost leaf node: l-r_preorder(r-l_preorder(v) + |Fv| - 1) rightPath_v = v_in_preL + size_v - 1 + 1; // this is the right path's ID which is the rightmost leaf node: l-r_preorder(v) + |Fv| - 1 krSum_v = pre2krSum1[v_in_preL]; revkrSum_v = pre2revkrSum1[v_in_preL]; descSum_v = pre2descSum1[v_in_preL]; if(is_v_leaf) { cost1_L[v] = leafRow; cost1_R[v] = leafRow; cost1_I[v] = leafRow; for(int i = 0; i < size2; i++) strategypointer_v[postL_to_preL_2[i]] = v_in_preL; } cost_Lpointer_v = cost1_L[v]; cost_Rpointer_v = cost1_R[v]; cost_Ipointer_v = cost1_I[v]; if(parent_v_preL != -1 && cost1_L[parent_v_postL] == null) { if (rowsToReuse_L.isEmpty()) { cost1_L[parent_v_postL] = new float[size2]; cost1_R[parent_v_postL] = new float[size2]; cost1_I[parent_v_postL] = new float[size2]; } else { cost1_L[parent_v_postL] = rowsToReuse_L.pop(); cost1_R[parent_v_postL] = rowsToReuse_R.pop(); cost1_I[parent_v_postL] = rowsToReuse_I.pop(); } } if (parent_v_preL != -1) { cost_Lpointer_parent_v = cost1_L[parent_v_postL]; cost_Rpointer_parent_v = cost1_R[parent_v_postL]; cost_Ipointer_parent_v = cost1_I[parent_v_postL]; strategypointer_parent_v = strategy[parent_v_preL]; } Arrays.fill(cost2_L, 0L); Arrays.fill(cost2_R, 0L); Arrays.fill(cost2_I, 0L); Arrays.fill(cost2_path, 0); for(int w = 0; w < size2; w++) { w_in_preL = postL_to_preL_2[w]; parent_w_preL = pre2parent2[w_in_preL]; if (parent_w_preL != -1) parent_w_postL = preL_to_postL_2[parent_w_preL]; size_w = pre2size2[w_in_preL]; if(it2.isLeaf(w_in_preL)) { cost2_L[w] = 0L; cost2_R[w] = 0L; cost2_I[w] = 0L; cost2_path[w] = w_in_preL; } minCost = 0x7fffffffffffffffL; strategyPath = -1; float tmpCost = 0x7fffffffffffffffL; if (size_v <= 1 || size_w <= 1) { // USE NEW SINGLE_PATH FUNCTIONS FOR SMALL SUBTREES minCost = Math.max(size_v, size_w); } else { tmpCost = (float) size_v * (float) pre2krSum2[w_in_preL] + cost_Lpointer_v[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = leftPath_v; } tmpCost = (float) size_v * (float) pre2revkrSum2[w_in_preL] + cost_Rpointer_v[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = rightPath_v; } tmpCost = (float) size_v * (float) pre2descSum2[w_in_preL] + cost_Ipointer_v[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = (int)strategypointer_v[w_in_preL] + 1; } tmpCost = (float) size_w * (float) krSum_v + cost2_L[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = -(preR_to_preL_2[preL_to_preR_2[w_in_preL] + size_w - 1] + pathIDOffset + 1); } tmpCost = (float) size_w * (float) revkrSum_v + cost2_R[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = w_in_preL + size_w - 1 + pathIDOffset + 1; } tmpCost = (float) size_w * (float) descSum_v + cost2_I[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = cost2_path[w] + pathIDOffset + 1; } } if(parent_v_preL != -1) { cost_Rpointer_parent_v[w] += minCost; tmpCost = -minCost + cost1_I[v][w]; if(tmpCost < cost1_I[parent_v_postL][w]) { cost_Ipointer_parent_v[w] = tmpCost; strategypointer_parent_v[w_in_preL] = strategypointer_v[w_in_preL]; } if(it1.ifNodeOfType(v_in_preL, 1)) { cost_Ipointer_parent_v[w] += cost_Rpointer_parent_v[w]; cost_Rpointer_parent_v[w] += cost_Rpointer_v[w] - minCost; } if(it1.ifNodeOfType(v_in_preL, 0)) cost_Lpointer_parent_v[w] += cost_Lpointer_v[w]; else cost_Lpointer_parent_v[w] += minCost; } if(parent_w_preL != -1) { cost2_R[parent_w_postL] += minCost; tmpCost = -minCost + cost2_I[w]; if(tmpCost < cost2_I[parent_w_postL]) { cost2_I[parent_w_postL] = tmpCost; cost2_path[parent_w_postL] = cost2_path[w]; } if(it2.ifNodeOfType(w_in_preL, 1)) { cost2_I[parent_w_postL] += cost2_R[parent_w_postL]; cost2_R[parent_w_postL] += cost2_R[w] - minCost; } if(it2.ifNodeOfType(w_in_preL, 0)) cost2_L[parent_w_postL] += cost2_L[w]; else cost2_L[parent_w_postL] += minCost; } strategypointer_v[w_in_preL] = strategyPath; } if(!it1.isLeaf(v_in_preL)) { Arrays.fill(cost1_L[v], 0); Arrays.fill(cost1_R[v], 0); Arrays.fill(cost1_I[v], 0); rowsToReuse_L.push(cost1_L[v]); rowsToReuse_R.push(cost1_R[v]); rowsToReuse_I.push(cost1_I[v]); } } return strategy; } public float[][] computeOptStrategyUsingAllPathsOn2_memopt_postR(InfoTree_PLUS it1, InfoTree_PLUS it2) { int size1 = it1.getSize(); int size2 = it2.getSize(); float strategy[][] = new float[size1][size2]; float cost1_L[][] = new float[size1][]; float cost1_R[][] = new float[size1][]; float cost1_I[][] = new float[size1][]; float cost2_L[] = new float[size2]; float cost2_R[] = new float[size2]; float cost2_I[] = new float[size2]; int cost2_path[] = new int[size2]; float leafRow[] = new float[size2]; int pathIDOffset = size1; float minCost = 0x7fffffffffffffffL; int strategyPath = -1; int[] pre2size1 = it1.sizes; int[] pre2size2 = it2.sizes; int[] pre2descSum1 = it1.preL_to_desc_sum; int[] pre2descSum2 = it2.preL_to_desc_sum; int[] pre2krSum1 = it1.preL_to_kr_sum; int[] pre2krSum2 = it2.preL_to_kr_sum; int[] pre2revkrSum1 = it1.preL_to_rev_kr_sum; int[] pre2revkrSum2 = it2.preL_to_rev_kr_sum; int[] preL_to_preR_1 = it1.preL_to_preR; int[] preL_to_preR_2 = it2.preL_to_preR; int[] preR_to_preL_1 = it1.preR_to_preL; int[] preR_to_preL_2 = it2.preR_to_preL; int[] pre2parent1 = it1.parents; int[] pre2parent2 = it2.parents; int size_v, parent_v, parent_w, size_w; int leftPath_v, rightPath_v; float[] cost_Lpointer_v, cost_Rpointer_v, cost_Ipointer_v; float[] strategypointer_v; float[] cost_Lpointer_parent_v = null, cost_Rpointer_parent_v = null, cost_Ipointer_parent_v = null; float[] strategypointer_parent_v = null; int krSum_v, revkrSum_v, descSum_v; boolean is_v_leaf; Stack<float[]> rowsToReuse_L = new Stack<float[]>(); Stack<float[]> rowsToReuse_R = new Stack<float[]>(); Stack<float[]> rowsToReuse_I = new Stack<float[]>(); for(int v = size1 - 1; v >= 0; v--) { is_v_leaf = it1.isLeaf(v); parent_v = pre2parent1[v]; strategypointer_v = strategy[v]; size_v = pre2size1[v]; leftPath_v = -(preR_to_preL_1[preL_to_preR_1[v] + pre2size1[v] - 1] + 1);// this is the left path's ID which is the leftmost leaf node: l-r_preorder(r-l_preorder(v) + |Fv| - 1) rightPath_v = v + pre2size1[v] - 1 + 1; // this is the right path's ID which is the rightmost leaf node: l-r_preorder(v) + |Fv| - 1 krSum_v = pre2krSum1[v]; revkrSum_v = pre2revkrSum1[v]; descSum_v = pre2descSum1[v]; if(is_v_leaf) { cost1_L[v] = leafRow; cost1_R[v] = leafRow; cost1_I[v] = leafRow; for(int i = 0; i < size2; i++) strategypointer_v[i] = v; } cost_Lpointer_v = cost1_L[v]; cost_Rpointer_v = cost1_R[v]; cost_Ipointer_v = cost1_I[v]; if(parent_v != -1 && cost1_L[parent_v] == null) { if (rowsToReuse_L.isEmpty()) { cost1_L[parent_v] = new float[size2]; cost1_R[parent_v] = new float[size2]; cost1_I[parent_v] = new float[size2]; } else { cost1_L[parent_v] = rowsToReuse_L.pop(); cost1_R[parent_v] = rowsToReuse_R.pop(); cost1_I[parent_v] = rowsToReuse_I.pop(); } } if (parent_v != -1) { cost_Lpointer_parent_v = cost1_L[parent_v]; cost_Rpointer_parent_v = cost1_R[parent_v]; cost_Ipointer_parent_v = cost1_I[parent_v]; strategypointer_parent_v = strategy[parent_v]; } Arrays.fill(cost2_L, 0L); Arrays.fill(cost2_R, 0L); Arrays.fill(cost2_I, 0L); Arrays.fill(cost2_path, 0); for(int w = size2 - 1; w >= 0; w--) { size_w = pre2size2[w]; if(it2.isLeaf(w)) { cost2_L[w] = 0L; cost2_R[w] = 0L; cost2_I[w] = 0L; cost2_path[w] = w; } minCost = 0x7fffffffffffffffL; strategyPath = -1; float tmpCost = 0x7fffffffffffffffL; if (size_v <= 1 || size_w <= 1) { // USE NEW SINGLE_PATH FUNCTIONS FOR SMALL SUBTREES minCost = Math.max(size_v, size_w); } else { tmpCost = (float) size_v * (float) pre2krSum2[w] + cost_Lpointer_v[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = leftPath_v; } tmpCost = (float) size_v * (float) pre2revkrSum2[w] + cost_Rpointer_v[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = rightPath_v; } tmpCost = (float) size_v * (float) pre2descSum2[w] + cost_Ipointer_v[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = (int)strategypointer_v[w] + 1; } tmpCost = (float) size_w * (float) krSum_v + cost2_L[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = -(preR_to_preL_2[preL_to_preR_2[w] + size_w - 1] + pathIDOffset + 1); } tmpCost = (float) size_w * (float) revkrSum_v + cost2_R[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = w + size_w - 1 + pathIDOffset + 1; } tmpCost = (float) size_w * (float) descSum_v + cost2_I[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = cost2_path[w] + pathIDOffset + 1; } } if(parent_v != -1) { cost_Lpointer_parent_v[w] += minCost; tmpCost = -minCost + cost1_I[v][w]; if(tmpCost < cost1_I[parent_v][w]) { cost_Ipointer_parent_v[w] = tmpCost; strategypointer_parent_v[w] = strategypointer_v[w]; } if(it1.ifNodeOfType(v, 0)) { cost_Ipointer_parent_v[w] += cost_Lpointer_parent_v[w]; cost_Lpointer_parent_v[w] += cost_Lpointer_v[w] - minCost; } if(it1.ifNodeOfType(v, 1)) cost_Rpointer_parent_v[w] += cost_Rpointer_v[w]; else cost_Rpointer_parent_v[w] += minCost; } parent_w = pre2parent2[w]; if(parent_w != -1) { cost2_L[parent_w] += minCost; tmpCost = -minCost + cost2_I[w]; if(tmpCost < cost2_I[parent_w]) { cost2_I[parent_w] = tmpCost; cost2_path[parent_w] = cost2_path[w]; } if(it2.ifNodeOfType(w, 0)) { cost2_I[parent_w] += cost2_L[parent_w]; cost2_L[parent_w] += cost2_L[w] - minCost; } if(it2.ifNodeOfType(w, 1)) cost2_R[parent_w] += cost2_R[w]; else cost2_R[parent_w] += minCost; } strategypointer_v[w] = strategyPath; } if(!it1.isLeaf(v)) { Arrays.fill(cost1_L[v], 0); Arrays.fill(cost1_R[v], 0); Arrays.fill(cost1_I[v], 0); rowsToReuse_L.push(cost1_L[v]); rowsToReuse_R.push(cost1_R[v]); rowsToReuse_I.push(cost1_I[v]); } } return strategy; } private float computeDistUsingLRHPathsStrArray(InfoTree_PLUS it1, InfoTree_PLUS it2) { int currentSubtree1 = it1.getCurrentNode(); int currentSubtree2 = it2.getCurrentNode(); int subtreeSize1 = it1.getSizes(currentSubtree1); int subtreeSize2 = it2.getSizes(currentSubtree2); // SINGLE-NODE SUBTREE if ((subtreeSize1 == 1 || subtreeSize2 == 1)) { if (it1.getCurrentNode() > 0 || it2.getCurrentNode() > 0) { return -1; } else { float result = Math.max(it1.getSizes(currentSubtree1), it2.getSizes(currentSubtree2)); boolean matchFound = false; for (int i = currentSubtree1; i < currentSubtree1 + it1.sizes[currentSubtree1]; i++) { for (int j = currentSubtree2; j < currentSubtree2 + it2.sizes[currentSubtree2]; j++) { if (!matchFound) matchFound = it1.labels[i] == it2.labels[j]; counter++; } } // TODO: modify to custom costs // unit cost only return result += (matchFound ? -1.0D : 0.0D); } } // END int strategyPathID = (int)delta[currentSubtree1][currentSubtree2]; byte strategyPathType = -1; int currentPathNode = Math.abs(strategyPathID) - 1; int pathIDOffset = it1.getSize(); int parent = -1; if(currentPathNode < pathIDOffset) { strategyPathType = getStrategyPathType(strategyPathID, pathIDOffset, it1, currentSubtree1, subtreeSize1); while((parent = it1.getParents(currentPathNode)) >= currentSubtree1) { int ai[]; int k = (ai = it1.getChildren(parent)).length; for(int i = 0; i < k; i++) { int child = ai[i]; if(child != currentPathNode) { it1.setCurrentNode(child); computeDistUsingLRHPathsStrArray(it1, it2); } } currentPathNode = parent; } it1.setCurrentNode(currentSubtree1); it1.setSwitched(false); it2.setSwitched(false); if (strategyPathType == 0) { return spfL(it1, it2); } if (strategyPathType == 1) { return spfR(it1, it2); } return spfWithPathID_opt_mem(it1, it2, Math.abs(strategyPathID) - 1, strategyPathType); } currentPathNode -= pathIDOffset; strategyPathType = getStrategyPathType(strategyPathID, pathIDOffset, it2, currentSubtree2, subtreeSize2); while((parent = it2.getParents(currentPathNode)) >= currentSubtree2) { int ai1[]; int l = (ai1 = it2.getChildren(parent)).length; for(int j = 0; j < l; j++) { int child = ai1[j]; if(child != currentPathNode) { it2.setCurrentNode(child); computeDistUsingLRHPathsStrArray(it1, it2); } } currentPathNode = parent; } it2.setCurrentNode(currentSubtree2); it1.setSwitched(true); it2.setSwitched(true); if (strategyPathType == 0) { return spfL(it2, it1); } if (strategyPathType == 1) { return spfR(it2, it1); } return spfWithPathID_opt_mem(it2, it1, Math.abs(strategyPathID) - pathIDOffset - 1, strategyPathType); } private float spfWithPathID_opt_mem(InfoTree_PLUS it1, InfoTree_PLUS it2, int pathID, byte pathType) { boolean treesSwitched = it1.isSwitched(); int[] it2labels = it2.labels; int[] it2sizes = it2.sizes; int currentSubtreePreL1 = it1.getCurrentNode(); int currentSubtreePreL2 = it2.getCurrentNode(); int currentForestSize1 = 0; int currentForestSize2 = 0; int tmpForestSize1 = 0; int subtreeSize2 = it2.getSizes(currentSubtreePreL2); int subtreeSize1 = it1.getSizes(currentSubtreePreL1); float[][] t = new float[subtreeSize2+1][subtreeSize2+1]; float[][] s = new float[subtreeSize1+1][subtreeSize2+1]; float minCost = -1; float sp1 = 0; float sp2 = 0; float sp3 = 0; int startPathNode = -1; int endPathNode = pathID; int it1PreLoff = endPathNode; int it2PreLoff = currentSubtreePreL2; int it1PreRoff = it1.getPreL_to_PreR(endPathNode); int it2PreRoff = it2.getPreL_to_PreR(it2PreLoff); // variable declarations which were inside the loops int rFlast,lFlast,endPathNode_in_preR,startPathNode_in_preR,parent_of_endPathNode,parent_of_endPathNode_in_preR, lFfirst,rFfirst,rGlast,rGfirst,lGfirst,rG_in_preL,rGminus1_in_preL,parent_of_rG_in_preL,lGlast,lF_in_preR,lFSubtreeSize,lFLabel, lGminus1_in_preR,parent_of_lG,parent_of_lG_in_preR,rF_in_preL,rFSubtreeSize, rGfirst_in_preL; boolean leftPart,rightPart,fForestIsTree,lFIsConsecutiveNodeOfCurrentPathNode,lFIsLeftSiblingOfCurrentPathNode, rFIsConsecutiveNodeOfCurrentPathNode,rFIsRightSiblingOfCurrentPathNode; float[] sp1spointer,sp2spointer,sp3spointer,sp3deltapointer,swritepointer,sp1tpointer,sp3tpointer; byte sp1source,sp3source; for(; endPathNode >= currentSubtreePreL1; endPathNode = it1.getParents(endPathNode)) { it1PreLoff = endPathNode; it1PreRoff = it1.getPreL_to_PreR(endPathNode); rFlast = -1; lFlast = -1; endPathNode_in_preR = it1.getPreL_to_PreR(endPathNode); startPathNode_in_preR = startPathNode == -1 ? 0x7fffffff : it1.getPreL_to_PreR(startPathNode); parent_of_endPathNode = it1.getParents(endPathNode); parent_of_endPathNode_in_preR = parent_of_endPathNode == -1 ? 0x7fffffff : it1.getPreL_to_PreR(parent_of_endPathNode); if(startPathNode - endPathNode > 1) { leftPart = true; } else { leftPart = false; } if(startPathNode >= 0 && startPathNode_in_preR - endPathNode_in_preR > 1) { rightPart = true; } else { rightPart = false; } if(pathType == 1 || pathType == 2 && leftPart) { if(startPathNode == -1) { rFfirst = endPathNode_in_preR; lFfirst = endPathNode; } else { rFfirst = startPathNode_in_preR; lFfirst = startPathNode - 1; } if(!rightPart) rFlast = endPathNode_in_preR; rGlast = it2.getPreL_to_PreR(currentSubtreePreL2); rGfirst = (rGlast + subtreeSize2) - 1; lFlast = rightPart ? endPathNode + 1 : endPathNode; fn[fn.length - 1] = -1; for(int i = currentSubtreePreL2; i < currentSubtreePreL2 + subtreeSize2; i++) { fn[i] = -1; ft[i] = -1; } tmpForestSize1 = currentForestSize1; for(int rG = rGfirst; rG >= rGlast; rG--) { lGfirst = it2.getPreR_to_PreL(rG); rG_in_preL = it2.getPreR_to_PreL(rG); rGminus1_in_preL = rG <= it2.getPreL_to_PreR(currentSubtreePreL2) ? 0x7fffffff : it2.getPreR_to_PreL(rG - 1); parent_of_rG_in_preL = it2.getParents(rG_in_preL); if(pathType == 1) { if (lGfirst == currentSubtreePreL2 || rGminus1_in_preL != parent_of_rG_in_preL) lGlast = lGfirst; else lGlast = it2.getParents(lGfirst)+1; } else { lGlast = lGfirst == currentSubtreePreL2 ? lGfirst : currentSubtreePreL2+1; } updateFnArray(it2.getPreL_to_LN(lGfirst), lGfirst, currentSubtreePreL2); updateFtArray(it2.getPreL_to_LN(lGfirst), lGfirst); int rF = rFfirst; currentForestSize1 = tmpForestSize1; for(int lF = lFfirst; lF >= lFlast; lF--) { if(lF == lFlast && !rightPart) rF = rFlast; currentForestSize1++; currentForestSize2 = it2.getSizes(lGfirst) - 1; lF_in_preR = it1.getPreL_to_PreR(lF); fForestIsTree = lF_in_preR == rF; lFSubtreeSize = it1.getSizes(lF); lFLabel = it1.getLabels(lF); lFIsConsecutiveNodeOfCurrentPathNode = startPathNode - lF == 1; lFIsLeftSiblingOfCurrentPathNode = lF + lFSubtreeSize == startPathNode; sp1spointer = s[(lF + 1) - it1PreLoff]; sp2spointer = s[lF - it1PreLoff]; sp3spointer = s[0]; sp3deltapointer = treesSwitched ? null : delta[lF]; swritepointer = s[lF - it1PreLoff]; sp1source = 1; sp3source = 1; if(fForestIsTree) { if(lFSubtreeSize == 1) sp1source = 3; else if(lFIsConsecutiveNodeOfCurrentPathNode) sp1source = 2; sp3 = 0; sp3source = 2; } else { if(lFIsConsecutiveNodeOfCurrentPathNode) sp1source = 2; sp3 = currentForestSize1 - lFSubtreeSize * costDel; if(lFIsLeftSiblingOfCurrentPathNode) sp3source = 3; } if (sp3source == 1) sp3spointer = s[(lF + lFSubtreeSize) - it1PreLoff]; if(currentForestSize2 + 1 == 1) sp2 = currentForestSize1 * costDel; else sp2 = q[lF]; int lG = lGfirst; currentForestSize2++; switch(sp1source) { case 1: sp1 = sp1spointer[lG - it2PreLoff]; break; case 2: sp1 = t[lG - it2PreLoff][rG - it2PreRoff]; break; case 3: sp1 = currentForestSize2 * costIns; break; } sp1 += costDel; minCost = sp1; sp2 += costIns; if(sp2 < minCost) minCost = sp2; if (sp3 < minCost) { sp3 += treesSwitched ? delta[lG][lF] : sp3deltapointer[lG]; if (sp3 < minCost) { if (lFLabel != it2labels[lG]) sp3 += costMatch; if(sp3 < minCost) minCost = sp3; } } swritepointer[lG - it2PreLoff] = minCost; lG = ft[lG]; counter++; while (lG >= lGlast) { currentForestSize2++; switch(sp1source) { case 1: sp1 = sp1spointer[lG - it2PreLoff] + costDel; break; case 2: sp1 = t[lG - it2PreLoff][rG - it2PreRoff] + costDel; break; case 3: sp1 = currentForestSize2 * costIns + costDel; break; } sp2 = sp2spointer[fn[lG] - it2PreLoff] + costDel; minCost = sp1; if(sp2 < minCost) minCost = sp2; sp3 = treesSwitched ? delta[lG][lF] : sp3deltapointer[lG]; if (sp3 < minCost) { switch(sp3source) { case 1: sp3 += sp3spointer[fn[(lG + it2sizes[lG]) - 1] - it2PreLoff]; break; case 2: sp3 += (currentForestSize2 - it2sizes[lG]) * costIns; break; case 3: sp3 += t[fn[(lG + it2sizes[lG]) - 1] - it2PreLoff][rG - it2PreRoff]; break; } if (sp3 < minCost) { if (lFLabel != it2labels[lG]) sp3 += costMatch; if(sp3 < minCost) minCost = sp3; } } swritepointer[lG - it2PreLoff] = minCost; lG = ft[lG]; counter++; } } if(rGminus1_in_preL == parent_of_rG_in_preL) { if(!rightPart) { if(leftPart) { if(treesSwitched) { delta[parent_of_rG_in_preL][endPathNode] = s[(lFlast + 1) - it1PreLoff][(rGminus1_in_preL + 1) - it2PreLoff]; } else { delta[endPathNode][parent_of_rG_in_preL] = s[(lFlast + 1) - it1PreLoff][(rGminus1_in_preL + 1) - it2PreLoff]; } } if(endPathNode > 0 && endPathNode == parent_of_endPathNode + 1 && endPathNode_in_preR == parent_of_endPathNode_in_preR + 1) { if(treesSwitched) { delta[parent_of_rG_in_preL][parent_of_endPathNode] = s[lFlast - it1PreLoff][(rGminus1_in_preL + 1) - it2PreLoff]; } else { delta[parent_of_endPathNode][parent_of_rG_in_preL] = s[lFlast - it1PreLoff][(rGminus1_in_preL + 1) - it2PreLoff]; } } } for(int lF = lFfirst; lF >= lFlast; lF--) { q[lF] = s[lF - it1PreLoff][(parent_of_rG_in_preL + 1) - it2PreLoff]; } } // TODO: first pointers can be precomputed for(int lG = lGfirst; lG >= lGlast; lG = ft[lG]) { t[lG - it2PreLoff][rG - it2PreRoff] = s[lFlast - it1PreLoff][lG - it2PreLoff]; } } } if(pathType == 0 || pathType == 2 && rightPart || pathType == 2 && !leftPart && !rightPart) { if(startPathNode == -1) { lFfirst = endPathNode; rFfirst = it1.getPreL_to_PreR(endPathNode); } else { rFfirst = it1.getPreL_to_PreR(startPathNode) - 1; lFfirst = endPathNode + 1; } lFlast = endPathNode; lGlast = currentSubtreePreL2; lGfirst = (lGlast + subtreeSize2) - 1; rFlast = it1.getPreL_to_PreR(endPathNode); fn[fn.length - 1] = -1; for(int i = currentSubtreePreL2; i < currentSubtreePreL2 + subtreeSize2; i++) { fn[i] = -1; ft[i] = -1; } tmpForestSize1 = currentForestSize1; for(int lG = lGfirst; lG >= lGlast; lG--) { rGfirst = it2.getPreL_to_PreR(lG); updateFnArray(it2.getPreR_to_LN(rGfirst), rGfirst, it2.getPreL_to_PreR(currentSubtreePreL2)); updateFtArray(it2.getPreR_to_LN(rGfirst), rGfirst); int lF = lFfirst; lGminus1_in_preR = lG <= currentSubtreePreL2 ? 0x7fffffff : it2.getPreL_to_PreR(lG - 1); parent_of_lG = it2.getParents(lG); parent_of_lG_in_preR = parent_of_lG == -1 ? -1 : it2.getPreL_to_PreR(parent_of_lG); currentForestSize1 = tmpForestSize1; if(pathType == 0) { if (lG == currentSubtreePreL2) rGlast = rGfirst; else if(it2.getChildren(parent_of_lG)[0] != lG) rGlast = rGfirst; else rGlast = it2.getPreL_to_PreR(parent_of_lG)+1; } else { rGlast = rGfirst == it2.getPreL_to_PreR(currentSubtreePreL2) ? rGfirst : it2.getPreL_to_PreR(currentSubtreePreL2); } for(int rF = rFfirst; rF >= rFlast; rF--) { if(rF == rFlast) lF = lFlast; currentForestSize1++; currentForestSize2 = it2.getSizes(lG) - 1; rF_in_preL = it1.getPreR_to_PreL(rF); rFSubtreeSize = it1.getSizes(rF_in_preL); if(startPathNode > 0) { rFIsConsecutiveNodeOfCurrentPathNode = startPathNode_in_preR - rF == 1; rFIsRightSiblingOfCurrentPathNode = rF + rFSubtreeSize == startPathNode_in_preR; } else { rFIsConsecutiveNodeOfCurrentPathNode = false; rFIsRightSiblingOfCurrentPathNode = false; } fForestIsTree = rF_in_preL == lF; int rFLabel = it1.getLabels(rF_in_preL); sp1spointer = s[(rF + 1) - it1PreRoff]; sp2spointer = s[rF - it1PreRoff]; sp3spointer = s[0]; sp3deltapointer = treesSwitched ? null : delta[rF_in_preL]; swritepointer = s[rF - it1PreRoff]; sp1tpointer = t[lG - it2PreLoff]; sp3tpointer = t[lG - it2PreLoff]; sp1source = 1; sp3source = 1; if(fForestIsTree) { if (rFSubtreeSize == 1) sp1source = 3; else if (rFIsConsecutiveNodeOfCurrentPathNode) sp1source = 2; sp3 = 0; sp3source = 2; } else { if (rFIsConsecutiveNodeOfCurrentPathNode) sp1source = 2; sp3 = currentForestSize1 - rFSubtreeSize * costDel; if (rFIsRightSiblingOfCurrentPathNode) sp3source = 3; } if (sp3source == 1) sp3spointer = s[(rF + rFSubtreeSize) - it1PreRoff]; if (currentForestSize2 + 1 == 1) sp2 = currentForestSize1 * costDel; else sp2 = q[rF]; int rG = rGfirst; rGfirst_in_preL = it2.getPreR_to_PreL(rGfirst); currentForestSize2++; switch(sp1source) { case 1: sp1 = sp1spointer[rG - it2PreRoff]; break; case 2: sp1 = sp1tpointer[rG - it2PreRoff]; break; case 3: sp1 = currentForestSize2 * costIns; break; } sp1 += costDel; minCost = sp1; sp2 += costIns; if(sp2 < minCost) minCost = sp2; if (sp3 < minCost) { sp3 += treesSwitched ? delta[rGfirst_in_preL][rF_in_preL] : sp3deltapointer[rGfirst_in_preL]; if (sp3 < minCost) { if (rFLabel != it2labels[rGfirst_in_preL]) sp3 += costMatch; if (sp3 < minCost) minCost = sp3; } } swritepointer[rG - it2PreRoff] = minCost; rG = ft[rG]; counter++; while (rG >= rGlast) { currentForestSize2++; rG_in_preL = it2.getPreR_to_PreL(rG); switch(sp1source) { case 1: sp1 = sp1spointer[rG - it2PreRoff] + costDel; break; case 2: sp1 = sp1tpointer[rG - it2PreRoff] + costDel; break; case 3: sp1 = currentForestSize2 * costIns + costDel; break; } sp2 = sp2spointer[fn[rG] - it2PreRoff] + costIns; minCost = sp1; if(sp2 < minCost) minCost = sp2; sp3 = treesSwitched ? delta[rG_in_preL][rF_in_preL] : sp3deltapointer[rG_in_preL]; if (sp3 < minCost) { switch(sp3source) { case 1: sp3 += sp3spointer[fn[(rG + it2sizes[rG_in_preL]) - 1] - it2PreRoff]; break; case 2: sp3 += (currentForestSize2 - it2sizes[rG_in_preL]) * costIns; break; case 3: sp3 += sp3tpointer[fn[(rG + it2sizes[rG_in_preL]) - 1] - it2PreRoff]; break; } if (sp3 < minCost) { if (rFLabel != it2labels[rG_in_preL]) sp3 += costMatch; if(sp3 < minCost) minCost = sp3; } } swritepointer[rG - it2PreRoff] = minCost; rG = ft[rG]; counter++; } } if(lG > currentSubtreePreL2 && lG - 1 == parent_of_lG) { if(rightPart) { if(treesSwitched) { delta[parent_of_lG][endPathNode] = s[(rFlast + 1) - it1PreRoff][(lGminus1_in_preR + 1) - it2PreRoff]; } else { delta[endPathNode][parent_of_lG] = s[(rFlast + 1) - it1PreRoff][(lGminus1_in_preR + 1) - it2PreRoff]; } } if(endPathNode > 0 && endPathNode == parent_of_endPathNode + 1 && endPathNode_in_preR == parent_of_endPathNode_in_preR + 1) if(treesSwitched) { delta[parent_of_lG][parent_of_endPathNode] = s[rFlast - it1PreRoff][(lGminus1_in_preR + 1) - it2PreRoff]; } else { delta[parent_of_endPathNode][parent_of_lG] = s[rFlast - it1PreRoff][(lGminus1_in_preR + 1) - it2PreRoff]; } for (int rF = rFfirst; rF >= rFlast; rF--) { q[rF] = s[rF - it1PreRoff][(parent_of_lG_in_preR + 1) - it2PreRoff]; } } // TODO: first pointers can be precomputed for (int rG = rGfirst; rG >= rGlast; rG = ft[rG]) { t[lG - it2PreLoff][rG - it2PreRoff] = s[rFlast - it1PreRoff][rG - it2PreRoff]; } } } startPathNode = endPathNode; } return minCost; } // ===================== BEGIN spfL private float spfL(InfoTree_PLUS it1, InfoTree_PLUS it2) { int[] keyRoots = new int[it2.sizes[it2.getCurrentNode()]]; Arrays.fill(keyRoots, -1); int pathID = it2.preR_to_preL[it2.preL_to_preR[it2.getCurrentNode()] + it2.sizes[it2.getCurrentNode()] - 1]; int firstKeyRoot = computeKeyRoots(it2, it2.getCurrentNode(), pathID, keyRoots, 0); float[][] forestdist = new float[it1.sizes[it1.getCurrentNode()]+1][it2.sizes[it2.getCurrentNode()]+1]; for (int i = firstKeyRoot-1; i >= 0; i--) { treeEditDist(it1, it2, it1.getCurrentNode(), keyRoots[i], forestdist); } return forestdist[it1.sizes[it1.getCurrentNode()]][it2.sizes[it2.getCurrentNode()]]; } private int computeKeyRoots(InfoTree_PLUS it2, int subtreeRootNode, int pathID, int[] keyRoots, int index) { keyRoots[index] = subtreeRootNode; index++; int pathNode = pathID; while (pathNode > subtreeRootNode) { int parent = it2.parents[pathNode]; for (int child : it2.getChildren(parent)) { if (child != pathNode) index = computeKeyRoots(it2, child, it2.preR_to_preL[it2.preL_to_preR[child]+it2.sizes[child]-1], keyRoots, index); } pathNode = parent; } return index; } private int getLLD(InfoTree_PLUS it, int postorder) { int preL = it.postL_to_preL[postorder]; return it.preL_to_postL[it.preR_to_preL[it.preL_to_preR[preL] + it.sizes[preL] - 1]]; } private void treeEditDist(InfoTree_PLUS it1, InfoTree_PLUS it2, int it1subtree, int it2subtree, float[][] forestdist) { // i,j have to be in postorder int i = it1.preL_to_postL[it1subtree]; int j = it2.preL_to_postL[it2subtree]; int ioff = getLLD(it1, i) - 1; int joff = getLLD(it2, j) - 1; float da = 0; float db = 0; float dc = 0; boolean switched = it1.isSwitched(); forestdist[0][0] = 0; for(int i1 = 1; i1 <= i - ioff; i1++) forestdist[i1][0] = forestdist[i1 - 1][0] + 1; for(int j1 = 1; j1 <= j - joff; j1++) forestdist[0][j1] = forestdist[0][j1 - 1] + 1; for(int i1 = 1; i1 <= i - ioff; i1++) { for(int j1 = 1; j1 <= j - joff; j1++) { counter++; float u = 0; if(it1.labels[it1.postL_to_preL[i1 + ioff]] != it2.labels[it2.postL_to_preL[j1 + joff]]) u = costMatch; if(getLLD(it1,i1 + ioff) == getLLD(it1,i) && getLLD(it2,j1 + joff) == getLLD(it2,j)) { da = forestdist[i1 - 1][j1] + costDel; db = forestdist[i1][j1 - 1] + costIns; dc = forestdist[i1 - 1][j1 - 1] + u; forestdist[i1][j1] = da >= db ? db >= dc ? dc : db : da >= dc ? dc : da; if (switched) { delta[it2.postL_to_preL[j1+joff]][it1.postL_to_preL[i1+ioff]] = forestdist[i1 - 1][j1 - 1]; } else { delta[it1.postL_to_preL[i1+ioff]][it2.postL_to_preL[j1+joff]] = forestdist[i1 - 1][j1 - 1]; } } else { da = forestdist[i1 - 1][j1] + costDel; db = forestdist[i1][j1 - 1] + costIns; dc = forestdist[getLLD(it1,i1 + ioff) - 1 - ioff][getLLD(it2,j1 + joff) - 1 - joff] + (switched ? delta[it2.postL_to_preL[j1 + joff]][it1.postL_to_preL[i1 + ioff]] : delta[it1.postL_to_preL[i1 + ioff]][it2.postL_to_preL[j1 + joff]]) + u; forestdist[i1][j1] = da >= db ? db >= dc ? dc : db : da >= dc ? dc : da; } } } } // ===================== END spfL // ===================== BEGIN spfR private float spfR(InfoTree_PLUS it1, InfoTree_PLUS it2) { int[] revKeyRoots = new int[it2.sizes[it2.getCurrentNode()]]; Arrays.fill(revKeyRoots, -1); int pathID = it2.getCurrentNode() + it2.sizes[it2.getCurrentNode()] - 1; // in r-l preorder int firstKeyRoot = computeRevKeyRoots(it2, it2.getCurrentNode(), pathID, revKeyRoots, 0); float[][] forestdist = new float[it1.sizes[it1.getCurrentNode()]+1][it2.sizes[it2.getCurrentNode()]+1]; for (int i = firstKeyRoot-1; i >= 0; i--) { revTreeEditDist(it1, it2, it1.getCurrentNode(), revKeyRoots[i], forestdist); } return forestdist[it1.sizes[it1.getCurrentNode()]][it2.sizes[it2.getCurrentNode()]]; } private int computeRevKeyRoots(InfoTree_PLUS it2, int subtreeRootNode, int pathID, int[] revKeyRoots, int index) { revKeyRoots[index] = subtreeRootNode; index++; int pathNode = pathID; while (pathNode > subtreeRootNode) { int parent = it2.parents[pathNode]; for (int child : it2.getChildren(parent)) { if (child != pathNode) index = computeRevKeyRoots(it2, child, child+it2.sizes[child]-1, revKeyRoots, index); } pathNode = parent; } return index; } private int getRLD(InfoTree_PLUS it, int revPostorder) { int preL = it.postR_to_preL[revPostorder]; return it.preL_to_postR[preL + it.sizes[preL] - 1]; } private void revTreeEditDist(InfoTree_PLUS it1, InfoTree_PLUS it2, int it1subtree, int it2subtree, float[][] forestdist) { // i,j have to be in r-l postorder int i = it1.preL_to_postR[it1subtree]; int j = it2.preL_to_postR[it2subtree]; int ioff = getRLD(it1, i) - 1; int joff = getRLD(it2, j) - 1; float da = 0; float db = 0; float dc = 0; boolean switched = it1.isSwitched(); forestdist[0][0] = 0; for(int i1 = 1; i1 <= i - ioff; i1++) forestdist[i1][0] = forestdist[i1 - 1][0] + 1; for(int j1 = 1; j1 <= j - joff; j1++) forestdist[0][j1] = forestdist[0][j1 - 1] + 1; for(int i1 = 1; i1 <= i - ioff; i1++) { for(int j1 = 1; j1 <= j - joff; j1++) { counter++; float u = 0; if(it1.labels[it1.postR_to_preL[i1 + ioff]] != it2.labels[it2.postR_to_preL[j1 + joff]]) u = costMatch; if(getRLD(it1,i1 + ioff) == getRLD(it1,i) && getRLD(it2,j1 + joff) == getRLD(it2,j)) { da = forestdist[i1 - 1][j1] + costDel; db = forestdist[i1][j1 - 1] + costIns; dc = forestdist[i1 - 1][j1 - 1] + u; forestdist[i1][j1] = da >= db ? db >= dc ? dc : db : da >= dc ? dc : da; if (switched) { delta[it2.postR_to_preL[j1+joff]][it1.postR_to_preL[i1+ioff]] = forestdist[i1 - 1][j1 - 1]; } else { delta[it1.postR_to_preL[i1+ioff]][it2.postR_to_preL[j1+joff]] = forestdist[i1 - 1][j1 - 1]; } } else { da = forestdist[i1 - 1][j1] + costDel; db = forestdist[i1][j1 - 1] + costIns; dc = forestdist[getRLD(it1,i1 + ioff) - 1 - ioff][getRLD(it2,j1 + joff) - 1 - joff] + (switched ? delta[it2.postR_to_preL[j1 + joff]][it1.postR_to_preL[i1 + ioff]] : delta[it1.postR_to_preL[i1 + ioff]][it2.postR_to_preL[j1 + joff]]) + u; forestdist[i1][j1] = da >= db ? db >= dc ? dc : db : da >= dc ? dc : da; } } } } // ===================== END spfR private byte getStrategyPathType(int pathIDWithPathIDOffset, int pathIDOffset, InfoTree_PLUS it, int currentRootNodePreL, int currentSubtreeSize) { if (Integer.signum(pathIDWithPathIDOffset) == -1) return LEFT; int pathID = Math.abs(pathIDWithPathIDOffset) - 1; if(pathID >= pathIDOffset) pathID = pathID - pathIDOffset; if(pathID == (currentRootNodePreL + currentSubtreeSize) - 1) return RIGHT; return INNER; } private void updateFnArray(int lnForNode, int node, int currentSubtreePreL) { if(lnForNode >= currentSubtreePreL) { fn[node] = fn[lnForNode]; fn[lnForNode] = node; } else { fn[node] = fn[fn.length - 1]; fn[fn.length - 1] = node; } } private void updateFtArray(int lnForNode, int node) { ft[node] = lnForNode; if(fn[node] > -1) ft[fn[node]] = node; } public void setCustomCosts(float costDel, float costIns, float costMatch) { this.costDel = costDel; this.costIns = costIns; this.costMatch = costMatch; } public InfoTree_PLUS getIt1() { return it1; } public InfoTree_PLUS getIt2() { return it2; } }
src/distance/APTED.java
// The MIT License (MIT) // Copyright (c) 2016 Mateusz Pawlik and Nikolaus Augsten // // 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 distance; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.Stack; import util.*; /** * Implements APTED algorithm from [2]. * * - Optimal strategy with all paths. * - Single-node single path function supports currently only unit cost. * - Two-node single path function not included. * - \Delta^L and \Delta^R based on Zhang and Shasha's algorithm for executing * left and right paths (as in [3]). If only left and right paths are used * in the strategy, the memory usage is reduced by one quadratic array. * - For any other path \Delta^A from [1] is used. * * [1] M. Pawlik and N. Augsten. Efficient Computation of the Tree Edit * Distance. ACM Transactions on Database Systems (TODS) 40(1). 2015. * [2] M. Pawlik and N. Augsten. Tree edit distance: Robust and memory- * efficient. Information Systems 56. 2016. * [3] M. Pawlik and N. Augsten. RTED: A Robust Algorithm for the Tree Edit * Distance. PVLDB 5(4). 2011. * * @author Mateusz Pawlik * */ public class APTED { private static final byte LEFT = 0; private static final byte RIGHT = 1; private static final byte INNER = 2; private static final byte HEAVY = 2; private InfoTree_PLUS it1; private InfoTree_PLUS it2; private int size1; private int size2; private LabelDictionary ld; private float delta[][]; public int initSCounter; public int initTCounter; private float q[]; int fn[]; int ft[]; private long counter; private float costDel; private float costIns; private float costMatch; public APTED(float delCost, float insCost, float matchCost) { counter = 0L; costDel = delCost; costIns = insCost; costMatch = matchCost; } public float nonNormalizedTreeDist(LblTree t1, LblTree t2) { // PRECOMPUTATION init(t1, t2); // STRATEGY COMPUTATION with heuristic described in [2] if (it1.lchl < it1.rchl) { delta = computeOptStrategyUsingAllPathsOn2_memopt_postL(it1, it2); } else { delta = computeOptStrategyUsingAllPathsOn2_memopt_postR(it1, it2); } // TED COMPUTATION tedInit(); float result = computeDistUsingLRHPathsStrArray(it1, it2); return result; } public void init(LblTree t1, LblTree t2) { ld = new LabelDictionary(); it1 = new InfoTree_PLUS(t1, ld); t1 = null; it2 = new InfoTree_PLUS(t2, ld); t2 = null; size1 = it1.getSize(); size2 = it2.getSize(); } private void tedInit() { initSCounter = 0; initTCounter = 0; counter = 0L; // Initialize arrays. int maxSize = Math.max(size1, size2) + 1; q = new float[maxSize]; fn = new int[maxSize + 1]; ft = new int[maxSize + 1]; // Compute subtree distances without the root nodes. for(int x = 0; x < size1; x++) { int sizeX = it1.getSizes(x); for(int y = 0; y < size2; y++) { int sizeY = it2.getSizes(y); if(sizeX == 1 || sizeY == 1) { delta[x][y] = (sizeX - 1) * costDel + (sizeY - 1) * costIns; } } } } public float[][] computeOptStrategyUsingAllPathsOn2_memopt_postL(InfoTree_PLUS it1, InfoTree_PLUS it2) { int size1 = it1.getSize(); int size2 = it2.getSize(); float strategy[][] = new float[size1][size2]; float cost1_L[][] = new float[size1][]; float cost1_R[][] = new float[size1][]; float cost1_I[][] = new float[size1][]; float cost2_L[] = new float[size2]; float cost2_R[] = new float[size2]; float cost2_I[] = new float[size2]; int cost2_path[] = new int[size2]; float leafRow[] = new float[size2]; int pathIDOffset = size1; float minCost = 0x7fffffffffffffffL; int strategyPath = -1; int[] pre2size1 = it1.sizes; int[] pre2size2 = it2.sizes; int[] pre2descSum1 = it1.preL_to_desc_sum; int[] pre2descSum2 = it2.preL_to_desc_sum; int[] pre2krSum1 = it1.preL_to_kr_sum; int[] pre2krSum2 = it2.preL_to_kr_sum; int[] pre2revkrSum1 = it1.preL_to_rev_kr_sum; int[] pre2revkrSum2 = it2.preL_to_rev_kr_sum; int[] preL_to_preR_1 = it1.preL_to_preR; int[] preL_to_preR_2 = it2.preL_to_preR; int[] preR_to_preL_1 = it1.preR_to_preL; int[] preR_to_preL_2 = it2.preR_to_preL; int[] pre2parent1 = it1.parents; int[] pre2parent2 = it2.parents; int[] preL_to_postL_1 = it1.preL_to_postL; int[] preL_to_postL_2 = it2.preL_to_postL; int[] postL_to_preL_1 = it1.postL_to_preL; int[] postL_to_preL_2 = it2.postL_to_preL; int size_v, parent_v_preL, parent_w_preL, parent_w_postL = -1, size_w, parent_v_postL = -1; int leftPath_v, rightPath_v; float[] cost_Lpointer_v, cost_Rpointer_v, cost_Ipointer_v; float[] strategypointer_v; float[] cost_Lpointer_parent_v = null, cost_Rpointer_parent_v = null, cost_Ipointer_parent_v = null; float[] strategypointer_parent_v = null; int krSum_v, revkrSum_v, descSum_v; boolean is_v_leaf; int v_in_preL; int w_in_preL; Stack<float[]> rowsToReuse_L = new Stack<float[]>(); Stack<float[]> rowsToReuse_R = new Stack<float[]>(); Stack<float[]> rowsToReuse_I = new Stack<float[]>(); for(int v = 0; v < size1; v++) { v_in_preL = postL_to_preL_1[v]; is_v_leaf = it1.isLeaf(v_in_preL); parent_v_preL = pre2parent1[v_in_preL]; if (parent_v_preL != -1) parent_v_postL = preL_to_postL_1[parent_v_preL]; strategypointer_v = strategy[v_in_preL]; size_v = pre2size1[v_in_preL]; leftPath_v = -(preR_to_preL_1[preL_to_preR_1[v_in_preL] + size_v - 1] + 1);// this is the left path's ID which is the leftmost leaf node: l-r_preorder(r-l_preorder(v) + |Fv| - 1) rightPath_v = v_in_preL + size_v - 1 + 1; // this is the right path's ID which is the rightmost leaf node: l-r_preorder(v) + |Fv| - 1 krSum_v = pre2krSum1[v_in_preL]; revkrSum_v = pre2revkrSum1[v_in_preL]; descSum_v = pre2descSum1[v_in_preL]; if(is_v_leaf) { cost1_L[v] = leafRow; cost1_R[v] = leafRow; cost1_I[v] = leafRow; for(int i = 0; i < size2; i++) strategypointer_v[postL_to_preL_2[i]] = v_in_preL; } cost_Lpointer_v = cost1_L[v]; cost_Rpointer_v = cost1_R[v]; cost_Ipointer_v = cost1_I[v]; if(parent_v_preL != -1 && cost1_L[parent_v_postL] == null) { if (rowsToReuse_L.isEmpty()) { cost1_L[parent_v_postL] = new float[size2]; cost1_R[parent_v_postL] = new float[size2]; cost1_I[parent_v_postL] = new float[size2]; } else { cost1_L[parent_v_postL] = rowsToReuse_L.pop(); cost1_R[parent_v_postL] = rowsToReuse_R.pop(); cost1_I[parent_v_postL] = rowsToReuse_I.pop(); } } if (parent_v_preL != -1) { cost_Lpointer_parent_v = cost1_L[parent_v_postL]; cost_Rpointer_parent_v = cost1_R[parent_v_postL]; cost_Ipointer_parent_v = cost1_I[parent_v_postL]; strategypointer_parent_v = strategy[parent_v_preL]; } Arrays.fill(cost2_L, 0L); Arrays.fill(cost2_R, 0L); Arrays.fill(cost2_I, 0L); Arrays.fill(cost2_path, 0); for(int w = 0; w < size2; w++) { w_in_preL = postL_to_preL_2[w]; parent_w_preL = pre2parent2[w_in_preL]; if (parent_w_preL != -1) parent_w_postL = preL_to_postL_2[parent_w_preL]; size_w = pre2size2[w_in_preL]; if(it2.isLeaf(w_in_preL)) { cost2_L[w] = 0L; cost2_R[w] = 0L; cost2_I[w] = 0L; cost2_path[w] = w_in_preL; } minCost = 0x7fffffffffffffffL; strategyPath = -1; float tmpCost = 0x7fffffffffffffffL; if (size_v <= 1 || size_w <= 1) { // USE NEW SINGLE_PATH FUNCTIONS FOR SMALL SUBTREES minCost = Math.max(size_v, size_w); } else { tmpCost = (float) size_v * (float) pre2krSum2[w_in_preL] + cost_Lpointer_v[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = leftPath_v; } tmpCost = (float) size_v * (float) pre2revkrSum2[w_in_preL] + cost_Rpointer_v[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = rightPath_v; } tmpCost = (float) size_v * (float) pre2descSum2[w_in_preL] + cost_Ipointer_v[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = (int)strategypointer_v[w_in_preL] + 1; } tmpCost = (float) size_w * (float) krSum_v + cost2_L[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = -(preR_to_preL_2[preL_to_preR_2[w_in_preL] + size_w - 1] + pathIDOffset + 1); } tmpCost = (float) size_w * (float) revkrSum_v + cost2_R[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = w_in_preL + size_w - 1 + pathIDOffset + 1; } tmpCost = (float) size_w * (float) descSum_v + cost2_I[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = cost2_path[w] + pathIDOffset + 1; } } if(parent_v_preL != -1) { cost_Rpointer_parent_v[w] += minCost; tmpCost = -minCost + cost1_I[v][w]; if(tmpCost < cost1_I[parent_v_postL][w]) { cost_Ipointer_parent_v[w] = tmpCost; strategypointer_parent_v[w_in_preL] = strategypointer_v[w_in_preL]; } if(it1.ifNodeOfType(v_in_preL, 1)) { cost_Ipointer_parent_v[w] += cost_Rpointer_parent_v[w]; cost_Rpointer_parent_v[w] += cost_Rpointer_v[w] - minCost; } if(it1.ifNodeOfType(v_in_preL, 0)) cost_Lpointer_parent_v[w] += cost_Lpointer_v[w]; else cost_Lpointer_parent_v[w] += minCost; } if(parent_w_preL != -1) { cost2_R[parent_w_postL] += minCost; tmpCost = -minCost + cost2_I[w]; if(tmpCost < cost2_I[parent_w_postL]) { cost2_I[parent_w_postL] = tmpCost; cost2_path[parent_w_postL] = cost2_path[w]; } if(it2.ifNodeOfType(w_in_preL, 1)) { cost2_I[parent_w_postL] += cost2_R[parent_w_postL]; cost2_R[parent_w_postL] += cost2_R[w] - minCost; } if(it2.ifNodeOfType(w_in_preL, 0)) cost2_L[parent_w_postL] += cost2_L[w]; else cost2_L[parent_w_postL] += minCost; } strategypointer_v[w_in_preL] = strategyPath; } if(!it1.isLeaf(v_in_preL)) { Arrays.fill(cost1_L[v], 0); Arrays.fill(cost1_R[v], 0); Arrays.fill(cost1_I[v], 0); rowsToReuse_L.push(cost1_L[v]); rowsToReuse_R.push(cost1_R[v]); rowsToReuse_I.push(cost1_I[v]); } } return strategy; } public float[][] computeOptStrategyUsingAllPathsOn2_memopt_postR(InfoTree_PLUS it1, InfoTree_PLUS it2) { int size1 = it1.getSize(); int size2 = it2.getSize(); float strategy[][] = new float[size1][size2]; float cost1_L[][] = new float[size1][]; float cost1_R[][] = new float[size1][]; float cost1_I[][] = new float[size1][]; float cost2_L[] = new float[size2]; float cost2_R[] = new float[size2]; float cost2_I[] = new float[size2]; int cost2_path[] = new int[size2]; float leafRow[] = new float[size2]; int pathIDOffset = size1; float minCost = 0x7fffffffffffffffL; int strategyPath = -1; int[] pre2size1 = it1.sizes; int[] pre2size2 = it2.sizes; int[] pre2descSum1 = it1.preL_to_desc_sum; int[] pre2descSum2 = it2.preL_to_desc_sum; int[] pre2krSum1 = it1.preL_to_kr_sum; int[] pre2krSum2 = it2.preL_to_kr_sum; int[] pre2revkrSum1 = it1.preL_to_rev_kr_sum; int[] pre2revkrSum2 = it2.preL_to_rev_kr_sum; int[] preL_to_preR_1 = it1.preL_to_preR; int[] preL_to_preR_2 = it2.preL_to_preR; int[] preR_to_preL_1 = it1.preR_to_preL; int[] preR_to_preL_2 = it2.preR_to_preL; int[] pre2parent1 = it1.parents; int[] pre2parent2 = it2.parents; int size_v, parent_v, parent_w, size_w; int leftPath_v, rightPath_v; float[] cost_Lpointer_v, cost_Rpointer_v, cost_Ipointer_v; float[] strategypointer_v; float[] cost_Lpointer_parent_v = null, cost_Rpointer_parent_v = null, cost_Ipointer_parent_v = null; float[] strategypointer_parent_v = null; int krSum_v, revkrSum_v, descSum_v; boolean is_v_leaf; Stack<float[]> rowsToReuse_L = new Stack<float[]>(); Stack<float[]> rowsToReuse_R = new Stack<float[]>(); Stack<float[]> rowsToReuse_I = new Stack<float[]>(); for(int v = size1 - 1; v >= 0; v--) { is_v_leaf = it1.isLeaf(v); parent_v = pre2parent1[v]; strategypointer_v = strategy[v]; size_v = pre2size1[v]; leftPath_v = -(preR_to_preL_1[preL_to_preR_1[v] + pre2size1[v] - 1] + 1);// this is the left path's ID which is the leftmost leaf node: l-r_preorder(r-l_preorder(v) + |Fv| - 1) rightPath_v = v + pre2size1[v] - 1 + 1; // this is the right path's ID which is the rightmost leaf node: l-r_preorder(v) + |Fv| - 1 krSum_v = pre2krSum1[v]; revkrSum_v = pre2revkrSum1[v]; descSum_v = pre2descSum1[v]; if(is_v_leaf) { cost1_L[v] = leafRow; cost1_R[v] = leafRow; cost1_I[v] = leafRow; for(int i = 0; i < size2; i++) strategypointer_v[i] = v; } cost_Lpointer_v = cost1_L[v]; cost_Rpointer_v = cost1_R[v]; cost_Ipointer_v = cost1_I[v]; if(parent_v != -1 && cost1_L[parent_v] == null) { if (rowsToReuse_L.isEmpty()) { cost1_L[parent_v] = new float[size2]; cost1_R[parent_v] = new float[size2]; cost1_I[parent_v] = new float[size2]; } else { cost1_L[parent_v] = rowsToReuse_L.pop(); cost1_R[parent_v] = rowsToReuse_R.pop(); cost1_I[parent_v] = rowsToReuse_I.pop(); } } if (parent_v != -1) { cost_Lpointer_parent_v = cost1_L[parent_v]; cost_Rpointer_parent_v = cost1_R[parent_v]; cost_Ipointer_parent_v = cost1_I[parent_v]; strategypointer_parent_v = strategy[parent_v]; } Arrays.fill(cost2_L, 0L); Arrays.fill(cost2_R, 0L); Arrays.fill(cost2_I, 0L); Arrays.fill(cost2_path, 0); for(int w = size2 - 1; w >= 0; w--) { size_w = pre2size2[w]; if(it2.isLeaf(w)) { cost2_L[w] = 0L; cost2_R[w] = 0L; cost2_I[w] = 0L; cost2_path[w] = w; } minCost = 0x7fffffffffffffffL; strategyPath = -1; float tmpCost = 0x7fffffffffffffffL; if (size_v <= 2 || size_w <= 2) { // USE NEW SINGLE_PATH FUNCTIONS FOR SMALL SUBTREES minCost = Math.max(size_v, size_w); } else { tmpCost = (float) size_v * (float) pre2krSum2[w] + cost_Lpointer_v[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = leftPath_v; } tmpCost = (float) size_v * (float) pre2revkrSum2[w] + cost_Rpointer_v[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = rightPath_v; } tmpCost = (float) size_v * (float) pre2descSum2[w] + cost_Ipointer_v[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = (int)strategypointer_v[w] + 1; } tmpCost = (float) size_w * (float) krSum_v + cost2_L[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = -(preR_to_preL_2[preL_to_preR_2[w] + size_w - 1] + pathIDOffset + 1); } tmpCost = (float) size_w * (float) revkrSum_v + cost2_R[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = w + size_w - 1 + pathIDOffset + 1; } tmpCost = (float) size_w * (float) descSum_v + cost2_I[w]; if(tmpCost < minCost) { minCost = tmpCost; strategyPath = cost2_path[w] + pathIDOffset + 1; } } if(parent_v != -1) { cost_Lpointer_parent_v[w] += minCost; tmpCost = -minCost + cost1_I[v][w]; if(tmpCost < cost1_I[parent_v][w]) { cost_Ipointer_parent_v[w] = tmpCost; strategypointer_parent_v[w] = strategypointer_v[w]; } if(it1.ifNodeOfType(v, 0)) { cost_Ipointer_parent_v[w] += cost_Lpointer_parent_v[w]; cost_Lpointer_parent_v[w] += cost_Lpointer_v[w] - minCost; } if(it1.ifNodeOfType(v, 1)) cost_Rpointer_parent_v[w] += cost_Rpointer_v[w]; else cost_Rpointer_parent_v[w] += minCost; } parent_w = pre2parent2[w]; if(parent_w != -1) { cost2_L[parent_w] += minCost; tmpCost = -minCost + cost2_I[w]; if(tmpCost < cost2_I[parent_w]) { cost2_I[parent_w] = tmpCost; cost2_path[parent_w] = cost2_path[w]; } if(it2.ifNodeOfType(w, 0)) { cost2_I[parent_w] += cost2_L[parent_w]; cost2_L[parent_w] += cost2_L[w] - minCost; } if(it2.ifNodeOfType(w, 1)) cost2_R[parent_w] += cost2_R[w]; else cost2_R[parent_w] += minCost; } strategypointer_v[w] = strategyPath; } if(!it1.isLeaf(v)) { Arrays.fill(cost1_L[v], 0); Arrays.fill(cost1_R[v], 0); Arrays.fill(cost1_I[v], 0); rowsToReuse_L.push(cost1_L[v]); rowsToReuse_R.push(cost1_R[v]); rowsToReuse_I.push(cost1_I[v]); } } return strategy; } private float computeDistUsingLRHPathsStrArray(InfoTree_PLUS it1, InfoTree_PLUS it2) { int currentSubtree1 = it1.getCurrentNode(); int currentSubtree2 = it2.getCurrentNode(); int subtreeSize1 = it1.getSizes(currentSubtree1); int subtreeSize2 = it2.getSizes(currentSubtree2); // SINGLE-NODE SUBTREE if ((subtreeSize1 == 1 || subtreeSize2 == 1)) { if (it1.getCurrentNode() > 0 || it2.getCurrentNode() > 0) { return -1; } else { float result = Math.max(it1.getSizes(currentSubtree1), it2.getSizes(currentSubtree2)); boolean matchFound = false; for (int i = currentSubtree1; i < currentSubtree1 + it1.sizes[currentSubtree1]; i++) { for (int j = currentSubtree2; j < currentSubtree2 + it2.sizes[currentSubtree2]; j++) { if (!matchFound) matchFound = it1.labels[i] == it2.labels[j]; counter++; } } // TODO: modify to custom costs // unit cost only return result += (matchFound ? -1.0D : 0.0D); } } // END int strategyPathID = (int)delta[currentSubtree1][currentSubtree2]; byte strategyPathType = -1; int currentPathNode = Math.abs(strategyPathID) - 1; int pathIDOffset = it1.getSize(); int parent = -1; if(currentPathNode < pathIDOffset) { strategyPathType = getStrategyPathType(strategyPathID, pathIDOffset, it1, currentSubtree1, subtreeSize1); while((parent = it1.getParents(currentPathNode)) >= currentSubtree1) { int ai[]; int k = (ai = it1.getChildren(parent)).length; for(int i = 0; i < k; i++) { int child = ai[i]; if(child != currentPathNode) { it1.setCurrentNode(child); computeDistUsingLRHPathsStrArray(it1, it2); } } currentPathNode = parent; } it1.setCurrentNode(currentSubtree1); it1.setSwitched(false); it2.setSwitched(false); if (strategyPathType == 0) { return spfL(it1, it2); } if (strategyPathType == 1) { return spfR(it1, it2); } return spfWithPathID_opt_mem(it1, it2, Math.abs(strategyPathID) - 1, strategyPathType); } currentPathNode -= pathIDOffset; strategyPathType = getStrategyPathType(strategyPathID, pathIDOffset, it2, currentSubtree2, subtreeSize2); while((parent = it2.getParents(currentPathNode)) >= currentSubtree2) { int ai1[]; int l = (ai1 = it2.getChildren(parent)).length; for(int j = 0; j < l; j++) { int child = ai1[j]; if(child != currentPathNode) { it2.setCurrentNode(child); computeDistUsingLRHPathsStrArray(it1, it2); } } currentPathNode = parent; } it2.setCurrentNode(currentSubtree2); it1.setSwitched(true); it2.setSwitched(true); if (strategyPathType == 0) { return spfL(it2, it1); } if (strategyPathType == 1) { return spfR(it2, it1); } return spfWithPathID_opt_mem(it2, it1, Math.abs(strategyPathID) - pathIDOffset - 1, strategyPathType); } private float spfWithPathID_opt_mem(InfoTree_PLUS it1, InfoTree_PLUS it2, int pathID, byte pathType) { boolean treesSwitched = it1.isSwitched(); int[] it2labels = it2.labels; int[] it2sizes = it2.sizes; int currentSubtreePreL1 = it1.getCurrentNode(); int currentSubtreePreL2 = it2.getCurrentNode(); int currentForestSize1 = 0; int currentForestSize2 = 0; int tmpForestSize1 = 0; int subtreeSize2 = it2.getSizes(currentSubtreePreL2); int subtreeSize1 = it1.getSizes(currentSubtreePreL1); float[][] t = new float[subtreeSize2+1][subtreeSize2+1]; float[][] s = new float[subtreeSize1+1][subtreeSize2+1]; float minCost = -1; float sp1 = 0; float sp2 = 0; float sp3 = 0; int startPathNode = -1; int endPathNode = pathID; int it1PreLoff = endPathNode; int it2PreLoff = currentSubtreePreL2; int it1PreRoff = it1.getPreL_to_PreR(endPathNode); int it2PreRoff = it2.getPreL_to_PreR(it2PreLoff); // variable declarations which were inside the loops int rFlast,lFlast,endPathNode_in_preR,startPathNode_in_preR,parent_of_endPathNode,parent_of_endPathNode_in_preR, lFfirst,rFfirst,rGlast,rGfirst,lGfirst,rG_in_preL,rGminus1_in_preL,parent_of_rG_in_preL,lGlast,lF_in_preR,lFSubtreeSize,lFLabel, lGminus1_in_preR,parent_of_lG,parent_of_lG_in_preR,rF_in_preL,rFSubtreeSize, rGfirst_in_preL; boolean leftPart,rightPart,fForestIsTree,lFIsConsecutiveNodeOfCurrentPathNode,lFIsLeftSiblingOfCurrentPathNode, rFIsConsecutiveNodeOfCurrentPathNode,rFIsRightSiblingOfCurrentPathNode; float[] sp1spointer,sp2spointer,sp3spointer,sp3deltapointer,swritepointer,sp1tpointer,sp3tpointer; byte sp1source,sp3source; for(; endPathNode >= currentSubtreePreL1; endPathNode = it1.getParents(endPathNode)) { it1PreLoff = endPathNode; it1PreRoff = it1.getPreL_to_PreR(endPathNode); rFlast = -1; lFlast = -1; endPathNode_in_preR = it1.getPreL_to_PreR(endPathNode); startPathNode_in_preR = startPathNode == -1 ? 0x7fffffff : it1.getPreL_to_PreR(startPathNode); parent_of_endPathNode = it1.getParents(endPathNode); parent_of_endPathNode_in_preR = parent_of_endPathNode == -1 ? 0x7fffffff : it1.getPreL_to_PreR(parent_of_endPathNode); if(startPathNode - endPathNode > 1) { leftPart = true; } else { leftPart = false; } if(startPathNode >= 0 && startPathNode_in_preR - endPathNode_in_preR > 1) { rightPart = true; } else { rightPart = false; } if(pathType == 1 || pathType == 2 && leftPart) { if(startPathNode == -1) { rFfirst = endPathNode_in_preR; lFfirst = endPathNode; } else { rFfirst = startPathNode_in_preR; lFfirst = startPathNode - 1; } if(!rightPart) rFlast = endPathNode_in_preR; rGlast = it2.getPreL_to_PreR(currentSubtreePreL2); rGfirst = (rGlast + subtreeSize2) - 1; lFlast = rightPart ? endPathNode + 1 : endPathNode; fn[fn.length - 1] = -1; for(int i = currentSubtreePreL2; i < currentSubtreePreL2 + subtreeSize2; i++) { fn[i] = -1; ft[i] = -1; } tmpForestSize1 = currentForestSize1; for(int rG = rGfirst; rG >= rGlast; rG--) { lGfirst = it2.getPreR_to_PreL(rG); rG_in_preL = it2.getPreR_to_PreL(rG); rGminus1_in_preL = rG <= it2.getPreL_to_PreR(currentSubtreePreL2) ? 0x7fffffff : it2.getPreR_to_PreL(rG - 1); parent_of_rG_in_preL = it2.getParents(rG_in_preL); if(pathType == 1) { if (lGfirst == currentSubtreePreL2 || rGminus1_in_preL != parent_of_rG_in_preL) lGlast = lGfirst; else lGlast = it2.getParents(lGfirst)+1; } else { lGlast = lGfirst == currentSubtreePreL2 ? lGfirst : currentSubtreePreL2+1; } updateFnArray(it2.getPreL_to_LN(lGfirst), lGfirst, currentSubtreePreL2); updateFtArray(it2.getPreL_to_LN(lGfirst), lGfirst); int rF = rFfirst; currentForestSize1 = tmpForestSize1; for(int lF = lFfirst; lF >= lFlast; lF--) { if(lF == lFlast && !rightPart) rF = rFlast; currentForestSize1++; currentForestSize2 = it2.getSizes(lGfirst) - 1; lF_in_preR = it1.getPreL_to_PreR(lF); fForestIsTree = lF_in_preR == rF; lFSubtreeSize = it1.getSizes(lF); lFLabel = it1.getLabels(lF); lFIsConsecutiveNodeOfCurrentPathNode = startPathNode - lF == 1; lFIsLeftSiblingOfCurrentPathNode = lF + lFSubtreeSize == startPathNode; sp1spointer = s[(lF + 1) - it1PreLoff]; sp2spointer = s[lF - it1PreLoff]; sp3spointer = s[0]; sp3deltapointer = treesSwitched ? null : delta[lF]; swritepointer = s[lF - it1PreLoff]; sp1source = 1; sp3source = 1; if(fForestIsTree) { if(lFSubtreeSize == 1) sp1source = 3; else if(lFIsConsecutiveNodeOfCurrentPathNode) sp1source = 2; sp3 = 0; sp3source = 2; } else { if(lFIsConsecutiveNodeOfCurrentPathNode) sp1source = 2; sp3 = currentForestSize1 - lFSubtreeSize * costDel; if(lFIsLeftSiblingOfCurrentPathNode) sp3source = 3; } if (sp3source == 1) sp3spointer = s[(lF + lFSubtreeSize) - it1PreLoff]; if(currentForestSize2 + 1 == 1) sp2 = currentForestSize1 * costDel; else sp2 = q[lF]; int lG = lGfirst; currentForestSize2++; switch(sp1source) { case 1: sp1 = sp1spointer[lG - it2PreLoff]; break; case 2: sp1 = t[lG - it2PreLoff][rG - it2PreRoff]; break; case 3: sp1 = currentForestSize2 * costIns; break; } sp1 += costDel; minCost = sp1; sp2 += costIns; if(sp2 < minCost) minCost = sp2; if (sp3 < minCost) { sp3 += treesSwitched ? delta[lG][lF] : sp3deltapointer[lG]; if (sp3 < minCost) { if (lFLabel != it2labels[lG]) sp3 += costMatch; if(sp3 < minCost) minCost = sp3; } } swritepointer[lG - it2PreLoff] = minCost; lG = ft[lG]; counter++; while (lG >= lGlast) { currentForestSize2++; switch(sp1source) { case 1: sp1 = sp1spointer[lG - it2PreLoff] + costDel; break; case 2: sp1 = t[lG - it2PreLoff][rG - it2PreRoff] + costDel; break; case 3: sp1 = currentForestSize2 * costIns + costDel; break; } sp2 = sp2spointer[fn[lG] - it2PreLoff] + costDel; minCost = sp1; if(sp2 < minCost) minCost = sp2; sp3 = treesSwitched ? delta[lG][lF] : sp3deltapointer[lG]; if (sp3 < minCost) { switch(sp3source) { case 1: sp3 += sp3spointer[fn[(lG + it2sizes[lG]) - 1] - it2PreLoff]; break; case 2: sp3 += (currentForestSize2 - it2sizes[lG]) * costIns; break; case 3: sp3 += t[fn[(lG + it2sizes[lG]) - 1] - it2PreLoff][rG - it2PreRoff]; break; } if (sp3 < minCost) { if (lFLabel != it2labels[lG]) sp3 += costMatch; if(sp3 < minCost) minCost = sp3; } } swritepointer[lG - it2PreLoff] = minCost; lG = ft[lG]; counter++; } } if(rGminus1_in_preL == parent_of_rG_in_preL) { if(!rightPart) { if(leftPart) { if(treesSwitched) { delta[parent_of_rG_in_preL][endPathNode] = s[(lFlast + 1) - it1PreLoff][(rGminus1_in_preL + 1) - it2PreLoff]; } else { delta[endPathNode][parent_of_rG_in_preL] = s[(lFlast + 1) - it1PreLoff][(rGminus1_in_preL + 1) - it2PreLoff]; } } if(endPathNode > 0 && endPathNode == parent_of_endPathNode + 1 && endPathNode_in_preR == parent_of_endPathNode_in_preR + 1) { if(treesSwitched) { delta[parent_of_rG_in_preL][parent_of_endPathNode] = s[lFlast - it1PreLoff][(rGminus1_in_preL + 1) - it2PreLoff]; } else { delta[parent_of_endPathNode][parent_of_rG_in_preL] = s[lFlast - it1PreLoff][(rGminus1_in_preL + 1) - it2PreLoff]; } } } for(int lF = lFfirst; lF >= lFlast; lF--) { q[lF] = s[lF - it1PreLoff][(parent_of_rG_in_preL + 1) - it2PreLoff]; } } // TODO: first pointers can be precomputed for(int lG = lGfirst; lG >= lGlast; lG = ft[lG]) { t[lG - it2PreLoff][rG - it2PreRoff] = s[lFlast - it1PreLoff][lG - it2PreLoff]; } } } if(pathType == 0 || pathType == 2 && rightPart || pathType == 2 && !leftPart && !rightPart) { if(startPathNode == -1) { lFfirst = endPathNode; rFfirst = it1.getPreL_to_PreR(endPathNode); } else { rFfirst = it1.getPreL_to_PreR(startPathNode) - 1; lFfirst = endPathNode + 1; } lFlast = endPathNode; lGlast = currentSubtreePreL2; lGfirst = (lGlast + subtreeSize2) - 1; rFlast = it1.getPreL_to_PreR(endPathNode); fn[fn.length - 1] = -1; for(int i = currentSubtreePreL2; i < currentSubtreePreL2 + subtreeSize2; i++) { fn[i] = -1; ft[i] = -1; } tmpForestSize1 = currentForestSize1; for(int lG = lGfirst; lG >= lGlast; lG--) { rGfirst = it2.getPreL_to_PreR(lG); updateFnArray(it2.getPreR_to_LN(rGfirst), rGfirst, it2.getPreL_to_PreR(currentSubtreePreL2)); updateFtArray(it2.getPreR_to_LN(rGfirst), rGfirst); int lF = lFfirst; lGminus1_in_preR = lG <= currentSubtreePreL2 ? 0x7fffffff : it2.getPreL_to_PreR(lG - 1); parent_of_lG = it2.getParents(lG); parent_of_lG_in_preR = parent_of_lG == -1 ? -1 : it2.getPreL_to_PreR(parent_of_lG); currentForestSize1 = tmpForestSize1; if(pathType == 0) { if (lG == currentSubtreePreL2) rGlast = rGfirst; else if(it2.getChildren(parent_of_lG)[0] != lG) rGlast = rGfirst; else rGlast = it2.getPreL_to_PreR(parent_of_lG)+1; } else { rGlast = rGfirst == it2.getPreL_to_PreR(currentSubtreePreL2) ? rGfirst : it2.getPreL_to_PreR(currentSubtreePreL2); } for(int rF = rFfirst; rF >= rFlast; rF--) { if(rF == rFlast) lF = lFlast; currentForestSize1++; currentForestSize2 = it2.getSizes(lG) - 1; rF_in_preL = it1.getPreR_to_PreL(rF); rFSubtreeSize = it1.getSizes(rF_in_preL); if(startPathNode > 0) { rFIsConsecutiveNodeOfCurrentPathNode = startPathNode_in_preR - rF == 1; rFIsRightSiblingOfCurrentPathNode = rF + rFSubtreeSize == startPathNode_in_preR; } else { rFIsConsecutiveNodeOfCurrentPathNode = false; rFIsRightSiblingOfCurrentPathNode = false; } fForestIsTree = rF_in_preL == lF; int rFLabel = it1.getLabels(rF_in_preL); sp1spointer = s[(rF + 1) - it1PreRoff]; sp2spointer = s[rF - it1PreRoff]; sp3spointer = s[0]; sp3deltapointer = treesSwitched ? null : delta[rF_in_preL]; swritepointer = s[rF - it1PreRoff]; sp1tpointer = t[lG - it2PreLoff]; sp3tpointer = t[lG - it2PreLoff]; sp1source = 1; sp3source = 1; if(fForestIsTree) { if (rFSubtreeSize == 1) sp1source = 3; else if (rFIsConsecutiveNodeOfCurrentPathNode) sp1source = 2; sp3 = 0; sp3source = 2; } else { if (rFIsConsecutiveNodeOfCurrentPathNode) sp1source = 2; sp3 = currentForestSize1 - rFSubtreeSize * costDel; if (rFIsRightSiblingOfCurrentPathNode) sp3source = 3; } if (sp3source == 1) sp3spointer = s[(rF + rFSubtreeSize) - it1PreRoff]; if (currentForestSize2 + 1 == 1) sp2 = currentForestSize1 * costDel; else sp2 = q[rF]; int rG = rGfirst; rGfirst_in_preL = it2.getPreR_to_PreL(rGfirst); currentForestSize2++; switch(sp1source) { case 1: sp1 = sp1spointer[rG - it2PreRoff]; break; case 2: sp1 = sp1tpointer[rG - it2PreRoff]; break; case 3: sp1 = currentForestSize2 * costIns; break; } sp1 += costDel; minCost = sp1; sp2 += costIns; if(sp2 < minCost) minCost = sp2; if (sp3 < minCost) { sp3 += treesSwitched ? delta[rGfirst_in_preL][rF_in_preL] : sp3deltapointer[rGfirst_in_preL]; if (sp3 < minCost) { if (rFLabel != it2labels[rGfirst_in_preL]) sp3 += costMatch; if (sp3 < minCost) minCost = sp3; } } swritepointer[rG - it2PreRoff] = minCost; rG = ft[rG]; counter++; while (rG >= rGlast) { currentForestSize2++; rG_in_preL = it2.getPreR_to_PreL(rG); switch(sp1source) { case 1: sp1 = sp1spointer[rG - it2PreRoff] + costDel; break; case 2: sp1 = sp1tpointer[rG - it2PreRoff] + costDel; break; case 3: sp1 = currentForestSize2 * costIns + costDel; break; } sp2 = sp2spointer[fn[rG] - it2PreRoff] + costIns; minCost = sp1; if(sp2 < minCost) minCost = sp2; sp3 = treesSwitched ? delta[rG_in_preL][rF_in_preL] : sp3deltapointer[rG_in_preL]; if (sp3 < minCost) { switch(sp3source) { case 1: sp3 += sp3spointer[fn[(rG + it2sizes[rG_in_preL]) - 1] - it2PreRoff]; break; case 2: sp3 += (currentForestSize2 - it2sizes[rG_in_preL]) * costIns; break; case 3: sp3 += sp3tpointer[fn[(rG + it2sizes[rG_in_preL]) - 1] - it2PreRoff]; break; } if (sp3 < minCost) { if (rFLabel != it2labels[rG_in_preL]) sp3 += costMatch; if(sp3 < minCost) minCost = sp3; } } swritepointer[rG - it2PreRoff] = minCost; rG = ft[rG]; counter++; } } if(lG > currentSubtreePreL2 && lG - 1 == parent_of_lG) { if(rightPart) { if(treesSwitched) { delta[parent_of_lG][endPathNode] = s[(rFlast + 1) - it1PreRoff][(lGminus1_in_preR + 1) - it2PreRoff]; } else { delta[endPathNode][parent_of_lG] = s[(rFlast + 1) - it1PreRoff][(lGminus1_in_preR + 1) - it2PreRoff]; } } if(endPathNode > 0 && endPathNode == parent_of_endPathNode + 1 && endPathNode_in_preR == parent_of_endPathNode_in_preR + 1) if(treesSwitched) { delta[parent_of_lG][parent_of_endPathNode] = s[rFlast - it1PreRoff][(lGminus1_in_preR + 1) - it2PreRoff]; } else { delta[parent_of_endPathNode][parent_of_lG] = s[rFlast - it1PreRoff][(lGminus1_in_preR + 1) - it2PreRoff]; } for (int rF = rFfirst; rF >= rFlast; rF--) { q[rF] = s[rF - it1PreRoff][(parent_of_lG_in_preR + 1) - it2PreRoff]; } } // TODO: first pointers can be precomputed for (int rG = rGfirst; rG >= rGlast; rG = ft[rG]) { t[lG - it2PreLoff][rG - it2PreRoff] = s[rFlast - it1PreRoff][rG - it2PreRoff]; } } } startPathNode = endPathNode; } return minCost; } // ===================== BEGIN spfL private float spfL(InfoTree_PLUS it1, InfoTree_PLUS it2) { int[] keyRoots = new int[it2.sizes[it2.getCurrentNode()]]; Arrays.fill(keyRoots, -1); int pathID = it2.preR_to_preL[it2.preL_to_preR[it2.getCurrentNode()] + it2.sizes[it2.getCurrentNode()] - 1]; int firstKeyRoot = computeKeyRoots(it2, it2.getCurrentNode(), pathID, keyRoots, 0); float[][] forestdist = new float[it1.sizes[it1.getCurrentNode()]+1][it2.sizes[it2.getCurrentNode()]+1]; for (int i = firstKeyRoot-1; i >= 0; i--) { treeEditDist(it1, it2, it1.getCurrentNode(), keyRoots[i], forestdist); } return forestdist[it1.sizes[it1.getCurrentNode()]][it2.sizes[it2.getCurrentNode()]]; } private int computeKeyRoots(InfoTree_PLUS it2, int subtreeRootNode, int pathID, int[] keyRoots, int index) { keyRoots[index] = subtreeRootNode; index++; int pathNode = pathID; while (pathNode > subtreeRootNode) { int parent = it2.parents[pathNode]; for (int child : it2.getChildren(parent)) { if (child != pathNode) index = computeKeyRoots(it2, child, it2.preR_to_preL[it2.preL_to_preR[child]+it2.sizes[child]-1], keyRoots, index); } pathNode = parent; } return index; } private int getLLD(InfoTree_PLUS it, int postorder) { int preL = it.postL_to_preL[postorder]; return it.preL_to_postL[it.preR_to_preL[it.preL_to_preR[preL] + it.sizes[preL] - 1]]; } private void treeEditDist(InfoTree_PLUS it1, InfoTree_PLUS it2, int it1subtree, int it2subtree, float[][] forestdist) { // i,j have to be in postorder int i = it1.preL_to_postL[it1subtree]; int j = it2.preL_to_postL[it2subtree]; int ioff = getLLD(it1, i) - 1; int joff = getLLD(it2, j) - 1; float da = 0; float db = 0; float dc = 0; boolean switched = it1.isSwitched(); forestdist[0][0] = 0; for(int i1 = 1; i1 <= i - ioff; i1++) forestdist[i1][0] = forestdist[i1 - 1][0] + 1; for(int j1 = 1; j1 <= j - joff; j1++) forestdist[0][j1] = forestdist[0][j1 - 1] + 1; for(int i1 = 1; i1 <= i - ioff; i1++) { for(int j1 = 1; j1 <= j - joff; j1++) { counter++; float u = 0; if(it1.labels[it1.postL_to_preL[i1 + ioff]] != it2.labels[it2.postL_to_preL[j1 + joff]]) u = costMatch; if(getLLD(it1,i1 + ioff) == getLLD(it1,i) && getLLD(it2,j1 + joff) == getLLD(it2,j)) { da = forestdist[i1 - 1][j1] + costDel; db = forestdist[i1][j1 - 1] + costIns; dc = forestdist[i1 - 1][j1 - 1] + u; forestdist[i1][j1] = da >= db ? db >= dc ? dc : db : da >= dc ? dc : da; if (switched) { delta[it2.postL_to_preL[j1+joff]][it1.postL_to_preL[i1+ioff]] = forestdist[i1 - 1][j1 - 1]; } else { delta[it1.postL_to_preL[i1+ioff]][it2.postL_to_preL[j1+joff]] = forestdist[i1 - 1][j1 - 1]; } } else { da = forestdist[i1 - 1][j1] + costDel; db = forestdist[i1][j1 - 1] + costIns; dc = forestdist[getLLD(it1,i1 + ioff) - 1 - ioff][getLLD(it2,j1 + joff) - 1 - joff] + (switched ? delta[it2.postL_to_preL[j1 + joff]][it1.postL_to_preL[i1 + ioff]] : delta[it1.postL_to_preL[i1 + ioff]][it2.postL_to_preL[j1 + joff]]) + u; forestdist[i1][j1] = da >= db ? db >= dc ? dc : db : da >= dc ? dc : da; } } } } // ===================== END spfL // ===================== BEGIN spfR private float spfR(InfoTree_PLUS it1, InfoTree_PLUS it2) { int[] revKeyRoots = new int[it2.sizes[it2.getCurrentNode()]]; Arrays.fill(revKeyRoots, -1); int pathID = it2.getCurrentNode() + it2.sizes[it2.getCurrentNode()] - 1; // in r-l preorder int firstKeyRoot = computeRevKeyRoots(it2, it2.getCurrentNode(), pathID, revKeyRoots, 0); float[][] forestdist = new float[it1.sizes[it1.getCurrentNode()]+1][it2.sizes[it2.getCurrentNode()]+1]; for (int i = firstKeyRoot-1; i >= 0; i--) { revTreeEditDist(it1, it2, it1.getCurrentNode(), revKeyRoots[i], forestdist); } return forestdist[it1.sizes[it1.getCurrentNode()]][it2.sizes[it2.getCurrentNode()]]; } private int computeRevKeyRoots(InfoTree_PLUS it2, int subtreeRootNode, int pathID, int[] revKeyRoots, int index) { revKeyRoots[index] = subtreeRootNode; index++; int pathNode = pathID; while (pathNode > subtreeRootNode) { int parent = it2.parents[pathNode]; for (int child : it2.getChildren(parent)) { if (child != pathNode) index = computeRevKeyRoots(it2, child, child+it2.sizes[child]-1, revKeyRoots, index); } pathNode = parent; } return index; } private int getRLD(InfoTree_PLUS it, int revPostorder) { int preL = it.postR_to_preL[revPostorder]; return it.preL_to_postR[preL + it.sizes[preL] - 1]; } private void revTreeEditDist(InfoTree_PLUS it1, InfoTree_PLUS it2, int it1subtree, int it2subtree, float[][] forestdist) { // i,j have to be in r-l postorder int i = it1.preL_to_postR[it1subtree]; int j = it2.preL_to_postR[it2subtree]; int ioff = getRLD(it1, i) - 1; int joff = getRLD(it2, j) - 1; float da = 0; float db = 0; float dc = 0; boolean switched = it1.isSwitched(); forestdist[0][0] = 0; for(int i1 = 1; i1 <= i - ioff; i1++) forestdist[i1][0] = forestdist[i1 - 1][0] + 1; for(int j1 = 1; j1 <= j - joff; j1++) forestdist[0][j1] = forestdist[0][j1 - 1] + 1; for(int i1 = 1; i1 <= i - ioff; i1++) { for(int j1 = 1; j1 <= j - joff; j1++) { counter++; float u = 0; if(it1.labels[it1.postR_to_preL[i1 + ioff]] != it2.labels[it2.postR_to_preL[j1 + joff]]) u = costMatch; if(getRLD(it1,i1 + ioff) == getRLD(it1,i) && getRLD(it2,j1 + joff) == getRLD(it2,j)) { da = forestdist[i1 - 1][j1] + costDel; db = forestdist[i1][j1 - 1] + costIns; dc = forestdist[i1 - 1][j1 - 1] + u; forestdist[i1][j1] = da >= db ? db >= dc ? dc : db : da >= dc ? dc : da; if (switched) { delta[it2.postR_to_preL[j1+joff]][it1.postR_to_preL[i1+ioff]] = forestdist[i1 - 1][j1 - 1]; } else { delta[it1.postR_to_preL[i1+ioff]][it2.postR_to_preL[j1+joff]] = forestdist[i1 - 1][j1 - 1]; } } else { da = forestdist[i1 - 1][j1] + costDel; db = forestdist[i1][j1 - 1] + costIns; dc = forestdist[getRLD(it1,i1 + ioff) - 1 - ioff][getRLD(it2,j1 + joff) - 1 - joff] + (switched ? delta[it2.postR_to_preL[j1 + joff]][it1.postR_to_preL[i1 + ioff]] : delta[it1.postR_to_preL[i1 + ioff]][it2.postR_to_preL[j1 + joff]]) + u; forestdist[i1][j1] = da >= db ? db >= dc ? dc : db : da >= dc ? dc : da; } } } } // ===================== END spfR private byte getStrategyPathType(int pathIDWithPathIDOffset, int pathIDOffset, InfoTree_PLUS it, int currentRootNodePreL, int currentSubtreeSize) { if (Integer.signum(pathIDWithPathIDOffset) == -1) return LEFT; int pathID = Math.abs(pathIDWithPathIDOffset) - 1; if(pathID >= pathIDOffset) pathID = pathID - pathIDOffset; if(pathID == (currentRootNodePreL + currentSubtreeSize) - 1) return RIGHT; return INNER; } private void updateFnArray(int lnForNode, int node, int currentSubtreePreL) { if(lnForNode >= currentSubtreePreL) { fn[node] = fn[lnForNode]; fn[lnForNode] = node; } else { fn[node] = fn[fn.length - 1]; fn[fn.length - 1] = node; } } private void updateFtArray(int lnForNode, int node) { ft[node] = lnForNode; if(fn[node] > -1) ft[fn[node]] = node; } public void setCustomCosts(float costDel, float costIns, float costMatch) { this.costDel = costDel; this.costIns = costIns; this.costMatch = costMatch; } public InfoTree_PLUS getIt1() { return it1; } public InfoTree_PLUS getIt2() { return it2; } }
Bug fix: 2-node spf was considered in one of strategy computation functions.
src/distance/APTED.java
Bug fix: 2-node spf was considered in one of strategy computation functions.
<ide><path>rc/distance/APTED.java <ide> strategyPath = -1; <ide> float tmpCost = 0x7fffffffffffffffL; <ide> <del> if (size_v <= 2 || size_w <= 2) { // USE NEW SINGLE_PATH FUNCTIONS FOR SMALL SUBTREES <add> if (size_v <= 1 || size_w <= 1) { // USE NEW SINGLE_PATH FUNCTIONS FOR SMALL SUBTREES <ide> minCost = Math.max(size_v, size_w); <ide> } else { <ide> tmpCost = (float) size_v * (float) pre2krSum2[w] + cost_Lpointer_v[w];
Java
apache-2.0
5a1ecc8ee58cb582d05eb44aab7a7951bdbc648f
0
jberkel/sms-backup-plus,rsalmaso/sms-backup-plus,MadsAndreasen/sms-backup-plus,daniel-beet/sms-backup-plus,jberkel/sms-backup-plus,MadsAndreasen/sms-backup-plus,daniel-beet/sms-backup-plus,rsalmaso/sms-backup-plus,ashh87/sms-backup-plus,ashh87/sms-backup-plus
package com.zegoggles.smssync.activity; import android.preference.PreferenceManager; import com.zegoggles.smssync.R; import com.zegoggles.smssync.mail.DataType; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import static org.fest.assertions.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) @Ignore public class MainActivityTest { private MainActivity activity; @Before public void before() { activity = Robolectric.setupActivity(MainActivity.class); PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application).edit().clear().commit(); } @Test public void shouldDisplaySummaryOfEnabledBackupTypesDefault() throws Exception { assertThat(activity.summarizeAutoBackupSettings()).isEqualTo("Automatically backup SMS, MMS. You will also need to enable background data."); } @Test public void shouldDisplaySummaryOfEnabledBackupTypesNothingSelected() throws Exception { for (DataType t : DataType.values()) { activity.preferences.getDataTypePreferences().setBackupEnabled(false, t); } assertThat(activity.summarizeAutoBackupSettings()).isEqualTo( activity.getString(R.string.ui_enable_auto_sync_no_enabled_summary) ); } }
app/src/test/java/com/zegoggles/smssync/activity/MainActivityTest.java
package com.zegoggles.smssync.activity; import android.preference.PreferenceManager; import com.zegoggles.smssync.R; import com.zegoggles.smssync.mail.DataType; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import static org.fest.assertions.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) public class MainActivityTest { private MainActivity activity; @Before public void before() { activity = Robolectric.setupActivity(MainActivity.class); PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application).edit().clear().commit(); } @Test public void shouldDisplaySummaryOfEnabledBackupTypesDefault() throws Exception { assertThat(activity.summarizeAutoBackupSettings()).isEqualTo("Automatically backup SMS, MMS. You will also need to enable background data."); } @Test public void shouldDisplaySummaryOfEnabledBackupTypesNothingSelected() throws Exception { for (DataType t : DataType.values()) { activity.preferences.getDataTypePreferences().setBackupEnabled(false, t); } assertThat(activity.summarizeAutoBackupSettings()).isEqualTo( activity.getString(R.string.ui_enable_auto_sync_no_enabled_summary) ); } }
Ignore test
app/src/test/java/com/zegoggles/smssync/activity/MainActivityTest.java
Ignore test
<ide><path>pp/src/test/java/com/zegoggles/smssync/activity/MainActivityTest.java <ide> import com.zegoggles.smssync.R; <ide> import com.zegoggles.smssync.mail.DataType; <ide> import org.junit.Before; <add>import org.junit.Ignore; <ide> import org.junit.Test; <ide> import org.junit.runner.RunWith; <ide> import org.robolectric.Robolectric; <ide> import static org.fest.assertions.api.Assertions.assertThat; <ide> <ide> @RunWith(RobolectricTestRunner.class) <add>@Ignore <ide> public class MainActivityTest { <ide> private MainActivity activity; <ide>
JavaScript
mit
7efd3fe1689b15ba6d2d065e2720a532025774b8
0
hannes-hochreiner/more-podcasts,hannes-hochreiner/more-podcasts,hannes-hochreiner/more-podcasts
import PubSub from 'pubsub-js'; import {promisedPubSub as pps} from './utils'; export default class PlayerPresenter { constructor(view) { this._view = view; this._statusToken = PubSub.subscribe('system.playerService.statusChanged', this._handleStatusChange.bind(this)); this._updateCurrentState(); } _updateCurrentState() { return pps('system.playerService.getStatus').then(res => { this._handleStatusChange(null, res); }); } refreshEnclosure(item) { return pps('system.removeEnclosureBinaryByChannelIdItemId', { channelId: item.channelId, itemId: item.id }).then(() => { return pps('system.playerService.getStatus'); }).then(res => { this._handleStatusChange(null, res); }); } deleteEnclosure(item) { return pps('system.removeEnclosureDocAndBinaryByChannelItemId', { channelId: item.channelId, itemId: item.id }).then(() => { return pps('system.playerService.getStatus'); }).then(res => { this._handleStatusChange(null, res); }); } goToChannelListPage() { PubSub.publish('system.goToChannelListPage.request'); } goToInfoPage() { PubSub.publish('system.goToInfoPage.request'); } selectedItemChanged(item) { return pps('system.playerService.setItem', {item: item}).then(() => { return this._updateCurrentState(); }).catch(error => { let message = 'error loading item'; if (error.message) { message = error.message; } PubSub.publish('user.notification.showError', {error: {message: message}}); }); } volumeChanged(volume) { pps('system.playerService.setVolume', {volume: volume}); } speedChanged(speed) { pps('system.playerService.setSpeed', {speed: speed}); } currentTimeChanged(currentTime) { pps('system.playerService.setCurrentTime', {currentTime: currentTime}); } start() { return pps('system.playerService.setPlaying', {playing: true}).then(() => { this._view.playing = true; if (!this._intervalCancelToken) { this._intervalCancelToken = setInterval(this._updateCurrentTime.bind(this), 1000); } }); } stop() { let token = this._intervalCancelToken; delete this._intervalCancelToken; clearInterval(token); return pps('system.playerService.setPlaying', {playing: false}).then(res => { this._view.playing = false; }); } _updateCurrentTime() { pps('system.playerService.getCurrentTime').then(res => { this._view.currentTime = res.currentTime; }); } _handleStatusChange(topic, res) { this._view.playing = res.status.playing; this._view.selectedItem = res.status.item; this._view.duration = res.status.duration; this._view.currentTime = res.status.currentTime; this._view.volume = res.status.volume; this._view.speed = res.status.speed; this._view.items = res.status.playlist; if (this._intervalCancelToken && !res.status.playing) { let token = this._intervalCancelToken; delete this._intervalCancelToken; clearInterval(token); } if (!this._intervalCancelToken && res.status.playing) { this._intervalCancelToken = setInterval(this._updateCurrentTime.bind(this), 1000); } } finalize() { PubSub.unsubscribe(this._statusToken); if (this._intervalCancelToken) { clearInterval(this._intervalCancelToken); } } }
src/PlayerPresenter.js
import PubSub from 'pubsub-js'; import {promisedPubSub as pps} from './utils'; export default class PlayerPresenter { constructor(view) { this._view = view; this._statusToken = PubSub.subscribe('system.playerService.statusChanged', this._handleStatusChange.bind(this)); this._updateCurrentState(); } _updateCurrentState() { return pps('system.playerService.getStatus').then(res => { this._handleStatusChange(null, res); }); } refreshEnclosure(item) { return pps('system.removeEnclosureBinaryByChannelIdItemId', { channelId: item.channelId, itemId: item.id }).then(() => { return pps('system.playerService.getStatus'); }).then(res => { this._handleStatusChange(null, res); }); } deleteEnclosure(item) { return pps('system.removeEnclosureDocAndBinaryByChannelItemId', { channelId: item.channelId, itemId: item.id }).then(() => { return pps('system.playerService.getStatus'); }).then(res => { this._handleStatusChange(null, res); }); } goToChannelListPage() { PubSub.publish('system.goToChannelListPage.request'); } goToInfoPage() { PubSub.publish('system.goToInfoPage.request'); } selectedItemChanged(item) { return pps('system.playerService.setItem', {item: item}).then(() => { return this._updateCurrentState(); }).catch(error => { let message = 'error loading item'; if (error.message) { message = error.message; } PubSub.publish('user.notification.showError', {error: {message: message}}); }); } volumeChanged(volume) { pps('system.playerService.setVolume', {volume: volume}); } speedChanged(speed) { pps('system.playerService.setSpeed', {speed: speed}); } currentTimeChanged(currentTime) { pps('system.playerService.setCurrentTime', {currentTime: currentTime}); } start() { return pps('system.playerService.setPlaying', {playing: true}).then(() => { this._view.playing = true; if (!this._intervalCancelToken) { this._intervalCancelToken = setInterval(this._updateCurrentTime.bind(this), 1000); } }); } stop() { let token = this._intervalCancelToken; delete this._intervalCancelToken; clearInterval(token); return pps('system.playerService.setPlaying', {playing: false}).then(res => { this._view.playing = false; }); } _updateCurrentTime() { pps('system.playerService.getCurrentTime').then(res => { this._view.currentTime = res.currentTime; }); } _handleStatusChange(topic, res) { this._view.playing = res.status.playing; this._view.selectedItem = res.status.item; this._view.currentTime = res.status.currentTime; this._view.volume = res.status.volume; this._view.speed = res.status.speed; this._view.items = res.status.playlist; this._view.duration = res.status.duration; if (this._intervalCancelToken && !res.status.playing) { let token = this._intervalCancelToken; delete this._intervalCancelToken; clearInterval(token); } if (!this._intervalCancelToken && res.status.playing) { this._intervalCancelToken = setInterval(this._updateCurrentTime.bind(this), 1000); } } finalize() { PubSub.unsubscribe(this._statusToken); if (this._intervalCancelToken) { clearInterval(this._intervalCancelToken); } } }
switched order of property setting to avoid interval boundaries problems
src/PlayerPresenter.js
switched order of property setting to avoid interval boundaries problems
<ide><path>rc/PlayerPresenter.js <ide> _handleStatusChange(topic, res) { <ide> this._view.playing = res.status.playing; <ide> this._view.selectedItem = res.status.item; <add> this._view.duration = res.status.duration; <ide> this._view.currentTime = res.status.currentTime; <ide> this._view.volume = res.status.volume; <ide> this._view.speed = res.status.speed; <ide> this._view.items = res.status.playlist; <del> this._view.duration = res.status.duration; <ide> <ide> if (this._intervalCancelToken && !res.status.playing) { <ide> let token = this._intervalCancelToken;
Java
apache-2.0
6bcdd0737e25b701d8c6ac51b8ec13d8312f9cca
0
PeterIJia/android_xlight
package com.umarbhutta.xlightcompanion.main; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.ToggleButton; import com.jaygoo.widget.RangeSeekBar; import com.umarbhutta.xlightcompanion.R; import com.umarbhutta.xlightcompanion.SDK.xltDevice; import com.umarbhutta.xlightcompanion.Tools.AndroidBug54971Workaround; import com.umarbhutta.xlightcompanion.Tools.Logger; import com.umarbhutta.xlightcompanion.Tools.NetworkUtils; import com.umarbhutta.xlightcompanion.Tools.StatusReceiver; import com.umarbhutta.xlightcompanion.Tools.ToastUtil; import com.umarbhutta.xlightcompanion.Tools.UserUtils; import com.umarbhutta.xlightcompanion.glance.GlanceMainFragment; import com.umarbhutta.xlightcompanion.okHttp.HttpUtils; import com.umarbhutta.xlightcompanion.okHttp.NetConfig; import com.umarbhutta.xlightcompanion.okHttp.model.DeviceInfoResult; import com.umarbhutta.xlightcompanion.okHttp.model.Devicenodes; import com.umarbhutta.xlightcompanion.okHttp.model.Rows; import com.umarbhutta.xlightcompanion.okHttp.model.Scenarionodes; import com.umarbhutta.xlightcompanion.okHttp.model.SceneListResult; import com.umarbhutta.xlightcompanion.okHttp.requests.RequestDeviceDetailInfo; import com.umarbhutta.xlightcompanion.okHttp.requests.RequestSceneListInfo; import com.umarbhutta.xlightcompanion.scenario.ColorSelectActivity; import com.umarbhutta.xlightcompanion.scenario.ScenarioMainFragment; import com.umarbhutta.xlightcompanion.settings.BaseActivity; import com.umarbhutta.xlightcompanion.views.CircleDotView; import com.umarbhutta.xlightcompanion.views.DialogUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2017/3/5. * 设置灯 */ public class EditDeviceActivity extends BaseActivity implements View.OnClickListener { private TextView tvTitle; public SceneListResult mDeviceInfoResult; private Devicenodes deviceInfo; private int mPositon; private int red = 130; private int green = 255; private int blue = 0; private TextView mscenarioName; private static final String TAG = EditDeviceActivity.class.getSimpleName(); private static final String DEFAULT_LAMP_TEXT = "LIVING ROOM"; private static final String RINGALL_TEXT = "ALL RINGS"; private static final String RING1_TEXT = "RING 1"; private static final String RING2_TEXT = "RING 2"; private static final String RING3_TEXT = "RING 3"; private CheckBox powerSwitch; // private SeekBar brightnessSeekBar; private RangeSeekBar brightnessSeekBar; private SeekBar cctSeekBar; private TextView colorTextView; private Spinner scenarioSpinner; private LinearLayout scenarioNoneLL; private ToggleButton ring1Button, ring2Button, ring3Button; private TextView deviceRingLabel, powerLabel, brightnessLabel, cctLabel, colorLabel; private ImageView lightImageView; private LinearLayout llBack; private TextView btnSure; private LinearLayout linear; private LayoutInflater mInflater; private ArrayList<String> scenarioDropdown; private String colorHex; private boolean state = false; boolean ring1 = false, ring2 = false, ring3 = false; private Handler m_handlerControl; private CircleDotView circleIcon; private TextView cctLabelColor; private RelativeLayout rl_scenario; private LinearLayout colorLL; private View line2; private xltDevice mCurrentDevice; private HorizontalScrollView mHorizontalScrollView; private final MyStatusReceiver m_StatusReceiver = new MyStatusReceiver(); private class MyStatusReceiver extends StatusReceiver { @Override public void onReceive(Context context, Intent intent) { Logger.e(TAG, "data=" + intent.getIntExtra("nd", 0)); // powerSwitch.setChecked(mCurrentDevice.getState() > 0); // brightnessSeekBar.setProgress(mCurrentDevice.getBrightness()); // cctSeekBar.setProgress(mCurrentDevice.getCCT() - 2700); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_control); AndroidBug54971Workaround.assistActivity(findViewById(android.R.id.content)); mInflater = LayoutInflater.from(this); deviceInfo = (Devicenodes) getIntent().getSerializableExtra("info"); mPositon = getIntent().getIntExtra("position", 0); scenarioDropdown = new ArrayList<>(ScenarioMainFragment.name); scenarioDropdown.add(0, "None"); powerSwitch = (CheckBox) findViewById(R.id.powerSwitch); brightnessSeekBar = (RangeSeekBar) findViewById(R.id.brightnessSeekBar); cctSeekBar = (SeekBar) findViewById(R.id.cctSeekBar); cctSeekBar.setMax(6500 - 2700); colorTextView = (TextView) findViewById(R.id.colorTextView); scenarioNoneLL = (LinearLayout) findViewById(R.id.scenarioNoneLL); mHorizontalScrollView = (HorizontalScrollView) findViewById(R.id.hor_scroll_view); mHorizontalScrollView.setSmoothScrollingEnabled(true); scenarioNoneLL.setAlpha(1); ring1Button = (ToggleButton) findViewById(R.id.ring1Button); ring2Button = (ToggleButton) findViewById(R.id.ring2Button); ring3Button = (ToggleButton) findViewById(R.id.ring3Button); deviceRingLabel = (TextView) findViewById(R.id.deviceRingLabel); brightnessLabel = (TextView) findViewById(R.id.brightnessLabel); cctLabel = (TextView) findViewById(R.id.cctLabel); powerLabel = (TextView) findViewById(R.id.powerLabel); colorLabel = (TextView) findViewById(R.id.colorLabel); lightImageView = (ImageView) findViewById(R.id.lightImageView); linear = (LinearLayout) findViewById(R.id.ll_horizontal_scrollview); llBack = (LinearLayout) findViewById(R.id.ll_back); llBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); btnSure = (TextView) findViewById(R.id.tvEditSure); btnSure.setVisibility(View.INVISIBLE); tvTitle = (TextView) findViewById(R.id.tvTitle); tvTitle.setText(R.string.edit_device); mscenarioName = (TextView) findViewById(R.id.scenarioName); mscenarioName.setOnClickListener(this); cctLabelColor = (TextView) findViewById(R.id.cctLabelColor); scenarioSpinner = (Spinner) findViewById(R.id.scenarioSpinner); ArrayAdapter<String> scenarioAdapter = new ArrayAdapter<>(this, R.layout.control_scenario_spinner_item, scenarioDropdown); scenarioAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); scenarioSpinner.setAdapter(scenarioAdapter); circleIcon = new CircleDotView(this); RelativeLayout dotLayout = (RelativeLayout) findViewById(R.id.dotLayout); dotLayout.addView(circleIcon); rl_scenario = (RelativeLayout) findViewById(R.id.rl_scenario); line2 = findViewById(R.id.line2); colorLL = (LinearLayout) findViewById(R.id.colorLL); if (deviceInfo.devicenodetype == 1) { rl_scenario.setVisibility(View.GONE); colorLL.setVisibility(View.GONE); line2.setVisibility(View.GONE); } else { rl_scenario.setVisibility(View.VISIBLE); colorLL.setVisibility(View.VISIBLE); line2.setVisibility(View.VISIBLE); } mCurrentDevice = SlidingMenuMainActivity.xltDeviceMaps.get(deviceInfo.coreid); mCurrentDevice.setDeviceID(deviceInfo.nodeno); mCurrentDevice.QueryStatus();//查询所有的状态,通过handler或者广播发送过来。 mscenarioName.setText(deviceInfo.devicenodename); // powerSwitch.setChecked((mCurrentDevice.getState() == 0) ? false : true); // brightnessSeekBar.setProgress(mCurrentDevice.getBrightness()); // cctSeekBar.setProgress(mCurrentDevice.getCCT() - 2700); // // int R = mCurrentDevice.getRed(deviceInfo.nodeno); // int G = mCurrentDevice.getGreen(deviceInfo.nodeno); // int B = mCurrentDevice.getBlue(deviceInfo.nodeno); // int color = Color.rgb(R, G, B); // circleIcon.setColor(color); // colorTextView.setText("RGB(" + R + "," + G + "," + B + ")"); if (mCurrentDevice.getEnableEventBroadcast()) { IntentFilter intentFilter = new IntentFilter(xltDevice.bciDeviceStatus); intentFilter.setPriority(3); registerReceiver(m_StatusReceiver, intentFilter); } else { mCurrentDevice.setEnableEventBroadcast(true); IntentFilter intentFilter = new IntentFilter(xltDevice.bciDeviceStatus); intentFilter.setPriority(3); registerReceiver(m_StatusReceiver, intentFilter); } if (mCurrentDevice.getEnableEventSendMessage()) { upUIDateAddHandler(); } else { //打开 mCurrentDevice.setEnableEventSendMessage(true); upUIDateAddHandler(); } findViewById(com.umarbhutta.xlightcompanion.R.id.colorLayout).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onFabPressed(); } }); powerSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { //check if on or off Log.e(TAG, "The power value is " + (isChecked ? xltDevice.STATE_ON : xltDevice.STATE_OFF)); state = isChecked; int stateInt = mCurrentDevice.PowerSwitch(isChecked ? xltDevice.STATE_ON : xltDevice.STATE_OFF); Log.e(TAG, "stateInt value is= " + stateInt); deviceInfo.ison = isChecked ? xltDevice.STATE_ON : xltDevice.STATE_OFF; GlanceMainFragment.devicenodes.remove(mPositon); GlanceMainFragment.devicenodes.add(mPositon, deviceInfo); } }); /** * 亮度 */ brightnessSeekBar.setOnRangeChangedListener(new RangeSeekBar.OnRangeChangedListener() { @Override public void onRangeChanged(RangeSeekBar view, float min, float max, boolean isFromUser) { if (!isFromUser) { // Log.e(TAG, "The brightness value is " + (int) min + "view.getCurrentRange()=" + view.getCurrentRange()[0]); int brightnessInt = mCurrentDevice.ChangeBrightness((int) min); Log.e(TAG, "brightnessInt value is= " + brightnessInt); deviceInfo.brightness = (int) min; if (null != viewList && viewList.size() > 0) { viewList.get(0).callOnClick(); mHorizontalScrollView.smoothScrollTo(0, 0); } } } }); // brightnessSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { // @Override // public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // } // // @Override // public void onStartTrackingTouch(SeekBar seekBar) { // } // // @Override // public void onStopTrackingTouch(SeekBar seekBar) { // Log.e(TAG, "The brightness value is " + seekBar.getProgress()); // int brightnessInt = mCurrentDevice.ChangeBrightness(seekBar.getProgress()); // Log.e(TAG, "brightnessInt value is= " + brightnessInt); // deviceInfo.brightness = seekBar.getProgress(); // // if (null != viewList && viewList.size() > 0) { // viewList.get(0).callOnClick(); // mHorizontalScrollView.smoothScrollTo(0, 0); // } // } // }); /** *色温 */ cctSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int seekBarProgress = seekBar.getProgress() + 2700; if (seekBarProgress > 2700 && seekBarProgress < 3500) { cctLabelColor.setText(com.umarbhutta.xlightcompanion.R.string.nuan_bai); } if (seekBarProgress > 3500 && seekBarProgress < 5500) { cctLabelColor.setText(com.umarbhutta.xlightcompanion.R.string.zhengbai); } if (seekBarProgress > 5500 && seekBarProgress < 6500) { cctLabelColor.setText(com.umarbhutta.xlightcompanion.R.string.lengbai); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { Log.d(TAG, "The CCT value is " + seekBar.getProgress() + 2700); int seekBarProgress = seekBar.getProgress() + 2700; int cctInt = mCurrentDevice.ChangeCCT(seekBarProgress); Log.e(TAG, "cctInt value is= " + cctInt); if (null != viewList && viewList.size() > 0) { viewList.get(0).callOnClick(); mHorizontalScrollView.smoothScrollTo(0, 0); } } }); scenarioSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (parent.getItemAtPosition(position).toString() == "None") { //scenarioNoneLL.animate().alpha(1).setDuration(600).start(); //enable all views below spinner disableEnableControls(true); } else { //if anything but "None" is selected, fade scenarioNoneLL out //scenarioNoneLL.animate().alpha(0).setDuration(500).start(); //disable all views below spinner disableEnableControls(false); //ParticleAdapter.JSONCommandScenario(ParticleAdapter.DEFAULT_DEVICE_ID, position); //position passed into above function corresponds to the scenarioId i.e. s1, s2, s3 to trigger mCurrentDevice.ChangeScenario(position); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ring1Button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ring1 = isChecked; updateDeviceRingLabel(); } }); ring2Button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ring2 = isChecked; updateDeviceRingLabel(); } }); ring3Button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ring3 = isChecked; updateDeviceRingLabel(); } }); initScenario();//初始化场景 } //获取监听 private void upUIDateAddHandler() { m_handlerControl = new Handler() { public void handleMessage(Message msg) { Logger.e(TAG, "handler_msg=" + msg.getData().toString()); int intValue = msg.getData().getInt("State", -255); if (intValue != -255) { powerSwitch.setChecked(intValue > 0); } intValue = msg.getData().getInt("BR", -255); if (intValue != -255) { // brightnessSeekBar.setProgress(intValue); brightnessSeekBar.setValue(intValue); } intValue = msg.getData().getInt("CCT", -255); if (intValue != -255) { cctSeekBar.setProgress(intValue - 2700); } //颜色 int R = 0; int G = 0; int B = 0; intValue = msg.getData().getInt("R", -255); if (intValue != -255) { R = intValue; } intValue = msg.getData().getInt("G", -255); if (intValue != -255) { G = intValue; } intValue = msg.getData().getInt("B", -255); if (intValue != -255) { B = intValue; } int color = Color.rgb(R, G, B); circleIcon.setColor(color); colorTextView.setText("RGB(" + R + "," + G + "," + B + ")"); } }; mCurrentDevice.addDeviceEventHandler(m_handlerControl); // updateDeviceRingLabel();//这个作用是 切换灯上部图片的 } private EditText et; @Override public void onClick(View view) { switch (view.getId()) { case R.id.scenarioName: String title = getString(R.string.edit_device_name); et = (EditText) mInflater.inflate(R.layout.layout_edittext, null); new DialogUtils().getEditTextDialog(EditDeviceActivity.this, title, mscenarioName.getText().toString(), new DialogUtils.OnClickOkBtnListener() { @Override public void onClickOk(String editTextStr) { if (TextUtils.isEmpty(editTextStr)) { ToastUtil.showToast(EditDeviceActivity.this, getString(R.string.content_is_null)); return; } editDeViceInfo(editTextStr); } }); break; } } @Override public void onDestroy() { mCurrentDevice.removeDeviceEventHandler(m_handlerControl); if (mCurrentDevice.getEnableEventBroadcast()) { unregisterReceiver(m_StatusReceiver); } mCurrentDevice.Disconnect(); super.onDestroy(); } private void disableEnableControls(boolean isEnabled) { powerSwitch.setEnabled(isEnabled); colorTextView.setEnabled(isEnabled); brightnessSeekBar.setEnabled(isEnabled); cctSeekBar.setEnabled(isEnabled); int selectColor = R.color.colorAccent, allLabels = R.color.textColorPrimary; if (isEnabled) { selectColor = R.color.colorAccent; allLabels = R.color.textColorPrimary; } else { selectColor = R.color.colorDisabled; allLabels = R.color.colorDisabled; } colorTextView.setTextColor(ContextCompat.getColor(this, selectColor)); powerLabel.setTextColor(ContextCompat.getColor(this, allLabels)); brightnessLabel.setTextColor(ContextCompat.getColor(this, allLabels)); cctLabel.setTextColor(ContextCompat.getColor(this, allLabels)); colorLabel.setTextColor(ContextCompat.getColor(this, allLabels)); } private void updateDeviceRingLabel() { String label = mCurrentDevice.getDeviceName(); if (ring1 && ring2 && ring3) { label += ": " + RINGALL_TEXT; lightImageView.setImageResource(R.drawable.aquabg_ring123); } else if (!ring1 && !ring2 && !ring3) { label += ": " + RINGALL_TEXT; lightImageView.setImageResource(R.drawable.aquabg_noring); } else if (ring1 && ring2) { label += ": " + RING1_TEXT + " & " + RING2_TEXT; lightImageView.setImageResource(R.drawable.aquabg_ring12); } else if (ring2 && ring3) { label += ": " + RING2_TEXT + " & " + RING3_TEXT; lightImageView.setImageResource(R.drawable.aquabg_ring23); } else if (ring1 && ring3) { label += ": " + RING1_TEXT + " & " + RING3_TEXT; lightImageView.setImageResource(R.drawable.aquabg_ring13); } else if (ring1) { label += ": " + RING1_TEXT; lightImageView.setImageResource(R.drawable.aquabg_ring1); } else if (ring2) { label += ": " + RING2_TEXT; lightImageView.setImageResource(R.drawable.aquabg_ring2); } else if (ring3) { label += ": " + RING3_TEXT; lightImageView.setImageResource(R.drawable.aquabg_ring3); } else { label += ""; lightImageView.setImageResource(R.drawable.aquabg_noring); } deviceRingLabel.setText(label); } private void onFabPressed() { Intent intent = new Intent(EditDeviceActivity.this, ColorSelectActivity.class); startActivityForResult(intent, 1); } private void initScenario() { RequestSceneListInfo.getInstance().getSceneListInfo(this, new RequestSceneListInfo.OnRequestFirstPageInfoCallback() { @Override public void onRequestFirstPageInfoSuccess(final SceneListResult mDeviceInfoResult) { runOnUiThread(new Runnable() { @Override public void run() { EditDeviceActivity.this.mDeviceInfoResult = mDeviceInfoResult; initSceneList(); } }); } @Override public void onRequestFirstPageInfoFail(int code, final String errMsg) { runOnUiThread(new Runnable() { @Override public void run() { ToastUtil.showToast(EditDeviceActivity.this, "" + errMsg); } }); } }); // 场景列表跳到对应的位置 RequestDeviceDetailInfo.getInstance().getDeviceInfo(this, deviceInfo.id, new RequestDeviceDetailInfo.OnRequestFirstPageInfoCallback() { @Override public void onRequestFirstPageInfoSuccess(DeviceInfoResult mDeviceInfoResult) { Logger.i("详细信息 = " + mDeviceInfoResult.toString()); } @Override public void onRequestFirstPageInfoFail(int code, String errMsg) { } }); } private List<View> viewList = new ArrayList<View>(); private List<TextView> textViews = new ArrayList<TextView>(); private void initSceneList() { for (int i = 0; i < mDeviceInfoResult.rows.size() + 1; i++) { View view; TextView textView; if (i == 0) { view = mInflater.inflate(R.layout.add_scenario_zdy_item, linear, false); textView = (TextView) view.findViewById(R.id.textView); view.setBackgroundResource(R.drawable.add_scenario_blue_bg); } else { Rows info = mDeviceInfoResult.rows.get(i - 1); view = mInflater.inflate(R.layout.add_scenario_item, linear, false); view.setBackgroundResource(R.drawable.add_scenario_bg); textView = (TextView) view.findViewById(R.id.sceneName); textView.setText(info.scenarioname); } viewList.add(view); textViews.add(textView); view.setTag(i); view.setOnClickListener(mSceneClick); linear.addView(view); } linear.invalidate(); if (deviceInfo.devicenodetype != 1 && !TextUtils.isEmpty(deviceInfo.scenarioId)) { // if (deviceInfo.devicenodetype != 1) {//测试专用 for (int i = 0; i < viewList.size(); i++) { if (i != 0 && deviceInfo.scenarioId.equals(String.valueOf(mDeviceInfoResult.rows.get(i - 1).id))) { // if (i != 0 && "53".equals(String.valueOf(mDeviceInfoResult.rows.get(i - 1).id))) { View cView = viewList.get(i); cView.callOnClick(); Message msg = Message.obtain(); msg.arg1 = i; handler.sendMessageDelayed(msg, 100); break; } } } } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); int index = msg.arg1; View cView = viewList.get(index); int[] location = new int[2]; cView.getLocationOnScreen(location); // Logger.i("left1 = " + location[0] + ", " + location[1]); mHorizontalScrollView.scrollTo(location[0] - 100, 0); } }; /** * 当前场景 */ private Rows curSene = null; View.OnClickListener mSceneClick = new View.OnClickListener() { @Override public void onClick(View v) { int index = (int) v.getTag(); if (0 == index) { curSene = null; } else { Rows sceneInfo = mDeviceInfoResult.rows.get(index - 1); curSene = sceneInfo; updateSceneInfo(sceneInfo); } for (int i = 0; i < viewList.size(); i++) { View view = viewList.get(i); TextView textView = textViews.get(i); view.setBackgroundResource(R.drawable.add_scenario_bg); textView.setTextColor(getResources().getColor(R.color.black)); } View mView = viewList.get(index); mView.setBackgroundResource(R.drawable.add_scenario_blue_bg); TextView mText = textViews.get(index); mText.setTextColor(getResources().getColor(R.color.white)); editDeViceInfo(null); } }; /** * 选择了某一个场景 * * @param sceneInfo */ private void updateSceneInfo(Rows sceneInfo) { if (null == sceneInfo) { return; } // powerSwitch.setChecked((1 == sceneInfo.ison) ? true : false); if (mCurrentDevice.isSunny()) { // brightnessSeekBar.setProgress(sceneInfo.brightness); brightnessSeekBar.setValue(sceneInfo.brightness); mCurrentDevice.ChangeBrightness(sceneInfo.brightness); cctSeekBar.setProgress(sceneInfo.cct - 2700); mCurrentDevice.ChangeCCT(sceneInfo.cct - 2700); mCurrentDevice.ChangeScenario(sceneInfo.scenarionodes.get(0).scenarioId); } else { cctSeekBar.setProgress(sceneInfo.cct - 2700); mCurrentDevice.ChangeCCT(sceneInfo.cct - 2700); Scenarionodes currentNode = sceneInfo.scenarionodes.get(0);//当前灯 int R = 0; int G = 0; int B = 0; R = currentNode.R; G = currentNode.G; B = currentNode.B; int color = Color.rgb(R, G, B); circleIcon.setColor(color); colorTextView.setText("RGB(" + R + "," + G + "," + B + ")"); mCurrentDevice.ChangeColor(xltDevice.RING_ID_ALL, true, sceneInfo.brightness, 26, currentNode.R, currentNode.G, currentNode.B); } // brightnessSeekBar.setProgress(sceneInfo.brightness); // cctSeekBar.setProgress(sceneInfo.cct - 2700); //颜色 // int R = 0; // int G = 0; // int B = 0; // Scenarionodes currentNode= sceneInfo.scenarionodes.get(0);//当前灯 // R = currentNode.R; // G = currentNode.G; // B = currentNode.B; // int color = Color.rgb(R, G, B); // circleIcon.setColor(color); // colorTextView.setText("RGB(" + R + "," + G + "," + B + ")"); } /** * 提交编辑设备 */ private void editDeViceInfo(String newDeviceName) { if (!NetworkUtils.isNetworkAvaliable(this)) { ToastUtil.showToast(this, R.string.net_error); return; } final String deviceName = TextUtils.isEmpty(newDeviceName) ? mscenarioName.getText().toString() : newDeviceName; if (TextUtils.isEmpty(deviceName)) { ToastUtil.showToast(this, getString(R.string.please_set_lamp_name)); return; } JSONObject jsonObject = new JSONObject(); try { jsonObject.put("ison", powerSwitch.isChecked() ? 1 : 0); jsonObject.put("userId", UserUtils.getUserInfo(this).getId()); // jsonObject.put("devicename", deviceName);。。。。。。。。。 JSONArray devicenodes = new JSONArray(); jsonObject.put("devicenodes", devicenodes); JSONObject devicenodesJSONObject = new JSONObject(); devicenodes.put(devicenodesJSONObject); devicenodesJSONObject.put("devicenodeId", deviceInfo.id); devicenodesJSONObject.put("devicenodename", deviceName); devicenodesJSONObject.put("ison", powerSwitch.isChecked() ? 1 : 0); if (null == curSene) { devicenodesJSONObject.put("scenarioId", 0); // 场景id,自定义场景 } else { devicenodesJSONObject.put("scenarioId", curSene.id); // 场景id } JSONArray deviceringsArr = new JSONArray(); devicenodesJSONObject.put("devicerings", deviceringsArr); for (int i = 0; i < 3; i++) { JSONObject deviceringsObj = new JSONObject(); deviceringsArr.put(deviceringsObj); deviceringsObj.put("ison", powerSwitch.isChecked() ? 1 : 0); deviceringsObj.put("R", red); deviceringsObj.put("G", green); deviceringsObj.put("B", blue); deviceringsObj.put("color", "rgb(" + red + "," + green + "," + blue + ")"); deviceringsObj.put("cct", cctSeekBar.getProgress() + 2700); deviceringsObj.put("brightness", brightnessSeekBar.getCurrentRange()[0]); } } catch (JSONException e) { e.printStackTrace(); } HttpUtils.getInstance().putRequestInfo(NetConfig.URL_EDIT_DEVICE_INFO + deviceInfo.deviceId + "?access_token=" + UserUtils.getUserInfo(this).getAccess_token(), jsonObject.toString(), null, new HttpUtils.OnHttpRequestCallBack() { @Override public void onHttpRequestSuccess(Object result) { Logger.i("编辑成功 = " + result.toString()); runOnUiThread(new Runnable() { @Override public void run() { // ToastUtil.showToast(EditDeviceActivity.this, getString(R.string.modify_success)); // setResult(0); // EditDeviceActivity.this.finish(); if (!TextUtils.isEmpty(deviceName)) { deviceInfo.devicenodename = deviceName; mscenarioName.setText(deviceName); } } }); } @Override public void onHttpRequestFail(int code, final String errMsg) { Logger.i("编辑失败 = " + errMsg); runOnUiThread(new Runnable() { @Override public void run() { ToastUtil.showToast(EditDeviceActivity.this, getString(R.string.modify_fail) + errMsg); } }); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == -1) { int color = data.getIntExtra("color", -1); if (-1 != color) { red = (color & 0xff0000) >> 16; green = (color & 0x00ff00) >> 8; blue = (color & 0x0000ff); } circleIcon.setColor(color); colorTextView.setText("RGB(" + red + "," + green + "," + blue + ")"); int br = (int) brightnessSeekBar.getCurrentRange()[0]; int ww = 0; mCurrentDevice.ChangeColor(xltDevice.RING_ID_ALL, state, br, ww, red, green, blue); mCurrentDevice.setRed(xltDevice.RING_ID_ALL, red); mCurrentDevice.setGreen(xltDevice.RING_ID_ALL, green); mCurrentDevice.setBlue(xltDevice.RING_ID_ALL, blue); } } }
app/src/main/java/com/umarbhutta/xlightcompanion/main/EditDeviceActivity.java
package com.umarbhutta.xlightcompanion.main; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.ToggleButton; import com.jaygoo.widget.RangeSeekBar; import com.umarbhutta.xlightcompanion.R; import com.umarbhutta.xlightcompanion.SDK.xltDevice; import com.umarbhutta.xlightcompanion.Tools.AndroidBug54971Workaround; import com.umarbhutta.xlightcompanion.Tools.Logger; import com.umarbhutta.xlightcompanion.Tools.NetworkUtils; import com.umarbhutta.xlightcompanion.Tools.StatusReceiver; import com.umarbhutta.xlightcompanion.Tools.ToastUtil; import com.umarbhutta.xlightcompanion.Tools.UserUtils; import com.umarbhutta.xlightcompanion.glance.GlanceMainFragment; import com.umarbhutta.xlightcompanion.okHttp.HttpUtils; import com.umarbhutta.xlightcompanion.okHttp.NetConfig; import com.umarbhutta.xlightcompanion.okHttp.model.DeviceInfoResult; import com.umarbhutta.xlightcompanion.okHttp.model.Devicenodes; import com.umarbhutta.xlightcompanion.okHttp.model.Rows; import com.umarbhutta.xlightcompanion.okHttp.model.Scenarionodes; import com.umarbhutta.xlightcompanion.okHttp.model.SceneListResult; import com.umarbhutta.xlightcompanion.okHttp.requests.RequestDeviceDetailInfo; import com.umarbhutta.xlightcompanion.okHttp.requests.RequestSceneListInfo; import com.umarbhutta.xlightcompanion.scenario.ColorSelectActivity; import com.umarbhutta.xlightcompanion.scenario.ScenarioMainFragment; import com.umarbhutta.xlightcompanion.settings.BaseActivity; import com.umarbhutta.xlightcompanion.views.CircleDotView; import com.umarbhutta.xlightcompanion.views.DialogUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2017/3/5. * 设置灯 */ public class EditDeviceActivity extends BaseActivity implements View.OnClickListener { private TextView tvTitle; public SceneListResult mDeviceInfoResult; private Devicenodes deviceInfo; private int mPositon; private int red = 130; private int green = 255; private int blue = 0; private TextView mscenarioName; private static final String TAG = EditDeviceActivity.class.getSimpleName(); private static final String DEFAULT_LAMP_TEXT = "LIVING ROOM"; private static final String RINGALL_TEXT = "ALL RINGS"; private static final String RING1_TEXT = "RING 1"; private static final String RING2_TEXT = "RING 2"; private static final String RING3_TEXT = "RING 3"; private CheckBox powerSwitch; // private SeekBar brightnessSeekBar; private RangeSeekBar brightnessSeekBar; private SeekBar cctSeekBar; private TextView colorTextView; private Spinner scenarioSpinner; private LinearLayout scenarioNoneLL; private ToggleButton ring1Button, ring2Button, ring3Button; private TextView deviceRingLabel, powerLabel, brightnessLabel, cctLabel, colorLabel; private ImageView lightImageView; private LinearLayout llBack; private TextView btnSure; private LinearLayout linear; private LayoutInflater mInflater; private ArrayList<String> scenarioDropdown; private String colorHex; private boolean state = false; boolean ring1 = false, ring2 = false, ring3 = false; private Handler m_handlerControl; private CircleDotView circleIcon; private TextView cctLabelColor; private RelativeLayout rl_scenario; private LinearLayout colorLL; private View line2; private xltDevice mCurrentDevice; private HorizontalScrollView mHorizontalScrollView; private final MyStatusReceiver m_StatusReceiver = new MyStatusReceiver(); private class MyStatusReceiver extends StatusReceiver { @Override public void onReceive(Context context, Intent intent) { Logger.e(TAG, "data=" + intent.getIntExtra("nd", 0)); // powerSwitch.setChecked(mCurrentDevice.getState() > 0); // brightnessSeekBar.setProgress(mCurrentDevice.getBrightness()); // cctSeekBar.setProgress(mCurrentDevice.getCCT() - 2700); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_control); AndroidBug54971Workaround.assistActivity(findViewById(android.R.id.content)); mInflater = LayoutInflater.from(this); deviceInfo = (Devicenodes) getIntent().getSerializableExtra("info"); mPositon = getIntent().getIntExtra("position", 0); scenarioDropdown = new ArrayList<>(ScenarioMainFragment.name); scenarioDropdown.add(0, "None"); powerSwitch = (CheckBox) findViewById(R.id.powerSwitch); brightnessSeekBar = (RangeSeekBar) findViewById(R.id.brightnessSeekBar); cctSeekBar = (SeekBar) findViewById(R.id.cctSeekBar); cctSeekBar.setMax(6500 - 2700); colorTextView = (TextView) findViewById(R.id.colorTextView); scenarioNoneLL = (LinearLayout) findViewById(R.id.scenarioNoneLL); mHorizontalScrollView = (HorizontalScrollView) findViewById(R.id.hor_scroll_view); mHorizontalScrollView.setSmoothScrollingEnabled(true); scenarioNoneLL.setAlpha(1); ring1Button = (ToggleButton) findViewById(R.id.ring1Button); ring2Button = (ToggleButton) findViewById(R.id.ring2Button); ring3Button = (ToggleButton) findViewById(R.id.ring3Button); deviceRingLabel = (TextView) findViewById(R.id.deviceRingLabel); brightnessLabel = (TextView) findViewById(R.id.brightnessLabel); cctLabel = (TextView) findViewById(R.id.cctLabel); powerLabel = (TextView) findViewById(R.id.powerLabel); colorLabel = (TextView) findViewById(R.id.colorLabel); lightImageView = (ImageView) findViewById(R.id.lightImageView); linear = (LinearLayout) findViewById(R.id.ll_horizontal_scrollview); llBack = (LinearLayout) findViewById(R.id.ll_back); llBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); btnSure = (TextView) findViewById(R.id.tvEditSure); btnSure.setVisibility(View.INVISIBLE); tvTitle = (TextView) findViewById(R.id.tvTitle); tvTitle.setText(R.string.edit_device); mscenarioName = (TextView) findViewById(R.id.scenarioName); mscenarioName.setOnClickListener(this); cctLabelColor = (TextView) findViewById(R.id.cctLabelColor); scenarioSpinner = (Spinner) findViewById(R.id.scenarioSpinner); ArrayAdapter<String> scenarioAdapter = new ArrayAdapter<>(this, R.layout.control_scenario_spinner_item, scenarioDropdown); scenarioAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); scenarioSpinner.setAdapter(scenarioAdapter); circleIcon = new CircleDotView(this); RelativeLayout dotLayout = (RelativeLayout) findViewById(R.id.dotLayout); dotLayout.addView(circleIcon); rl_scenario = (RelativeLayout) findViewById(R.id.rl_scenario); line2 = findViewById(R.id.line2); colorLL = (LinearLayout) findViewById(R.id.colorLL); if (deviceInfo.devicenodetype == 1) { rl_scenario.setVisibility(View.GONE); colorLL.setVisibility(View.GONE); line2.setVisibility(View.GONE); } else { rl_scenario.setVisibility(View.VISIBLE); colorLL.setVisibility(View.VISIBLE); line2.setVisibility(View.VISIBLE); } mCurrentDevice = SlidingMenuMainActivity.xltDeviceMaps.get(deviceInfo.coreid); mCurrentDevice.setDeviceID(deviceInfo.nodeno); mCurrentDevice.QueryStatus();//查询所有的状态,通过handler或者广播发送过来。 mscenarioName.setText(deviceInfo.devicenodename); // powerSwitch.setChecked((mCurrentDevice.getState() == 0) ? false : true); // brightnessSeekBar.setProgress(mCurrentDevice.getBrightness()); // cctSeekBar.setProgress(mCurrentDevice.getCCT() - 2700); // // int R = mCurrentDevice.getRed(deviceInfo.nodeno); // int G = mCurrentDevice.getGreen(deviceInfo.nodeno); // int B = mCurrentDevice.getBlue(deviceInfo.nodeno); // int color = Color.rgb(R, G, B); // circleIcon.setColor(color); // colorTextView.setText("RGB(" + R + "," + G + "," + B + ")"); if (mCurrentDevice.getEnableEventBroadcast()) { IntentFilter intentFilter = new IntentFilter(xltDevice.bciDeviceStatus); intentFilter.setPriority(3); registerReceiver(m_StatusReceiver, intentFilter); } else { mCurrentDevice.setEnableEventBroadcast(true); IntentFilter intentFilter = new IntentFilter(xltDevice.bciDeviceStatus); intentFilter.setPriority(3); registerReceiver(m_StatusReceiver, intentFilter); } if (mCurrentDevice.getEnableEventSendMessage()) { upUIDateAddHandler(); } else { //打开 mCurrentDevice.setEnableEventSendMessage(true); upUIDateAddHandler(); } findViewById(com.umarbhutta.xlightcompanion.R.id.colorLayout).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onFabPressed(); } }); powerSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { //check if on or off Log.e(TAG, "The power value is " + (isChecked ? xltDevice.STATE_ON : xltDevice.STATE_OFF)); state = isChecked; int stateInt = mCurrentDevice.PowerSwitch(isChecked ? xltDevice.STATE_ON : xltDevice.STATE_OFF); Log.e(TAG, "stateInt value is= " + stateInt); deviceInfo.ison = isChecked ? xltDevice.STATE_ON : xltDevice.STATE_OFF; GlanceMainFragment.devicenodes.remove(mPositon); GlanceMainFragment.devicenodes.add(mPositon, deviceInfo); } }); /** * 亮度 */ brightnessSeekBar.setOnRangeChangedListener(new RangeSeekBar.OnRangeChangedListener(){ @Override public void onRangeChanged(RangeSeekBar view, float min, float max, boolean isFromUser) { // Log.e(TAG, "The brightness value is " + (int)min+"view.getCurrentRange()="+view.getCurrentRange()[0]); int brightnessInt = mCurrentDevice.ChangeBrightness((int)min); Log.e(TAG, "brightnessInt value is= " + brightnessInt); deviceInfo.brightness = (int)min; if (null != viewList && viewList.size() > 0) { viewList.get(0).callOnClick(); mHorizontalScrollView.smoothScrollTo(0, 0); } } }); // brightnessSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { // @Override // public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // } // // @Override // public void onStartTrackingTouch(SeekBar seekBar) { // } // // @Override // public void onStopTrackingTouch(SeekBar seekBar) { // Log.e(TAG, "The brightness value is " + seekBar.getProgress()); // int brightnessInt = mCurrentDevice.ChangeBrightness(seekBar.getProgress()); // Log.e(TAG, "brightnessInt value is= " + brightnessInt); // deviceInfo.brightness = seekBar.getProgress(); // // if (null != viewList && viewList.size() > 0) { // viewList.get(0).callOnClick(); // mHorizontalScrollView.smoothScrollTo(0, 0); // } // } // }); /** *色温 */ cctSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int seekBarProgress = seekBar.getProgress() + 2700; if (seekBarProgress > 2700 && seekBarProgress < 3500) { cctLabelColor.setText(com.umarbhutta.xlightcompanion.R.string.nuan_bai); } if (seekBarProgress > 3500 && seekBarProgress < 5500) { cctLabelColor.setText(com.umarbhutta.xlightcompanion.R.string.zhengbai); } if (seekBarProgress > 5500 && seekBarProgress < 6500) { cctLabelColor.setText(com.umarbhutta.xlightcompanion.R.string.lengbai); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { Log.d(TAG, "The CCT value is " + seekBar.getProgress() + 2700); int seekBarProgress = seekBar.getProgress() + 2700; int cctInt = mCurrentDevice.ChangeCCT(seekBarProgress); Log.e(TAG, "cctInt value is= " + cctInt); if (null != viewList && viewList.size() > 0) { viewList.get(0).callOnClick(); mHorizontalScrollView.smoothScrollTo(0, 0); } } }); scenarioSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (parent.getItemAtPosition(position).toString() == "None") { //scenarioNoneLL.animate().alpha(1).setDuration(600).start(); //enable all views below spinner disableEnableControls(true); } else { //if anything but "None" is selected, fade scenarioNoneLL out //scenarioNoneLL.animate().alpha(0).setDuration(500).start(); //disable all views below spinner disableEnableControls(false); //ParticleAdapter.JSONCommandScenario(ParticleAdapter.DEFAULT_DEVICE_ID, position); //position passed into above function corresponds to the scenarioId i.e. s1, s2, s3 to trigger mCurrentDevice.ChangeScenario(position); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ring1Button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ring1 = isChecked; updateDeviceRingLabel(); } }); ring2Button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ring2 = isChecked; updateDeviceRingLabel(); } }); ring3Button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ring3 = isChecked; updateDeviceRingLabel(); } }); initScenario();//初始化场景 } //获取监听 private void upUIDateAddHandler() { m_handlerControl = new Handler() { public void handleMessage(Message msg) { Logger.e(TAG, "handler_msg=" + msg.getData().toString()); int intValue = msg.getData().getInt("State", -255); if (intValue != -255) { powerSwitch.setChecked(intValue > 0); } intValue = msg.getData().getInt("BR", -255); if (intValue != -255) { // brightnessSeekBar.setProgress(intValue); brightnessSeekBar.setValue(intValue); } intValue = msg.getData().getInt("CCT", -255); if (intValue != -255) { cctSeekBar.setProgress(intValue - 2700); } //颜色 int R = 0; int G = 0; int B = 0; intValue = msg.getData().getInt("R", -255); if (intValue != -255) { R = intValue; } intValue = msg.getData().getInt("G", -255); if (intValue != -255) { G = intValue; } intValue = msg.getData().getInt("B", -255); if (intValue != -255) { B = intValue; } int color = Color.rgb(R, G, B); circleIcon.setColor(color); colorTextView.setText("RGB(" + R + "," + G + "," + B + ")"); } }; mCurrentDevice.addDeviceEventHandler(m_handlerControl); // updateDeviceRingLabel();//这个作用是 切换灯上部图片的 } private EditText et; @Override public void onClick(View view) { switch (view.getId()) { case R.id.scenarioName: String title = getString(R.string.edit_device_name); et = (EditText) mInflater.inflate(R.layout.layout_edittext, null); new DialogUtils().getEditTextDialog(EditDeviceActivity.this, title, mscenarioName.getText().toString(), new DialogUtils.OnClickOkBtnListener() { @Override public void onClickOk(String editTextStr) { if (TextUtils.isEmpty(editTextStr)) { ToastUtil.showToast(EditDeviceActivity.this, getString(R.string.content_is_null)); return; } editDeViceInfo(editTextStr); } }); break; } } @Override public void onDestroy() { mCurrentDevice.removeDeviceEventHandler(m_handlerControl); if (mCurrentDevice.getEnableEventBroadcast()) { unregisterReceiver(m_StatusReceiver); } mCurrentDevice.Disconnect(); super.onDestroy(); } private void disableEnableControls(boolean isEnabled) { powerSwitch.setEnabled(isEnabled); colorTextView.setEnabled(isEnabled); brightnessSeekBar.setEnabled(isEnabled); cctSeekBar.setEnabled(isEnabled); int selectColor = R.color.colorAccent, allLabels = R.color.textColorPrimary; if (isEnabled) { selectColor = R.color.colorAccent; allLabels = R.color.textColorPrimary; } else { selectColor = R.color.colorDisabled; allLabels = R.color.colorDisabled; } colorTextView.setTextColor(ContextCompat.getColor(this, selectColor)); powerLabel.setTextColor(ContextCompat.getColor(this, allLabels)); brightnessLabel.setTextColor(ContextCompat.getColor(this, allLabels)); cctLabel.setTextColor(ContextCompat.getColor(this, allLabels)); colorLabel.setTextColor(ContextCompat.getColor(this, allLabels)); } private void updateDeviceRingLabel() { String label = mCurrentDevice.getDeviceName(); if (ring1 && ring2 && ring3) { label += ": " + RINGALL_TEXT; lightImageView.setImageResource(R.drawable.aquabg_ring123); } else if (!ring1 && !ring2 && !ring3) { label += ": " + RINGALL_TEXT; lightImageView.setImageResource(R.drawable.aquabg_noring); } else if (ring1 && ring2) { label += ": " + RING1_TEXT + " & " + RING2_TEXT; lightImageView.setImageResource(R.drawable.aquabg_ring12); } else if (ring2 && ring3) { label += ": " + RING2_TEXT + " & " + RING3_TEXT; lightImageView.setImageResource(R.drawable.aquabg_ring23); } else if (ring1 && ring3) { label += ": " + RING1_TEXT + " & " + RING3_TEXT; lightImageView.setImageResource(R.drawable.aquabg_ring13); } else if (ring1) { label += ": " + RING1_TEXT; lightImageView.setImageResource(R.drawable.aquabg_ring1); } else if (ring2) { label += ": " + RING2_TEXT; lightImageView.setImageResource(R.drawable.aquabg_ring2); } else if (ring3) { label += ": " + RING3_TEXT; lightImageView.setImageResource(R.drawable.aquabg_ring3); } else { label += ""; lightImageView.setImageResource(R.drawable.aquabg_noring); } deviceRingLabel.setText(label); } private void onFabPressed() { Intent intent = new Intent(EditDeviceActivity.this, ColorSelectActivity.class); startActivityForResult(intent, 1); } private void initScenario() { RequestSceneListInfo.getInstance().getSceneListInfo(this, new RequestSceneListInfo.OnRequestFirstPageInfoCallback() { @Override public void onRequestFirstPageInfoSuccess(final SceneListResult mDeviceInfoResult) { runOnUiThread(new Runnable() { @Override public void run() { EditDeviceActivity.this.mDeviceInfoResult = mDeviceInfoResult; initSceneList(); } }); } @Override public void onRequestFirstPageInfoFail(int code, final String errMsg) { runOnUiThread(new Runnable() { @Override public void run() { ToastUtil.showToast(EditDeviceActivity.this, "" + errMsg); } }); } }); // 场景列表跳到对应的位置 RequestDeviceDetailInfo.getInstance().getDeviceInfo(this, deviceInfo.id, new RequestDeviceDetailInfo.OnRequestFirstPageInfoCallback() { @Override public void onRequestFirstPageInfoSuccess(DeviceInfoResult mDeviceInfoResult) { Logger.i("详细信息 = " + mDeviceInfoResult.toString()); } @Override public void onRequestFirstPageInfoFail(int code, String errMsg) { } }); } private List<View> viewList = new ArrayList<View>(); private List<TextView> textViews = new ArrayList<TextView>(); private void initSceneList() { for (int i = 0; i < mDeviceInfoResult.rows.size() + 1; i++) { View view; TextView textView; if (i == 0) { view = mInflater.inflate(R.layout.add_scenario_zdy_item, linear, false); textView = (TextView) view.findViewById(R.id.textView); view.setBackgroundResource(R.drawable.add_scenario_blue_bg); } else { Rows info = mDeviceInfoResult.rows.get(i - 1); view = mInflater.inflate(R.layout.add_scenario_item, linear, false); view.setBackgroundResource(R.drawable.add_scenario_bg); textView = (TextView) view.findViewById(R.id.sceneName); textView.setText(info.scenarioname); } viewList.add(view); textViews.add(textView); view.setTag(i); view.setOnClickListener(mSceneClick); linear.addView(view); } linear.invalidate(); if (deviceInfo.devicenodetype != 1 && !TextUtils.isEmpty(deviceInfo.scenarioId)) { // if (deviceInfo.devicenodetype != 1) {//测试专用 for (int i = 0; i < viewList.size(); i++) { if (i != 0 && deviceInfo.scenarioId.equals(String.valueOf(mDeviceInfoResult.rows.get(i - 1).id))) { // if (i != 0 && "53".equals(String.valueOf(mDeviceInfoResult.rows.get(i - 1).id))) { View cView = viewList.get(i); cView.callOnClick(); Message msg = Message.obtain(); msg.arg1 = i; handler.sendMessageDelayed(msg, 100); break; } } } } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); int index = msg.arg1; View cView = viewList.get(index); int[] location = new int[2]; cView.getLocationOnScreen(location); // Logger.i("left1 = " + location[0] + ", " + location[1]); mHorizontalScrollView.scrollTo(location[0] - 100, 0); } }; /** * 当前场景 */ private Rows curSene = null; View.OnClickListener mSceneClick = new View.OnClickListener() { @Override public void onClick(View v) { int index = (int) v.getTag(); if (0 == index) { curSene = null; } else { Rows sceneInfo = mDeviceInfoResult.rows.get(index - 1); curSene = sceneInfo; updateSceneInfo(sceneInfo); } for (int i = 0; i < viewList.size(); i++) { View view = viewList.get(i); TextView textView = textViews.get(i); view.setBackgroundResource(R.drawable.add_scenario_bg); textView.setTextColor(getResources().getColor(R.color.black)); } View mView = viewList.get(index); mView.setBackgroundResource(R.drawable.add_scenario_blue_bg); TextView mText = textViews.get(index); mText.setTextColor(getResources().getColor(R.color.white)); editDeViceInfo(null); } }; /** * 选择了某一个场景 * * @param sceneInfo */ private void updateSceneInfo(Rows sceneInfo) { if (null == sceneInfo) { return; } // powerSwitch.setChecked((1 == sceneInfo.ison) ? true : false); if (mCurrentDevice.isSunny()) { // brightnessSeekBar.setProgress(sceneInfo.brightness); brightnessSeekBar.setValue(sceneInfo.brightness); mCurrentDevice.ChangeBrightness(sceneInfo.brightness); cctSeekBar.setProgress(sceneInfo.cct - 2700); mCurrentDevice.ChangeCCT(sceneInfo.cct - 2700); mCurrentDevice.ChangeScenario(sceneInfo.scenarionodes.get(0).scenarioId); } else { cctSeekBar.setProgress(sceneInfo.cct - 2700); mCurrentDevice.ChangeCCT(sceneInfo.cct - 2700); Scenarionodes currentNode = sceneInfo.scenarionodes.get(0);//当前灯 int R = 0; int G = 0; int B = 0; R = currentNode.R; G = currentNode.G; B = currentNode.B; int color = Color.rgb(R, G, B); circleIcon.setColor(color); colorTextView.setText("RGB(" + R + "," + G + "," + B + ")"); mCurrentDevice.ChangeColor(xltDevice.RING_ID_ALL, true, sceneInfo.brightness, 26, currentNode.R, currentNode.G, currentNode.B); } // brightnessSeekBar.setProgress(sceneInfo.brightness); // cctSeekBar.setProgress(sceneInfo.cct - 2700); //颜色 // int R = 0; // int G = 0; // int B = 0; // Scenarionodes currentNode= sceneInfo.scenarionodes.get(0);//当前灯 // R = currentNode.R; // G = currentNode.G; // B = currentNode.B; // int color = Color.rgb(R, G, B); // circleIcon.setColor(color); // colorTextView.setText("RGB(" + R + "," + G + "," + B + ")"); } /** * 提交编辑设备 */ private void editDeViceInfo(String newDeviceName) { if (!NetworkUtils.isNetworkAvaliable(this)) { ToastUtil.showToast(this, R.string.net_error); return; } final String deviceName = TextUtils.isEmpty(newDeviceName) ? mscenarioName.getText().toString() : newDeviceName; if (TextUtils.isEmpty(deviceName)) { ToastUtil.showToast(this, getString(R.string.please_set_lamp_name)); return; } JSONObject jsonObject = new JSONObject(); try { jsonObject.put("ison", powerSwitch.isChecked() ? 1 : 0); jsonObject.put("userId", UserUtils.getUserInfo(this).getId()); // jsonObject.put("devicename", deviceName);。。。。。。。。。 JSONArray devicenodes = new JSONArray(); jsonObject.put("devicenodes", devicenodes); JSONObject devicenodesJSONObject = new JSONObject(); devicenodes.put(devicenodesJSONObject); devicenodesJSONObject.put("devicenodeId", deviceInfo.id); devicenodesJSONObject.put("devicenodename", deviceName); devicenodesJSONObject.put("ison", powerSwitch.isChecked() ? 1 : 0); if (null == curSene) { devicenodesJSONObject.put("scenarioId", 0); // 场景id,自定义场景 } else { devicenodesJSONObject.put("scenarioId", curSene.id); // 场景id } JSONArray deviceringsArr = new JSONArray(); devicenodesJSONObject.put("devicerings", deviceringsArr); for (int i = 0; i < 3; i++) { JSONObject deviceringsObj = new JSONObject(); deviceringsArr.put(deviceringsObj); deviceringsObj.put("ison", powerSwitch.isChecked() ? 1 : 0); deviceringsObj.put("R", red); deviceringsObj.put("G", green); deviceringsObj.put("B", blue); deviceringsObj.put("color", "rgb(" + red + "," + green + "," + blue + ")"); deviceringsObj.put("cct", cctSeekBar.getProgress() + 2700); deviceringsObj.put("brightness", brightnessSeekBar.getCurrentRange()[0]); } } catch (JSONException e) { e.printStackTrace(); } HttpUtils.getInstance().putRequestInfo(NetConfig.URL_EDIT_DEVICE_INFO + deviceInfo.deviceId + "?access_token=" + UserUtils.getUserInfo(this).getAccess_token(), jsonObject.toString(), null, new HttpUtils.OnHttpRequestCallBack() { @Override public void onHttpRequestSuccess(Object result) { Logger.i("编辑成功 = " + result.toString()); runOnUiThread(new Runnable() { @Override public void run() { // ToastUtil.showToast(EditDeviceActivity.this, getString(R.string.modify_success)); // setResult(0); // EditDeviceActivity.this.finish(); if (!TextUtils.isEmpty(deviceName)) { deviceInfo.devicenodename = deviceName; mscenarioName.setText(deviceName); } } }); } @Override public void onHttpRequestFail(int code, final String errMsg) { Logger.i("编辑失败 = " + errMsg); runOnUiThread(new Runnable() { @Override public void run() { ToastUtil.showToast(EditDeviceActivity.this, getString(R.string.modify_fail) + errMsg); } }); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == -1) { int color = data.getIntExtra("color", -1); if (-1 != color) { red = (color & 0xff0000) >> 16; green = (color & 0x00ff00) >> 8; blue = (color & 0x0000ff); } circleIcon.setColor(color); colorTextView.setText("RGB(" + red + "," + green + "," + blue + ")"); int br = (int)brightnessSeekBar.getCurrentRange()[0]; int ww = 0; mCurrentDevice.ChangeColor(xltDevice.RING_ID_ALL, state, br, ww, red, green, blue); mCurrentDevice.setRed(xltDevice.RING_ID_ALL, red); mCurrentDevice.setGreen(xltDevice.RING_ID_ALL, green); mCurrentDevice.setBlue(xltDevice.RING_ID_ALL, blue); } } }
优化亮度控件
app/src/main/java/com/umarbhutta/xlightcompanion/main/EditDeviceActivity.java
优化亮度控件
<ide><path>pp/src/main/java/com/umarbhutta/xlightcompanion/main/EditDeviceActivity.java <ide> private static final String RING3_TEXT = "RING 3"; <ide> <ide> private CheckBox powerSwitch; <del>// private SeekBar brightnessSeekBar; <add> // private SeekBar brightnessSeekBar; <ide> private RangeSeekBar brightnessSeekBar; <ide> <ide> private SeekBar cctSeekBar; <ide> /** <ide> * 亮度 <ide> */ <del> brightnessSeekBar.setOnRangeChangedListener(new RangeSeekBar.OnRangeChangedListener(){ <add> brightnessSeekBar.setOnRangeChangedListener(new RangeSeekBar.OnRangeChangedListener() { <ide> <ide> @Override <ide> public void onRangeChanged(RangeSeekBar view, float min, float max, boolean isFromUser) { <del> // <del> Log.e(TAG, "The brightness value is " + (int)min+"view.getCurrentRange()="+view.getCurrentRange()[0]); <del> int brightnessInt = mCurrentDevice.ChangeBrightness((int)min); <del> Log.e(TAG, "brightnessInt value is= " + brightnessInt); <del> deviceInfo.brightness = (int)min; <del> <del> if (null != viewList && viewList.size() > 0) { <del> viewList.get(0).callOnClick(); <del> mHorizontalScrollView.smoothScrollTo(0, 0); <add> if (!isFromUser) { <add> // <add> Log.e(TAG, "The brightness value is " + (int) min + "view.getCurrentRange()=" + view.getCurrentRange()[0]); <add> int brightnessInt = mCurrentDevice.ChangeBrightness((int) min); <add> Log.e(TAG, "brightnessInt value is= " + brightnessInt); <add> deviceInfo.brightness = (int) min; <add> <add> if (null != viewList && viewList.size() > 0) { <add> viewList.get(0).callOnClick(); <add> mHorizontalScrollView.smoothScrollTo(0, 0); <add> } <ide> } <ide> } <ide> }); <ide> circleIcon.setColor(color); <ide> colorTextView.setText("RGB(" + red + "," + green + "," + blue + ")"); <ide> <del> int br = (int)brightnessSeekBar.getCurrentRange()[0]; <add> int br = (int) brightnessSeekBar.getCurrentRange()[0]; <ide> int ww = 0; <ide> mCurrentDevice.ChangeColor(xltDevice.RING_ID_ALL, state, br, ww, red, green, blue); <ide> mCurrentDevice.setRed(xltDevice.RING_ID_ALL, red);
Java
mit
error: pathspec 'src/PathSumTwo.java' did not match any file(s) known to git
860d3962d7ab197a31c48baae41493c3f67eafb5
1
fredplusplus/staysharp
import java.util.ArrayList; /** * http://leetcode.com/onlinejudge#question_113 */ public class PathSumTwo { public static void main(String[] args) { } public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>(); if (root == null) { return results; } else if (root.val == sum && root.left == null && root.right == null) { ArrayList<Integer> result = new ArrayList<Integer>(); result.add(root.val); results.add(result); return results; } else { int partialSum = sum - root.val; ArrayList<ArrayList<Integer>> leftResult = pathSum(root.left, partialSum); if (!leftResult.isEmpty()) { for (ArrayList<Integer> result : leftResult) { result.add(0, root.val); } results.addAll(leftResult); } ArrayList<ArrayList<Integer>> rightResult = pathSum(root.right, partialSum); if (!rightResult.isEmpty()) { for (ArrayList<Integer> result : rightResult) { result.add(0, root.val); } results.addAll(rightResult); } return results; } } }
src/PathSumTwo.java
path sum 2
src/PathSumTwo.java
path sum 2
<ide><path>rc/PathSumTwo.java <add>import java.util.ArrayList; <add> <add>/** <add> * http://leetcode.com/onlinejudge#question_113 <add> */ <add>public class PathSumTwo { <add> <add> public static void main(String[] args) { <add> <add> } <add> <add> public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { <add> ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>(); <add> if (root == null) { <add> return results; <add> } else if (root.val == sum && root.left == null && root.right == null) { <add> ArrayList<Integer> result = new ArrayList<Integer>(); <add> result.add(root.val); <add> results.add(result); <add> return results; <add> } else { <add> int partialSum = sum - root.val; <add> ArrayList<ArrayList<Integer>> leftResult = pathSum(root.left, partialSum); <add> if (!leftResult.isEmpty()) { <add> for (ArrayList<Integer> result : leftResult) { <add> result.add(0, root.val); <add> } <add> results.addAll(leftResult); <add> } <add> ArrayList<ArrayList<Integer>> rightResult = pathSum(root.right, partialSum); <add> if (!rightResult.isEmpty()) { <add> for (ArrayList<Integer> result : rightResult) { <add> result.add(0, root.val); <add> } <add> results.addAll(rightResult); <add> } <add> return results; <add> } <add> } <add>}
Java
mit
addd4ddfcfb4d289e34f10499eabaa79f4d2f80c
0
MrBlobman/NBTProxy
/** * The MIT License (MIT) * * Copyright (c) 2016 MrBlobman * * 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 io.github.mrblobman.nbt.v1_9_R1; import io.github.mrblobman.nbt.NBTBaseTag; import io.github.mrblobman.nbt.NBTCompoundTag; import io.github.mrblobman.nbt.NBTException; import io.github.mrblobman.nbt.NBTIODelegate; import net.minecraft.server.v1_9_R1.*; import org.bukkit.block.BlockState; import org.bukkit.craftbukkit.v1_9_R1.block.CraftBlockState; import org.bukkit.craftbukkit.v1_9_R1.entity.CraftEntity; import org.bukkit.craftbukkit.v1_9_R1.inventory.CraftItemStack; import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; public class TagFactory extends io.github.mrblobman.nbt.TagFactory { private final NBTIODelegate<ItemStack> itemStackNBTIODelegate = new NBTIODelegate<ItemStack>() { @Override public NBTCompoundTag read(ItemStack item) { net.minecraft.server.v1_9_R1.ItemStack nmsItem = CraftItemStack.asNMSCopy(item); if (nmsItem.hasTag()) return new io.github.mrblobman.nbt.v1_9_R1.NBTCompoundTag(nmsItem.getTag()); else return new io.github.mrblobman.nbt.v1_9_R1.NBTCompoundTag(); } @Override public void write(ItemStack item, NBTCompoundTag tag) { //Grab the nms item net.minecraft.server.v1_9_R1.ItemStack nmsItem = CraftItemStack.asNMSCopy(item); nmsItem.setTag((NBTTagCompound) tag.getHandle()); //By setting the item meta we can modify the item directly without copying it //and requiring a new reference returned ItemMeta meta = CraftItemStack.getItemMeta(nmsItem); item.setItemMeta(meta); } @Override public void append(ItemStack item, NBTCompoundTag tag) { //Grab the nms item net.minecraft.server.v1_9_R1.ItemStack nmsItem = CraftItemStack.asNMSCopy(item); if (nmsItem.hasTag()) { NBTTagCompound nmsTag = nmsItem.getTag(); nmsTag.a((NBTTagCompound) tag.getHandle()); } else { nmsItem.setTag((NBTTagCompound) tag.getHandle()); } //By setting the item meta we can modify the item directly without copying it //and requiring a new reference returned ItemMeta meta = CraftItemStack.getItemMeta(nmsItem); item.setItemMeta(meta); } }; private final NBTIODelegate<Entity> entityNBTIODelegate = new NBTIODelegate<Entity>() { @Override public NBTCompoundTag read(Entity entity) { net.minecraft.server.v1_9_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTCompoundTag tag = new io.github.mrblobman.nbt.v1_9_R1.NBTCompoundTag(new NBTTagCompound()); if (!nmsEntity.c((NBTTagCompound) tag.getHandle())) { //Skip the id tag and try to read the data anyways nmsEntity.e((NBTTagCompound) tag.getHandle()); } return tag; } @Override public void write(Entity entity, NBTCompoundTag tag) { net.minecraft.server.v1_9_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); //Also set each of the default values for a standard entity nmsEntity.f((NBTTagCompound) tag.getHandle()); } @Override public void append(Entity entity, NBTCompoundTag tag) { net.minecraft.server.v1_9_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound oldTag = new NBTTagCompound(); if (!nmsEntity.c(oldTag)) { //Skip the id tag and try to read the data anyways nmsEntity.e(oldTag); } oldTag.a((NBTTagCompound) tag.getHandle()); //Also set each of the default values for a standard entity nmsEntity.f((NBTTagCompound) tag.getHandle()); } }; private final NBTIODelegate<BlockState> blockNBTIODelegate = new NBTIODelegate<BlockState>() { @Override public NBTCompoundTag read(BlockState blockState) { CraftBlockState craftState = (CraftBlockState) blockState; TileEntity nmsBlock = craftState.getTileEntity(); if (nmsBlock == null) throw new NBTException("Given block (" + blockState + ") is not a tile entity and does not have an NBT tag."); NBTCompoundTag tag = new io.github.mrblobman.nbt.v1_9_R1.NBTCompoundTag(); nmsBlock.save((NBTTagCompound) tag.getHandle()); return tag; } @Override public void write(BlockState blockState, NBTCompoundTag tag) { CraftBlockState craftState = (CraftBlockState) blockState; TileEntity nmsBlock = craftState.getTileEntity(); if (nmsBlock == null) throw new NBTException("Given block (" + blockState + ") is not a tile entity and does not have an NBT tag."); nmsBlock.a((NBTTagCompound) tag.getHandle()); } @Override public void append(BlockState blockState, NBTCompoundTag tag) { CraftBlockState craftState = (CraftBlockState) blockState; TileEntity nmsBlock = craftState.getTileEntity(); if (nmsBlock == null) throw new NBTException("Given block (" + blockState + ") is not a tile entity and does not have an NBT tag."); NBTCompoundTag oldTag = new io.github.mrblobman.nbt.v1_9_R1.NBTCompoundTag(); nmsBlock.save((NBTTagCompound) tag.getHandle()); oldTag.putAll(tag); nmsBlock.a((NBTTagCompound) oldTag.getHandle()); } }; @Override public NBTIODelegate<ItemStack> getItemIODelegate() { return itemStackNBTIODelegate; } @Override public NBTIODelegate<Entity> getEntityIODelegate() { return entityNBTIODelegate; } @Override public NBTIODelegate<BlockState> getBlockIODelegate() { return blockNBTIODelegate; } @Override public NBTBaseTag<Byte> newByteTag(byte value) { return new NBTByteTag(value); } @Override protected NBTBaseTag<Byte> wrapByteTag(Object handle) { return new NBTByteTag((NBTTagByte) handle); } @Override public NBTBaseTag<Short> newShortTag(short value) { return new NBTShortTag(value); } @Override protected NBTBaseTag<Short> wrapShortTag(Object handle) { return new NBTShortTag((NBTTagShort) handle); } @Override public NBTBaseTag<Integer> newIntTag(int value) { return new NBTIntTag(value); } @Override protected NBTBaseTag<Integer> wrapIntTag(Object handle) { return new NBTIntTag((NBTTagInt) handle); } @Override public NBTBaseTag<Long> newLongTag(long value) { return new NBTLongTag(value); } @Override protected NBTBaseTag<Long> wrapLongTag(Object handle) { return new NBTLongTag((NBTTagLong) handle); } @Override public NBTBaseTag<Float> newFloatTag(float value) { return new NBTFloatTag(value); } @Override protected NBTBaseTag<Float> wrapFloatTag(Object handle) { return new NBTFloatTag((NBTTagFloat) handle); } @Override public NBTBaseTag<Double> newDoubleTag(double value) { return new NBTDoubleTag(value); } @Override protected NBTBaseTag<Double> wrapDoubleTag(Object handle) { return new NBTDoubleTag((NBTTagDouble) handle); } @Override public NBTBaseTag<byte[]> newByteArrayTag(byte[] value) { return new NBTByteArrayTag(value); } @Override protected NBTBaseTag<byte[]> wrapByteArrayTag(Object handle) { return new NBTByteArrayTag((NBTTagByteArray) handle); } @Override public NBTBaseTag<String> newStringTag(String value) { return new NBTStringTag(value); } @Override protected NBTBaseTag<String> wrapStringTag(Object handle) { return new NBTStringTag((NBTTagString) handle); } @Override public NBTListTag newListTag() { return new NBTListTag(); } @Override protected NBTListTag wrapListTag(Object handle) { return new NBTListTag((NBTTagList) handle); } @Override public NBTCompoundTag newCompoundTag() { return new io.github.mrblobman.nbt.v1_9_R1.NBTCompoundTag(); } @Override protected NBTCompoundTag wrapCompoundTag(Object handle) { return new io.github.mrblobman.nbt.v1_9_R1.NBTCompoundTag((NBTTagCompound) handle); } @Override public NBTBaseTag<int[]> newIntArrayTag(int[] value) { return new NBTIntArrayTag(value); } @Override public NBTBaseTag<int[]> wrapIntArrayTag(Object handle) { return new NBTIntArrayTag((NBTTagIntArray) handle); } }
v1_9_R1/src/main/java/io/github/mrblobman/nbt/v1_9_R1/TagFactory.java
/** * The MIT License (MIT) * * Copyright (c) 2016 MrBlobman * * 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 io.github.mrblobman.nbt.v1_9_R1; import io.github.mrblobman.nbt.NBTBaseTag; import io.github.mrblobman.nbt.NBTCompoundTag; import io.github.mrblobman.nbt.NBTException; import io.github.mrblobman.nbt.NBTIODelegate; import net.minecraft.server.v1_9_R1.*; import org.bukkit.block.BlockState; import org.bukkit.craftbukkit.v1_9_R1.block.CraftBlockState; import org.bukkit.craftbukkit.v1_9_R1.entity.CraftEntity; import org.bukkit.craftbukkit.v1_9_R1.inventory.CraftItemStack; import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; public class TagFactory extends io.github.mrblobman.nbt.TagFactory { private final NBTIODelegate<ItemStack> itemStackNBTIODelegate = new NBTIODelegate<ItemStack>() { @Override public NBTCompoundTag read(ItemStack item) { net.minecraft.server.v1_9_R1.ItemStack nmsItem = CraftItemStack.asNMSCopy(item); if (nmsItem.hasTag()) return new io.github.mrblobman.nbt.v1_9_R1.NBTCompoundTag(nmsItem.getTag()); else return new io.github.mrblobman.nbt.v1_9_R1.NBTCompoundTag(); } @Override public void write(ItemStack item, NBTCompoundTag tag) { //Grab the nms item net.minecraft.server.v1_9_R1.ItemStack nmsItem = CraftItemStack.asNMSCopy(item); nmsItem.setTag((NBTTagCompound) tag.getHandle()); //By setting the item meta we can modify the item directly without copying it //and requiring a new reference returned ItemMeta meta = CraftItemStack.getItemMeta(nmsItem); item.setItemMeta(meta); } @Override public void append(ItemStack item, NBTCompoundTag tag) { //Grab the nms item net.minecraft.server.v1_9_R1.ItemStack nmsItem = CraftItemStack.asNMSCopy(item); if (nmsItem.hasTag()) { NBTTagCompound nmsTag = nmsItem.getTag(); nmsTag.a((NBTTagCompound) tag.getHandle()); } else { nmsItem.setTag((NBTTagCompound) tag.getHandle()); } //By setting the item meta we can modify the item directly without copying it //and requiring a new reference returned ItemMeta meta = CraftItemStack.getItemMeta(nmsItem); item.setItemMeta(meta); } }; private final NBTIODelegate<Entity> entityNBTIODelegate = new NBTIODelegate<Entity>() { @Override public NBTCompoundTag read(Entity entity) { net.minecraft.server.v1_9_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTCompoundTag tag = new io.github.mrblobman.nbt.v1_9_R1.NBTCompoundTag(new NBTTagCompound()); if (!nmsEntity.c((NBTTagCompound) tag.getHandle())) { //Skip the id tag and try to read the data anyways nmsEntity.e((NBTTagCompound) tag.getHandle()); } return tag; } @Override public void write(Entity entity, NBTCompoundTag tag) { net.minecraft.server.v1_9_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); //If the entity is a living entity we want to set the attribute values in the compound if (nmsEntity instanceof EntityLiving) { EntityLiving nmsEntityLiving = (EntityLiving) nmsEntity; nmsEntityLiving.a((NBTTagCompound) tag.getHandle()); } //Also set each of the default values for a standard entity nmsEntity.f((NBTTagCompound) tag.getHandle()); } @Override public void append(Entity entity, NBTCompoundTag tag) { net.minecraft.server.v1_9_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound oldTag = new NBTTagCompound(); if (!nmsEntity.c(oldTag)) { //Skip the id tag and try to read the data anyways nmsEntity.e(oldTag); } oldTag.a((NBTTagCompound) tag.getHandle()); //If the entity is a living entity we want to set the attribute values in the compound if (nmsEntity instanceof EntityLiving) { EntityLiving nmsEntityLiving = (EntityLiving) nmsEntity; nmsEntityLiving.a((NBTTagCompound) tag.getHandle()); } //Also set each of the default values for a standard entity nmsEntity.f((NBTTagCompound) tag.getHandle()); } }; private final NBTIODelegate<BlockState> blockNBTIODelegate = new NBTIODelegate<BlockState>() { @Override public NBTCompoundTag read(BlockState blockState) { CraftBlockState craftState = (CraftBlockState) blockState; TileEntity nmsBlock = craftState.getTileEntity(); if (nmsBlock == null) throw new NBTException("Given block (" + blockState + ") is not a tile entity and does not have an NBT tag."); NBTCompoundTag tag = new io.github.mrblobman.nbt.v1_9_R1.NBTCompoundTag(); nmsBlock.save((NBTTagCompound) tag.getHandle()); return tag; } @Override public void write(BlockState blockState, NBTCompoundTag tag) { CraftBlockState craftState = (CraftBlockState) blockState; TileEntity nmsBlock = craftState.getTileEntity(); if (nmsBlock == null) throw new NBTException("Given block (" + blockState + ") is not a tile entity and does not have an NBT tag."); nmsBlock.a((NBTTagCompound) tag.getHandle()); } @Override public void append(BlockState blockState, NBTCompoundTag tag) { CraftBlockState craftState = (CraftBlockState) blockState; TileEntity nmsBlock = craftState.getTileEntity(); if (nmsBlock == null) throw new NBTException("Given block (" + blockState + ") is not a tile entity and does not have an NBT tag."); NBTCompoundTag oldTag = new io.github.mrblobman.nbt.v1_9_R1.NBTCompoundTag(); nmsBlock.save((NBTTagCompound) tag.getHandle()); oldTag.putAll(tag); nmsBlock.a((NBTTagCompound) oldTag.getHandle()); } }; @Override public NBTIODelegate<ItemStack> getItemIODelegate() { return itemStackNBTIODelegate; } @Override public NBTIODelegate<Entity> getEntityIODelegate() { return entityNBTIODelegate; } @Override public NBTIODelegate<BlockState> getBlockIODelegate() { return blockNBTIODelegate; } @Override public NBTBaseTag<Byte> newByteTag(byte value) { return new NBTByteTag(value); } @Override protected NBTBaseTag<Byte> wrapByteTag(Object handle) { return new NBTByteTag((NBTTagByte) handle); } @Override public NBTBaseTag<Short> newShortTag(short value) { return new NBTShortTag(value); } @Override protected NBTBaseTag<Short> wrapShortTag(Object handle) { return new NBTShortTag((NBTTagShort) handle); } @Override public NBTBaseTag<Integer> newIntTag(int value) { return new NBTIntTag(value); } @Override protected NBTBaseTag<Integer> wrapIntTag(Object handle) { return new NBTIntTag((NBTTagInt) handle); } @Override public NBTBaseTag<Long> newLongTag(long value) { return new NBTLongTag(value); } @Override protected NBTBaseTag<Long> wrapLongTag(Object handle) { return new NBTLongTag((NBTTagLong) handle); } @Override public NBTBaseTag<Float> newFloatTag(float value) { return new NBTFloatTag(value); } @Override protected NBTBaseTag<Float> wrapFloatTag(Object handle) { return new NBTFloatTag((NBTTagFloat) handle); } @Override public NBTBaseTag<Double> newDoubleTag(double value) { return new NBTDoubleTag(value); } @Override protected NBTBaseTag<Double> wrapDoubleTag(Object handle) { return new NBTDoubleTag((NBTTagDouble) handle); } @Override public NBTBaseTag<byte[]> newByteArrayTag(byte[] value) { return new NBTByteArrayTag(value); } @Override protected NBTBaseTag<byte[]> wrapByteArrayTag(Object handle) { return new NBTByteArrayTag((NBTTagByteArray) handle); } @Override public NBTBaseTag<String> newStringTag(String value) { return new NBTStringTag(value); } @Override protected NBTBaseTag<String> wrapStringTag(Object handle) { return new NBTStringTag((NBTTagString) handle); } @Override public NBTListTag newListTag() { return new NBTListTag(); } @Override protected NBTListTag wrapListTag(Object handle) { return new NBTListTag((NBTTagList) handle); } @Override public NBTCompoundTag newCompoundTag() { return new io.github.mrblobman.nbt.v1_9_R1.NBTCompoundTag(); } @Override protected NBTCompoundTag wrapCompoundTag(Object handle) { return new io.github.mrblobman.nbt.v1_9_R1.NBTCompoundTag((NBTTagCompound) handle); } @Override public NBTBaseTag<int[]> newIntArrayTag(int[] value) { return new NBTIntArrayTag(value); } @Override public NBTBaseTag<int[]> wrapIntArrayTag(Object handle) { return new NBTIntArrayTag((NBTTagIntArray) handle); } }
Removed call to living entity methods as the entity methods call them if necessary
v1_9_R1/src/main/java/io/github/mrblobman/nbt/v1_9_R1/TagFactory.java
Removed call to living entity methods as the entity methods call them if necessary
<ide><path>1_9_R1/src/main/java/io/github/mrblobman/nbt/v1_9_R1/TagFactory.java <ide> public void write(Entity entity, NBTCompoundTag tag) { <ide> net.minecraft.server.v1_9_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); <ide> <del> //If the entity is a living entity we want to set the attribute values in the compound <del> if (nmsEntity instanceof EntityLiving) { <del> EntityLiving nmsEntityLiving = (EntityLiving) nmsEntity; <del> nmsEntityLiving.a((NBTTagCompound) tag.getHandle()); <del> } <del> <ide> //Also set each of the default values for a standard entity <ide> nmsEntity.f((NBTTagCompound) tag.getHandle()); <ide> } <ide> } <ide> oldTag.a((NBTTagCompound) tag.getHandle()); <ide> <del> //If the entity is a living entity we want to set the attribute values in the compound <del> if (nmsEntity instanceof EntityLiving) { <del> EntityLiving nmsEntityLiving = (EntityLiving) nmsEntity; <del> nmsEntityLiving.a((NBTTagCompound) tag.getHandle()); <del> } <del> <ide> //Also set each of the default values for a standard entity <ide> nmsEntity.f((NBTTagCompound) tag.getHandle()); <ide> }
Java
apache-2.0
f7fb7e3c659f90af7ee809cbe6e426491691cd76
0
masaki-yamakawa/geode,davebarnes97/geode,jdeppe-pivotal/geode,deepakddixit/incubator-geode,masaki-yamakawa/geode,smgoller/geode,PurelyApplied/geode,davebarnes97/geode,masaki-yamakawa/geode,deepakddixit/incubator-geode,masaki-yamakawa/geode,deepakddixit/incubator-geode,PurelyApplied/geode,davebarnes97/geode,pdxrunner/geode,davinash/geode,davinash/geode,smgoller/geode,PurelyApplied/geode,deepakddixit/incubator-geode,deepakddixit/incubator-geode,pdxrunner/geode,davinash/geode,pdxrunner/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,PurelyApplied/geode,pdxrunner/geode,davinash/geode,deepakddixit/incubator-geode,davebarnes97/geode,masaki-yamakawa/geode,smgoller/geode,pdxrunner/geode,PurelyApplied/geode,davinash/geode,smgoller/geode,jdeppe-pivotal/geode,deepakddixit/incubator-geode,smgoller/geode,davebarnes97/geode,PurelyApplied/geode,davinash/geode,jdeppe-pivotal/geode,smgoller/geode,davinash/geode,masaki-yamakawa/geode,pdxrunner/geode,smgoller/geode,PurelyApplied/geode,davebarnes97/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,jdeppe-pivotal/geode,pdxrunner/geode,davebarnes97/geode
/* * 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.geode.internal.cache.tier.sockets.command; import java.io.IOException; import java.util.HashSet; import java.util.NoSuchElementException; import java.util.Set; import org.apache.geode.cache.Region; import org.apache.geode.cache.client.internal.ConnectionImpl; import org.apache.geode.cache.execute.Function; import org.apache.geode.cache.execute.FunctionException; import org.apache.geode.cache.execute.FunctionInvocationTargetException; import org.apache.geode.cache.execute.FunctionService; import org.apache.geode.cache.operations.ExecuteFunctionOperationContext; import org.apache.geode.internal.Version; import org.apache.geode.internal.cache.PartitionedRegion; import org.apache.geode.internal.cache.execute.AbstractExecution; import org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException; import org.apache.geode.internal.cache.execute.MemberMappedArgument; import org.apache.geode.internal.cache.execute.PartitionedRegionFunctionExecutor; import org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender; import org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender65; import org.apache.geode.internal.cache.tier.CachedRegionHelper; import org.apache.geode.internal.cache.tier.Command; import org.apache.geode.internal.cache.tier.MessageType; import org.apache.geode.internal.cache.tier.ServerSideHandshake; import org.apache.geode.internal.cache.tier.sockets.BaseCommand; import org.apache.geode.internal.cache.tier.sockets.ChunkedMessage; import org.apache.geode.internal.cache.tier.sockets.Message; import org.apache.geode.internal.cache.tier.sockets.Part; import org.apache.geode.internal.cache.tier.sockets.ServerConnection; import org.apache.geode.internal.i18n.LocalizedStrings; import org.apache.geode.internal.logging.log4j.LocalizedMessage; import org.apache.geode.internal.security.AuthorizeRequest; import org.apache.geode.internal.security.SecurityService; /** * @since GemFire 6.5 */ public class ExecuteRegionFunctionSingleHop extends BaseCommand { private static final ExecuteRegionFunctionSingleHop singleton = new ExecuteRegionFunctionSingleHop(); public static Command getCommand() { return singleton; } private ExecuteRegionFunctionSingleHop() {} @Override public void cmdExecute(final Message clientMessage, final ServerConnection serverConnection, final SecurityService securityService, long start) throws IOException { String regionName = null; Object function = null; Object args = null; MemberMappedArgument memberMappedArg = null; byte isExecuteOnAllBuckets = 0; Set<Object> filter = null; Set<Integer> buckets = null; byte hasResult = 0; byte functionState = 0; int removedNodesSize = 0; Set<Object> removedNodesSet = null; int filterSize = 0, bucketIdsSize = 0, partNumber = 0; CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper(); int functionTimeout = ConnectionImpl.DEFAULT_CLIENT_FUNCTION_TIMEOUT; try { byte[] bytes = clientMessage.getPart(0).getSerializedForm(); functionState = bytes[0]; if (bytes.length >= 5 && serverConnection.getClientVersion().ordinal() >= Version.GFE_8009.ordinal()) { functionTimeout = Part.decodeInt(bytes, 1); } if (functionState != 1) { hasResult = (byte) ((functionState & 2) - 1); } else { hasResult = functionState; } if (hasResult == 1) { serverConnection.setAsTrue(REQUIRES_RESPONSE); serverConnection.setAsTrue(REQUIRES_CHUNKED_RESPONSE); } regionName = clientMessage.getPart(1).getString(); function = clientMessage.getPart(2).getStringOrObject(); args = clientMessage.getPart(3).getObject(); Part part = clientMessage.getPart(4); if (part != null) { Object obj = part.getObject(); if (obj instanceof MemberMappedArgument) { memberMappedArg = (MemberMappedArgument) obj; } } isExecuteOnAllBuckets = clientMessage.getPart(5).getSerializedForm()[0]; if (isExecuteOnAllBuckets == 1) { filter = new HashSet(); bucketIdsSize = clientMessage.getPart(6).getInt(); if (bucketIdsSize != 0) { buckets = new HashSet<Integer>(); partNumber = 7; for (int i = 0; i < bucketIdsSize; i++) { buckets.add(clientMessage.getPart(partNumber + i).getInt()); } } partNumber = 7 + bucketIdsSize; } else { filterSize = clientMessage.getPart(6).getInt(); if (filterSize != 0) { filter = new HashSet<Object>(); partNumber = 7; for (int i = 0; i < filterSize; i++) { filter.add(clientMessage.getPart(partNumber + i).getStringOrObject()); } } partNumber = 7 + filterSize; } removedNodesSize = clientMessage.getPart(partNumber).getInt(); if (removedNodesSize != 0) { removedNodesSet = new HashSet<Object>(); partNumber = partNumber + 1; for (int i = 0; i < removedNodesSize; i++) { removedNodesSet.add(clientMessage.getPart(partNumber + i).getStringOrObject()); } } } catch (ClassNotFoundException exception) { logger.warn(LocalizedMessage.create( LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), exception); if (hasResult == 1) { writeChunkedException(clientMessage, exception, serverConnection); serverConnection.setAsTrue(RESPONDED); return; } } if (function == null || regionName == null) { String message = null; if (function == null) { message = LocalizedStrings.ExecuteRegionFunction_THE_INPUT_0_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL .toLocalizedString("function"); } if (regionName == null) { message = LocalizedStrings.ExecuteRegionFunction_THE_INPUT_0_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL .toLocalizedString("region"); } logger.warn("{}: {}", serverConnection.getName(), message); sendError(hasResult, clientMessage, message, serverConnection); return; } Region region = crHelper.getRegion(regionName); if (region == null) { String message = LocalizedStrings.ExecuteRegionFunction_THE_REGION_NAMED_0_WAS_NOT_FOUND_DURING_EXECUTE_FUNCTION_REQUEST .toLocalizedString(regionName); logger.warn("{}: {}", serverConnection.getName(), message); sendError(hasResult, clientMessage, message, serverConnection); return; } ServerSideHandshake handshake = serverConnection.getHandshake(); int earlierClientReadTimeout = handshake.getClientReadTimeout(); handshake.setClientReadTimeout(functionTimeout); ServerToClientFunctionResultSender resultSender = null; Function<?> functionObject = null; try { if (function instanceof String) { functionObject = FunctionService.getFunction((String) function); if (functionObject == null) { String message = LocalizedStrings.ExecuteRegionFunction_THE_FUNCTION_0_HAS_NOT_BEEN_REGISTERED .toLocalizedString(function); logger.warn("{}: {}", serverConnection.getName(), message); sendError(hasResult, clientMessage, message, serverConnection); return; } else { byte functionStateOnServer = AbstractExecution.getFunctionState(functionObject.isHA(), functionObject.hasResult(), functionObject.optimizeForWrite()); if (functionStateOnServer != functionState) { String message = LocalizedStrings.FunctionService_FUNCTION_ATTRIBUTE_MISMATCH_CLIENT_SERVER .toLocalizedString(function); logger.warn("{}: {}", serverConnection.getName(), message); sendError(hasResult, clientMessage, message, serverConnection); return; } } } else { functionObject = (Function) function; } // check if the caller is authorized to do this operation on server functionObject.getRequiredPermissions(regionName).forEach(securityService::authorize); AuthorizeRequest authzRequest = serverConnection.getAuthzRequest(); final String functionName = functionObject.getId(); final String regionPath = region.getFullPath(); ExecuteFunctionOperationContext executeContext = null; if (authzRequest != null) { executeContext = authzRequest.executeFunctionAuthorize(functionName, regionPath, filter, args, functionObject.optimizeForWrite()); } // Construct execution AbstractExecution execution = (AbstractExecution) FunctionService.onRegion(region); ChunkedMessage m = serverConnection.getFunctionResponseMessage(); m.setTransactionId(clientMessage.getTransactionId()); resultSender = new ServerToClientFunctionResultSender65(m, MessageType.EXECUTE_REGION_FUNCTION_RESULT, serverConnection, functionObject, executeContext); if (isExecuteOnAllBuckets == 1) { PartitionedRegion pr = (PartitionedRegion) region; Set<Integer> actualBucketSet = pr.getRegionAdvisor().getBucketSet(); try { buckets.retainAll(actualBucketSet); } catch (NoSuchElementException done) { } if (buckets.isEmpty()) { throw new FunctionException("Buckets are null"); } execution = new PartitionedRegionFunctionExecutor((PartitionedRegion) region, buckets, args, memberMappedArg, resultSender, removedNodesSet, true, true); } else { execution = new PartitionedRegionFunctionExecutor((PartitionedRegion) region, filter, args, memberMappedArg, resultSender, removedNodesSet, false, true); } if ((hasResult == 1) && filter != null && filter.size() == 1) { ServerConnection.executeFunctionOnLocalNodeOnly((byte) 1); } if (logger.isDebugEnabled()) { logger.debug("Executing Function: {} on Server: {} with Execution: {}", functionObject.getId(), serverConnection, execution); } if (hasResult == 1) { if (function instanceof String) { switch (functionState) { case AbstractExecution.NO_HA_HASRESULT_NO_OPTIMIZEFORWRITE: execution.execute((String) function).getResult(); break; case AbstractExecution.HA_HASRESULT_NO_OPTIMIZEFORWRITE: execution.execute((String) function).getResult(); break; case AbstractExecution.HA_HASRESULT_OPTIMIZEFORWRITE: execution.execute((String) function).getResult(); break; case AbstractExecution.NO_HA_HASRESULT_OPTIMIZEFORWRITE: execution.execute((String) function).getResult(); break; } } else { execution.execute(functionObject).getResult(); } } else { if (function instanceof String) { switch (functionState) { case AbstractExecution.NO_HA_NO_HASRESULT_NO_OPTIMIZEFORWRITE: execution.execute((String) function); break; case AbstractExecution.NO_HA_NO_HASRESULT_OPTIMIZEFORWRITE: execution.execute((String) function); break; } } else { execution.execute(functionObject); } } } catch (IOException ioe) { logger.warn(LocalizedMessage.create( LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), ioe); final String message = LocalizedStrings.ExecuteRegionFunction_SERVER_COULD_NOT_SEND_THE_REPLY .toLocalizedString(); sendException(hasResult, clientMessage, message, serverConnection, ioe); } catch (FunctionException fe) { String message = fe.getMessage(); if (fe.getCause() instanceof FunctionInvocationTargetException) { if (functionObject.isHA() && logger.isDebugEnabled()) { logger.debug("Exception on server while executing function: {}: {}", function, message); } else if (logger.isDebugEnabled()) { logger.debug("Exception on server while executing function: {}: {}", function, message, fe); } synchronized (clientMessage) { resultSender.setException(fe); } } else { if (logger.isDebugEnabled()) { logger.debug(LocalizedMessage.create( LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), fe); } sendException(hasResult, clientMessage, message, serverConnection, fe); } } catch (Exception e) { logger.warn(LocalizedMessage.create( LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), e); String message = e.getMessage(); sendException(hasResult, clientMessage, message, serverConnection, e); } finally { handshake.setClientReadTimeout(earlierClientReadTimeout); ServerConnection.executeFunctionOnLocalNodeOnly((byte) 0); } } private void sendException(byte hasResult, Message msg, String message, ServerConnection serverConnection, Throwable e) throws IOException { synchronized (msg) { if (hasResult == 1) { writeFunctionResponseException(msg, MessageType.EXCEPTION, message, serverConnection, e); serverConnection.setAsTrue(RESPONDED); } } } private void sendError(byte hasResult, Message msg, String message, ServerConnection serverConnection) throws IOException { synchronized (msg) { if (hasResult == 1) { writeFunctionResponseError(msg, MessageType.EXECUTE_REGION_FUNCTION_ERROR, message, serverConnection); serverConnection.setAsTrue(RESPONDED); } } } protected static void writeFunctionResponseException(Message origMsg, int messageType, String message, ServerConnection serverConnection, Throwable e) throws IOException { ChunkedMessage functionResponseMsg = serverConnection.getFunctionResponseMessage(); ChunkedMessage chunkedResponseMsg = serverConnection.getChunkedResponseMessage(); int numParts = 0; if (functionResponseMsg.headerHasBeenSent()) { if (e instanceof FunctionException && e.getCause() instanceof InternalFunctionInvocationTargetException) { functionResponseMsg.setNumberOfParts(3); functionResponseMsg.addObjPart(e); functionResponseMsg.addStringPart(BaseCommand.getExceptionTrace(e)); InternalFunctionInvocationTargetException fe = (InternalFunctionInvocationTargetException) e.getCause(); functionResponseMsg.addObjPart(fe.getFailedNodeSet()); numParts = 3; } else { functionResponseMsg.setNumberOfParts(2); functionResponseMsg.addObjPart(e); functionResponseMsg.addStringPart(BaseCommand.getExceptionTrace(e)); numParts = 2; } if (logger.isDebugEnabled()) { logger.debug("{}: Sending exception chunk while reply in progress: ", serverConnection.getName(), e); } functionResponseMsg.setServerConnection(serverConnection); functionResponseMsg.setLastChunkAndNumParts(true, numParts); functionResponseMsg.sendChunk(serverConnection); } else { chunkedResponseMsg.setMessageType(messageType); chunkedResponseMsg.setTransactionId(origMsg.getTransactionId()); chunkedResponseMsg.sendHeader(); if (e instanceof FunctionException && e.getCause() instanceof InternalFunctionInvocationTargetException) { chunkedResponseMsg.setNumberOfParts(3); chunkedResponseMsg.addObjPart(e); chunkedResponseMsg.addStringPart(BaseCommand.getExceptionTrace(e)); InternalFunctionInvocationTargetException fe = (InternalFunctionInvocationTargetException) e.getCause(); chunkedResponseMsg.addObjPart(fe.getFailedNodeSet()); numParts = 3; } else { chunkedResponseMsg.setNumberOfParts(2); chunkedResponseMsg.addObjPart(e); chunkedResponseMsg.addStringPart(BaseCommand.getExceptionTrace(e)); numParts = 2; } if (logger.isDebugEnabled()) { logger.debug("{}: Sending exception chunk: ", serverConnection.getName(), e); } chunkedResponseMsg.setServerConnection(serverConnection); chunkedResponseMsg.setLastChunkAndNumParts(true, numParts); chunkedResponseMsg.sendChunk(serverConnection); } } }
geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/command/ExecuteRegionFunctionSingleHop.java
/* * 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.geode.internal.cache.tier.sockets.command; import java.io.IOException; import java.util.HashSet; import java.util.NoSuchElementException; import java.util.Set; import org.apache.geode.cache.Region; import org.apache.geode.cache.client.internal.ConnectionImpl; import org.apache.geode.cache.execute.Function; import org.apache.geode.cache.execute.FunctionException; import org.apache.geode.cache.execute.FunctionInvocationTargetException; import org.apache.geode.cache.execute.FunctionService; import org.apache.geode.cache.operations.ExecuteFunctionOperationContext; import org.apache.geode.internal.Version; import org.apache.geode.internal.cache.PartitionedRegion; import org.apache.geode.internal.cache.execute.AbstractExecution; import org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException; import org.apache.geode.internal.cache.execute.MemberMappedArgument; import org.apache.geode.internal.cache.execute.PartitionedRegionFunctionExecutor; import org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender; import org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender65; import org.apache.geode.internal.cache.tier.CachedRegionHelper; import org.apache.geode.internal.cache.tier.Command; import org.apache.geode.internal.cache.tier.MessageType; import org.apache.geode.internal.cache.tier.ServerSideHandshake; import org.apache.geode.internal.cache.tier.sockets.BaseCommand; import org.apache.geode.internal.cache.tier.sockets.ChunkedMessage; import org.apache.geode.internal.cache.tier.sockets.Message; import org.apache.geode.internal.cache.tier.sockets.Part; import org.apache.geode.internal.cache.tier.sockets.ServerConnection; import org.apache.geode.internal.i18n.LocalizedStrings; import org.apache.geode.internal.logging.log4j.LocalizedMessage; import org.apache.geode.internal.security.AuthorizeRequest; import org.apache.geode.internal.security.SecurityService; /** * @since GemFire 6.5 */ public class ExecuteRegionFunctionSingleHop extends BaseCommand { private static final ExecuteRegionFunctionSingleHop singleton = new ExecuteRegionFunctionSingleHop(); public static Command getCommand() { return singleton; } private ExecuteRegionFunctionSingleHop() {} @Override public void cmdExecute(final Message clientMessage, final ServerConnection serverConnection, final SecurityService securityService, long start) throws IOException { String regionName = null; Object function = null; Object args = null; MemberMappedArgument memberMappedArg = null; byte isExecuteOnAllBuckets = 0; Set<Object> filter = null; Set<Integer> buckets = null; byte hasResult = 0; byte functionState = 0; int removedNodesSize = 0; Set<Object> removedNodesSet = null; int filterSize = 0, bucketIdsSize = 0, partNumber = 0; CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper(); int functionTimeout = ConnectionImpl.DEFAULT_CLIENT_FUNCTION_TIMEOUT; try { byte[] bytes = clientMessage.getPart(0).getSerializedForm(); functionState = bytes[0]; if (bytes.length >= 5 && serverConnection.getClientVersion().ordinal() >= Version.GFE_8009.ordinal()) { functionTimeout = Part.decodeInt(bytes, 1); } if (functionState != 1) { hasResult = (byte) ((functionState & 2) - 1); } else { hasResult = functionState; } if (hasResult == 1) { serverConnection.setAsTrue(REQUIRES_RESPONSE); serverConnection.setAsTrue(REQUIRES_CHUNKED_RESPONSE); } regionName = clientMessage.getPart(1).getString(); function = clientMessage.getPart(2).getStringOrObject(); args = clientMessage.getPart(3).getObject(); Part part = clientMessage.getPart(4); if (part != null) { Object obj = part.getObject(); if (obj instanceof MemberMappedArgument) { memberMappedArg = (MemberMappedArgument) obj; } } isExecuteOnAllBuckets = clientMessage.getPart(5).getSerializedForm()[0]; if (isExecuteOnAllBuckets == 1) { filter = new HashSet(); bucketIdsSize = clientMessage.getPart(6).getInt(); if (bucketIdsSize != 0) { buckets = new HashSet<Integer>(); partNumber = 7; for (int i = 0; i < bucketIdsSize; i++) { buckets.add(clientMessage.getPart(partNumber + i).getInt()); } } partNumber = 7 + bucketIdsSize; } else { filterSize = clientMessage.getPart(6).getInt(); if (filterSize != 0) { filter = new HashSet<Object>(); partNumber = 7; for (int i = 0; i < filterSize; i++) { filter.add(clientMessage.getPart(partNumber + i).getStringOrObject()); } } partNumber = 7 + filterSize; } removedNodesSize = clientMessage.getPart(partNumber).getInt(); if (removedNodesSize != 0) { removedNodesSet = new HashSet<Object>(); partNumber = partNumber + 1; for (int i = 0; i < removedNodesSize; i++) { removedNodesSet.add(clientMessage.getPart(partNumber + i).getStringOrObject()); } } } catch (ClassNotFoundException exception) { logger.warn(LocalizedMessage.create( LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), exception); if (hasResult == 1) { writeChunkedException(clientMessage, exception, serverConnection); serverConnection.setAsTrue(RESPONDED); return; } } if (function == null || regionName == null) { String message = null; if (function == null) { message = LocalizedStrings.ExecuteRegionFunction_THE_INPUT_0_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL .toLocalizedString("function"); } if (regionName == null) { message = LocalizedStrings.ExecuteRegionFunction_THE_INPUT_0_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL .toLocalizedString("region"); } logger.warn("{}: {}", serverConnection.getName(), message); sendError(hasResult, clientMessage, message, serverConnection); return; } Region region = crHelper.getRegion(regionName); if (region == null) { String message = LocalizedStrings.ExecuteRegionFunction_THE_REGION_NAMED_0_WAS_NOT_FOUND_DURING_EXECUTE_FUNCTION_REQUEST .toLocalizedString(regionName); logger.warn("{}: {}", serverConnection.getName(), message); sendError(hasResult, clientMessage, message, serverConnection); return; } ServerSideHandshake handshake = serverConnection.getHandshake(); int earlierClientReadTimeout = handshake.getClientReadTimeout(); handshake.setClientReadTimeout(functionTimeout); ServerToClientFunctionResultSender resultSender = null; Function<?> functionObject = null; try { if (function instanceof String) { functionObject = FunctionService.getFunction((String) function); if (functionObject == null) { String message = LocalizedStrings.ExecuteRegionFunction_THE_FUNCTION_0_HAS_NOT_BEEN_REGISTERED .toLocalizedString(function); logger.warn("{}: {}", serverConnection.getName(), message); sendError(hasResult, clientMessage, message, serverConnection); return; } else { byte functionStateOnServer = AbstractExecution.getFunctionState(functionObject.isHA(), functionObject.hasResult(), functionObject.optimizeForWrite()); if (functionStateOnServer != functionState) { String message = LocalizedStrings.FunctionService_FUNCTION_ATTRIBUTE_MISMATCH_CLIENT_SERVER .toLocalizedString(function); logger.warn("{}: {}", serverConnection.getName(), message); sendError(hasResult, clientMessage, message, serverConnection); return; } } } else { functionObject = (Function) function; } // check if the caller is authorized to do this operation on server functionObject.getRequiredPermissions(regionName).forEach(securityService::authorize); AuthorizeRequest authzRequest = serverConnection.getAuthzRequest(); final String functionName = functionObject.getId(); final String regionPath = region.getFullPath(); ExecuteFunctionOperationContext executeContext = null; if (authzRequest != null) { executeContext = authzRequest.executeFunctionAuthorize(functionName, regionPath, filter, args, functionObject.optimizeForWrite()); } // Construct execution AbstractExecution execution = (AbstractExecution) FunctionService.onRegion(region); ChunkedMessage m = serverConnection.getFunctionResponseMessage(); m.setTransactionId(clientMessage.getTransactionId()); resultSender = new ServerToClientFunctionResultSender65(m, MessageType.EXECUTE_REGION_FUNCTION_RESULT, serverConnection, functionObject, executeContext); if (isExecuteOnAllBuckets == 1) { PartitionedRegion pr = (PartitionedRegion) region; Set<Integer> actualBucketSet = pr.getRegionAdvisor().getBucketSet(); try { buckets.retainAll(actualBucketSet); } catch (NoSuchElementException done) { } if (buckets.isEmpty()) { throw new FunctionException("Buckets are null"); } execution = new PartitionedRegionFunctionExecutor((PartitionedRegion) region, buckets, args, memberMappedArg, resultSender, removedNodesSet, true, true); } else { execution = new PartitionedRegionFunctionExecutor((PartitionedRegion) region, filter, args, memberMappedArg, resultSender, removedNodesSet, false, true); } if ((hasResult == 1) && filter != null && filter.size() == 1) { ServerConnection.executeFunctionOnLocalNodeOnly((byte) 1); } if (logger.isDebugEnabled()) { logger.debug("Executing Function: {} on Server: {} with Execution: {}", functionObject.getId(), serverConnection, execution); } if (hasResult == 1) { if (function instanceof String) { switch (functionState) { case AbstractExecution.NO_HA_HASRESULT_NO_OPTIMIZEFORWRITE: execution.execute((String) function).getResult(); break; case AbstractExecution.HA_HASRESULT_NO_OPTIMIZEFORWRITE: execution.execute((String) function).getResult(); break; case AbstractExecution.HA_HASRESULT_OPTIMIZEFORWRITE: execution.execute((String) function).getResult(); break; case AbstractExecution.NO_HA_HASRESULT_OPTIMIZEFORWRITE: execution.execute((String) function).getResult(); break; } } else { execution.execute(functionObject).getResult(); } } else { if (function instanceof String) { switch (functionState) { case AbstractExecution.NO_HA_NO_HASRESULT_NO_OPTIMIZEFORWRITE: execution.execute((String) function); break; case AbstractExecution.NO_HA_NO_HASRESULT_OPTIMIZEFORWRITE: execution.execute((String) function); break; } } else { execution.execute(functionObject); } } } catch (IOException ioe) { logger.warn(LocalizedMessage.create( LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), ioe); final String message = LocalizedStrings.ExecuteRegionFunction_SERVER_COULD_NOT_SEND_THE_REPLY .toLocalizedString(); sendException(hasResult, clientMessage, message, serverConnection, ioe); } catch (FunctionException fe) { String message = fe.getMessage(); if (fe.getCause() instanceof FunctionInvocationTargetException) { if (functionObject.isHA() && logger.isDebugEnabled()) { logger.debug("Exception on server while executing function: {}: {}", function, message); } else if (logger.isDebugEnabled()) { logger.debug("Exception on server while executing function: {}: {}", function, message, fe); } synchronized (clientMessage) { resultSender.setException(fe); } } else { logger.warn(LocalizedMessage.create( LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), fe); sendException(hasResult, clientMessage, message, serverConnection, fe); } } catch (Exception e) { logger.warn(LocalizedMessage.create( LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), e); String message = e.getMessage(); sendException(hasResult, clientMessage, message, serverConnection, e); } finally { handshake.setClientReadTimeout(earlierClientReadTimeout); ServerConnection.executeFunctionOnLocalNodeOnly((byte) 0); } } private void sendException(byte hasResult, Message msg, String message, ServerConnection serverConnection, Throwable e) throws IOException { synchronized (msg) { if (hasResult == 1) { writeFunctionResponseException(msg, MessageType.EXCEPTION, message, serverConnection, e); serverConnection.setAsTrue(RESPONDED); } } } private void sendError(byte hasResult, Message msg, String message, ServerConnection serverConnection) throws IOException { synchronized (msg) { if (hasResult == 1) { writeFunctionResponseError(msg, MessageType.EXECUTE_REGION_FUNCTION_ERROR, message, serverConnection); serverConnection.setAsTrue(RESPONDED); } } } protected static void writeFunctionResponseException(Message origMsg, int messageType, String message, ServerConnection serverConnection, Throwable e) throws IOException { ChunkedMessage functionResponseMsg = serverConnection.getFunctionResponseMessage(); ChunkedMessage chunkedResponseMsg = serverConnection.getChunkedResponseMessage(); int numParts = 0; if (functionResponseMsg.headerHasBeenSent()) { if (e instanceof FunctionException && e.getCause() instanceof InternalFunctionInvocationTargetException) { functionResponseMsg.setNumberOfParts(3); functionResponseMsg.addObjPart(e); functionResponseMsg.addStringPart(BaseCommand.getExceptionTrace(e)); InternalFunctionInvocationTargetException fe = (InternalFunctionInvocationTargetException) e.getCause(); functionResponseMsg.addObjPart(fe.getFailedNodeSet()); numParts = 3; } else { functionResponseMsg.setNumberOfParts(2); functionResponseMsg.addObjPart(e); functionResponseMsg.addStringPart(BaseCommand.getExceptionTrace(e)); numParts = 2; } if (logger.isDebugEnabled()) { logger.debug("{}: Sending exception chunk while reply in progress: ", serverConnection.getName(), e); } functionResponseMsg.setServerConnection(serverConnection); functionResponseMsg.setLastChunkAndNumParts(true, numParts); functionResponseMsg.sendChunk(serverConnection); } else { chunkedResponseMsg.setMessageType(messageType); chunkedResponseMsg.setTransactionId(origMsg.getTransactionId()); chunkedResponseMsg.sendHeader(); if (e instanceof FunctionException && e.getCause() instanceof InternalFunctionInvocationTargetException) { chunkedResponseMsg.setNumberOfParts(3); chunkedResponseMsg.addObjPart(e); chunkedResponseMsg.addStringPart(BaseCommand.getExceptionTrace(e)); InternalFunctionInvocationTargetException fe = (InternalFunctionInvocationTargetException) e.getCause(); chunkedResponseMsg.addObjPart(fe.getFailedNodeSet()); numParts = 3; } else { chunkedResponseMsg.setNumberOfParts(2); chunkedResponseMsg.addObjPart(e); chunkedResponseMsg.addStringPart(BaseCommand.getExceptionTrace(e)); numParts = 2; } if (logger.isDebugEnabled()) { logger.debug("{}: Sending exception chunk: ", serverConnection.getName(), e); } chunkedResponseMsg.setServerConnection(serverConnection); chunkedResponseMsg.setLastChunkAndNumParts(true, numParts); chunkedResponseMsg.sendChunk(serverConnection); } } }
GEODE-3013: Prevent multiple node found error to be displayed in the log (#2029) * This will be visible if debug mode is set. Co-authored-by: Ivan Godwin <[email protected]>
geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/command/ExecuteRegionFunctionSingleHop.java
GEODE-3013: Prevent multiple node found error to be displayed in the log (#2029)
<ide><path>eode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/command/ExecuteRegionFunctionSingleHop.java <ide> resultSender.setException(fe); <ide> } <ide> } else { <del> logger.warn(LocalizedMessage.create( <del> LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, <del> function), fe); <add> if (logger.isDebugEnabled()) { <add> logger.debug(LocalizedMessage.create( <add> LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, <add> function), fe); <add> } <ide> sendException(hasResult, clientMessage, message, serverConnection, fe); <ide> } <ide> } catch (Exception e) {
Java
apache-2.0
a22072444e0a4d4ee8c535416011de833f45cbc1
0
DaveVoorhis/Rel,DaveVoorhis/Rel,DaveVoorhis/Rel,DaveVoorhis/Rel,DaveVoorhis/Rel
package org.reldb.dbrowser.ui.html; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.HTMLTransfer; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.widgets.Composite; public class BrowserNativeWidget extends Browser { public BrowserNativeWidget(Composite parent, int style) { super(parent, style); this.addStatusTextListener(evt -> { if (!evt.text.startsWith(Style.getSelectionIndicator())) return; String text = evt.text.substring(Style.getSelectionIndicator().length()).replace("<table", "<table border=\"1\""); if (text == null || text.length() == 0) return; Clipboard clipboard = new Clipboard(parent.getDisplay()); TextTransfer textTransfer = TextTransfer.getInstance(); HTMLTransfer htmlTransfer = HTMLTransfer.getInstance(); Transfer[] transfers = new Transfer[] {textTransfer, htmlTransfer}; Object[] data = new Object[] {text, text}; clipboard.setContents(data, transfers); clipboard.dispose(); }); } public void copy() { execute("obtainSel();"); } public void selectAll() { execute("selectAll();"); } public void checkSubclass() { } }
RelUI/src/org/reldb/dbrowser/ui/html/BrowserNativeWidget.java
package org.reldb.dbrowser.ui.html; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.HTMLTransfer; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.widgets.Composite; public class BrowserNativeWidget extends Browser { public BrowserNativeWidget(Composite parent, int style) { super(parent, style); this.addStatusTextListener(evt -> { if (!evt.text.startsWith(Style.getSelectionIndicator())) return; String text = evt.text.substring(Style.getSelectionIndicator().length()).replace("<table", "<table border=\"1\""); if (text == null || text.length() == 0) { return; } Clipboard clipboard = new Clipboard(parent.getDisplay()); TextTransfer textTransfer = TextTransfer.getInstance(); if (textTransfer == null) { System.out.println("BrowserNativeWidget: TextTransfer is null. Copy of text to clipboard not supported."); return; } HTMLTransfer htmlTransfer = HTMLTransfer.getInstance(); if (htmlTransfer == null) { System.out.println("BrowserNativeWidget: HTMLTransfer is null. Copy of HTML to clipboard not supported."); return; } Transfer[] transfers = new Transfer[] {textTransfer, htmlTransfer}; Object[] data = new Object[] {text, text}; clipboard.setContents(data, transfers); clipboard.dispose(); }); } public void copy() { execute("obtainSel();"); } public void selectAll() { execute("selectAll();"); } public void checkSubclass() { } }
Remove debugging code.
RelUI/src/org/reldb/dbrowser/ui/html/BrowserNativeWidget.java
Remove debugging code.
<ide><path>elUI/src/org/reldb/dbrowser/ui/html/BrowserNativeWidget.java <ide> if (!evt.text.startsWith(Style.getSelectionIndicator())) <ide> return; <ide> String text = evt.text.substring(Style.getSelectionIndicator().length()).replace("<table", "<table border=\"1\""); <del> if (text == null || text.length() == 0) { <add> if (text == null || text.length() == 0) <ide> return; <del> } <ide> Clipboard clipboard = new Clipboard(parent.getDisplay()); <ide> TextTransfer textTransfer = TextTransfer.getInstance(); <del> if (textTransfer == null) { <del> System.out.println("BrowserNativeWidget: TextTransfer is null. Copy of text to clipboard not supported."); <del> return; <del> } <ide> HTMLTransfer htmlTransfer = HTMLTransfer.getInstance(); <del> if (htmlTransfer == null) { <del> System.out.println("BrowserNativeWidget: HTMLTransfer is null. Copy of HTML to clipboard not supported."); <del> return; <del> } <ide> Transfer[] transfers = new Transfer[] {textTransfer, htmlTransfer}; <ide> Object[] data = new Object[] {text, text}; <ide> clipboard.setContents(data, transfers);
JavaScript
agpl-3.0
72b53e1b3ffc2297012e1d5732fca734e5b7d0a2
0
adunning/zotero,rmzelle/zotero,hoehnp/zotero,hoehnp/zotero,hoehnp/zotero,LinuxMercedes/zotero,egh/zotero,LinuxMercedes/zotero,gracile-fr/zotero,retorquere/zotero,retorquere/zotero,gracile-fr/zotero,rmzelle/zotero,fbennett/zotero,egh/zotero,adunning/zotero,retorquere/zotero,robamler/zotero,egh/zotero,sendecomp/zotero,robamler/zotero,robamler/zotero,rmzelle/zotero,sendecomp/zotero,aurimasv/zotero,LinuxMercedes/zotero,sendecomp/zotero,adunning/zotero,gracile-fr/zotero
/* ***** BEGIN LICENSE BLOCK ***** Copyright (c) 2006 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://chnm.gmu.edu 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. ***** END LICENSE BLOCK ***** */ Zotero.Schema = new function(){ this.userDataUpgradeRequired = userDataUpgradeRequired; this.showUpgradeWizard = showUpgradeWizard; this.updateSchema = updateSchema; this.updateScrapersRemote = updateScrapersRemote; this.stopRepositoryTimer = stopRepositoryTimer; this.rebuildTranslatorsAndStylesTables = rebuildTranslatorsAndStylesTables; this.rebuildTranslatorsTable = rebuildTranslatorsTable; this.dbInitialized = false; this.upgradeFinished = false; this.goToChangeLog = false; var _dbVersions = []; var _schemaVersions = []; var _repositoryTimer; var _remoteUpdateInProgress = false; var self = this; function userDataUpgradeRequired() { var dbVersion = _getDBVersion('userdata'); var schemaVersion = _getSchemaSQLVersion('userdata'); return dbVersion && (dbVersion < schemaVersion); } function showUpgradeWizard() { var dbVersion = _getDBVersion('userdata'); var schemaVersion = _getSchemaSQLVersion('userdata'); var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getService(Components.interfaces.nsIWindowWatcher); var obj = { Zotero: Zotero, data: { success: false } }; var io = { wrappedJSObject: obj }; var win = ww.openWindow(null, "chrome://zotero/content/upgrade.xul", "zotero-schema-upgrade", "chrome,centerscreen,modal", io); if (obj.data.e) { var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getService(Components.interfaces.nsIWindowWatcher); var data = { msg: obj.data.msg, e: obj.data.e, extraData: "Schema upgrade from " + dbVersion + " to " + schemaVersion }; var io = { wrappedJSObject: { Zotero: Zotero, data: data } }; var win = ww.openWindow(null, "chrome://zotero/content/errorReport.xul", "zotero-error-report", "chrome,centerscreen,modal", io); } return obj.data.success; } /* * Checks if the DB schema exists and is up-to-date, updating if necessary */ function updateSchema(){ var dbVersion = _getDBVersion('userdata'); // 'schema' check is for old (<= 1.0b1) schema system, // 'user' is for pre-1.0b2 'user' table if (!dbVersion && !_getDBVersion('schema') && !_getDBVersion('user')){ Zotero.debug('Database does not exist -- creating\n'); _initializeSchema(); return; } var schemaVersion = _getSchemaSQLVersion('userdata'); try { Zotero.UnresponsiveScriptIndicator.disable(); // If upgrading userdata, make backup of database first if (dbVersion < schemaVersion){ Zotero.DB.backupDatabase(dbVersion); } Zotero.DB.beginTransaction(); try { // Old schema system if (!dbVersion){ // Check for pre-1.0b2 'user' table var user = _getDBVersion('user'); if (user) { dbVersion = user; var sql = "UPDATE version SET schema=? WHERE schema=?"; Zotero.DB.query(sql, ['userdata', 'user']); } else { dbVersion = 0; } } var up1 = _migrateUserDataSchema(dbVersion); var up2 = _updateSchema('system'); var up3 = _updateSchema('triggers'); var up4 = _updateSchema('scrapers'); Zotero.DB.commitTransaction(); } catch(e){ Zotero.debug(e); Zotero.DB.rollbackTransaction(); throw(e); } if (up1) { // Upgrade seems to have been a success -- delete any previous backups var maxPrevious = dbVersion - 1; var file = Zotero.getZoteroDirectory(); // directoryEntries.hasMoreElements() throws an error (possibly // because of the temporary SQLite journal file?), so we just look // for all versions for (var i=maxPrevious; i>=29; i--) { var fileName = 'zotero.sqlite.' + i + '.bak'; file.append(fileName); if (file.exists()) { Zotero.debug('Removing previous backup file ' + fileName); file.remove(null); } file = file.parent; } } if (up2 || up3 || up4) { // Run a manual scraper update if upgraded and pref set if (Zotero.Prefs.get('automaticScraperUpdates')){ this.updateScrapersRemote(2); } } } finally { Zotero.UnresponsiveScriptIndicator.enable(); } return; } /** * Send XMLHTTP request for updated scrapers to the central repository * * _force_ forces a repository query regardless of how long it's been * since the last check **/ function updateScrapersRemote(force, callback) { // Little hack to manually update CSLs from repo on upgrades if (!force && Zotero.Prefs.get('automaticScraperUpdates')) { var syncTargetVersion = 3; // increment this when releasing new version that requires it var syncVersion = _getDBVersion('sync'); if (syncVersion < syncTargetVersion) { force = true; var forceCSLUpdate = true; } } if (!force){ if (_remoteUpdateInProgress) { Zotero.debug("A remote update is already in progress -- not checking repository"); return false; } // Check user preference for automatic updates if (!Zotero.Prefs.get('automaticScraperUpdates')){ Zotero.debug('Automatic scraper updating disabled -- not checking repository', 4); return false; } // Determine the earliest local time that we'd query the repository again var nextCheck = new Date(); nextCheck.setTime((parseInt(_getDBVersion('lastcheck')) + ZOTERO_CONFIG['REPOSITORY_CHECK_INTERVAL']) * 1000); // JS uses ms var now = new Date(); // If enough time hasn't passed, don't update if (now < nextCheck){ Zotero.debug('Not enough time since last update -- not checking repository', 4); // Set the repository timer to the remaining time _setRepositoryTimer(Math.round((nextCheck.getTime() - now.getTime()) / 1000)); return false; } } // If transaction already in progress, delay by ten minutes if (Zotero.DB.transactionInProgress()){ Zotero.debug('Transaction in progress -- delaying repository check', 4) _setRepositoryTimer(600); return false; } // Get the last timestamp we got from the server var lastUpdated = _getDBVersion('repository'); var url = ZOTERO_CONFIG['REPOSITORY_URL'] + '/updated?' + (lastUpdated ? 'last=' + lastUpdated + '&' : '') + 'version=' + Zotero.version; Zotero.debug('Checking repository for updates'); _remoteUpdateInProgress = true; if (force) { if (force == 2) { url += '&m=2'; } else { url += '&m=1'; } // Force updating of all public CSLs if (forceCSLUpdate) { url += '&cslup=' + syncTargetVersion; } } var get = Zotero.Utilities.HTTP.doGet(url, function (xmlhttp) { var updated = _updateScrapersRemoteCallback(xmlhttp, !!force); if (callback) { callback(xmlhttp, updated) } }); // TODO: instead, add an observer to start and stop timer on online state change if (!get){ Zotero.debug('Browser is offline -- skipping check'); _setRepositoryTimer(ZOTERO_CONFIG['REPOSITORY_RETRY_INTERVAL']); } } function stopRepositoryTimer(){ if (_repositoryTimer){ Zotero.debug('Stopping repository check timer'); _repositoryTimer.cancel(); } } function rebuildTranslatorsAndStylesTables(callback) { Zotero.debug("Rebuilding translators and styles tables"); Zotero.DB.beginTransaction(); Zotero.DB.query("DELETE FROM translators"); Zotero.DB.query("DELETE FROM csl"); var sql = "DELETE FROM version WHERE schema IN " + "('scrapers', 'repository', 'lastcheck')"; Zotero.DB.query(sql); _dbVersions['scrapers'] = null; _dbVersions['repository'] = null; _dbVersions['lastcheck'] = null; // Rebuild from scrapers.sql _updateSchema('scrapers'); // Rebuild the translator cache Zotero.debug("Clearing translator cache"); Zotero.Translate.cache = null; Zotero.Translate.init(); Zotero.DB.commitTransaction(); // Run a manual update from repository if pref set if (Zotero.Prefs.get('automaticScraperUpdates')) { this.updateScrapersRemote(2, callback); } } function rebuildTranslatorsTable(callback) { Zotero.debug("Rebuilding translators table"); Zotero.DB.beginTransaction(); Zotero.DB.query("DELETE FROM translators"); var sql = "DELETE FROM version WHERE schema IN " + "('scrapers', 'repository', 'lastcheck')"; Zotero.DB.query(sql); _dbVersions['scrapers'] = null; _dbVersions['repository'] = null; _dbVersions['lastcheck'] = null; // Rebuild from scrapers.sql _updateSchema('scrapers'); // Rebuild the translator cache Zotero.debug("Clearing translator cache"); Zotero.Translate.cache = null; Zotero.Translate.init(); Zotero.DB.commitTransaction(); // Run a manual update from repository if pref set if (Zotero.Prefs.get('automaticScraperUpdates')) { this.updateScrapersRemote(2, callback); } } ///////////////////////////////////////////////////////////////// // // Private methods // ///////////////////////////////////////////////////////////////// /* * Retrieve the DB schema version */ function _getDBVersion(schema){ if (_dbVersions[schema]){ return _dbVersions[schema]; } if (Zotero.DB.tableExists('version')){ var dbVersion = Zotero.DB.valueQuery("SELECT version FROM " + "version WHERE schema='" + schema + "'"); _dbVersions[schema] = dbVersion; return dbVersion; } return false; } /* * Retrieve the version from the top line of the schema SQL file */ function _getSchemaSQLVersion(schema){ if (!schema){ throw ('Schema type not provided to _getSchemaSQLVersion()'); } var schemaFile = schema + '.sql'; if (_schemaVersions[schema]){ return _schemaVersions[schema]; } var file = Components.classes["@mozilla.org/extensions/manager;1"] .getService(Components.interfaces.nsIExtensionManager) .getInstallLocation(ZOTERO_CONFIG['GUID']) .getItemLocation(ZOTERO_CONFIG['GUID']); file.append(schemaFile); // Open an input stream from file var istream = Components.classes["@mozilla.org/network/file-input-stream;1"] .createInstance(Components.interfaces.nsIFileInputStream); istream.init(file, 0x01, 0444, 0); istream.QueryInterface(Components.interfaces.nsILineInputStream); var line = {}; // Fetch the schema version from the first line of the file istream.readLine(line); var schemaVersion = line.value.match(/-- ([0-9]+)/)[1]; istream.close(); _schemaVersions[schema] = schemaVersion; return schemaVersion; } /* * Load in SQL schema * * Returns the contents of an SQL file for feeding into query() */ function _getSchemaSQL(schema){ if (!schema){ throw ('Schema type not provided to _getSchemaSQL()'); } var schemaFile = schema + '.sql'; // We pull the schema from an external file so we only have to process // it when necessary var file = Components.classes["@mozilla.org/extensions/manager;1"] .getService(Components.interfaces.nsIExtensionManager) .getInstallLocation(ZOTERO_CONFIG['GUID']) .getItemLocation(ZOTERO_CONFIG['GUID']); file.append(schemaFile); // Open an input stream from file var istream = Components.classes["@mozilla.org/network/file-input-stream;1"] .createInstance(Components.interfaces.nsIFileInputStream); istream.init(file, 0x01, 0444, 0); istream.QueryInterface(Components.interfaces.nsILineInputStream); var line = {}, sql = '', hasmore; // Skip the first line, which contains the schema version istream.readLine(line); //var schemaVersion = line.value.match(/-- ([0-9]+)/)[1]; do { hasmore = istream.readLine(line); sql += line.value + "\n"; } while(hasmore); istream.close(); return sql; } /* * Determine the SQL statements necessary to drop the tables and indexed * in a given schema file * * NOTE: This is not currently used. * * Returns the SQL statements as a string for feeding into query() */ function _getDropCommands(schema){ if (!schema){ throw ('Schema type not provided to _getSchemaSQL()'); } var schemaFile = schema + '.sql'; // We pull the schema from an external file so we only have to process // it when necessary var file = Components.classes["@mozilla.org/extensions/manager;1"] .getService(Components.interfaces.nsIExtensionManager) .getInstallLocation(ZOTERO_CONFIG['GUID']) .getItemLocation(ZOTERO_CONFIG['GUID']); file.append(schemaFile); // Open an input stream from file var istream = Components.classes["@mozilla.org/network/file-input-stream;1"] .createInstance(Components.interfaces.nsIFileInputStream); istream.init(file, 0x01, 0444, 0); istream.QueryInterface(Components.interfaces.nsILineInputStream); var line = {}, str = '', hasmore; // Skip the first line, which contains the schema version istream.readLine(line); do { hasmore = istream.readLine(line); var matches = line.value.match(/CREATE (TABLE|INDEX) IF NOT EXISTS ([^\s]+)/); if (matches){ str += "DROP " + matches[1] + " IF EXISTS " + matches[2] + ";\n"; } } while(hasmore); istream.close(); return str; } /* * Create new DB schema */ function _initializeSchema(){ Zotero.DB.beginTransaction(); try { // Enable auto-vacuuming Zotero.DB.query("PRAGMA page_size = 4096"); Zotero.DB.query("PRAGMA encoding = 'UTF-8'"); Zotero.DB.query("PRAGMA auto_vacuum = 1"); Zotero.DB.query(_getSchemaSQL('system')); Zotero.DB.query(_getSchemaSQL('userdata')); Zotero.DB.query(_getSchemaSQL('triggers')); Zotero.DB.query(_getSchemaSQL('scrapers')); _updateDBVersion('system', _getSchemaSQLVersion('system')); _updateDBVersion('userdata', _getSchemaSQLVersion('userdata')); _updateDBVersion('triggers', _getSchemaSQLVersion('triggers')); _updateDBVersion('scrapers', _getSchemaSQLVersion('scrapers')); /* TODO: uncomment for release var sql = "INSERT INTO items VALUES(1, 14, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 'AJ4PT6IT')"; Zotero.DB.query(sql); var sql = "INSERT INTO itemAttachments VALUES (1, NULL, 3, 'text/html', 25, NULL, NULL)"; Zotero.DB.query(sql); var sql = "INSERT INTO itemDataValues VALUES (?, ?)"; Zotero.DB.query(sql, [1, "Zotero - " + Zotero.getString('install.quickStartGuide')]); var sql = "INSERT INTO itemData VALUES (1, 110, 1)"; Zotero.DB.query(sql); var sql = "INSERT INTO itemDataValues VALUES (2, 'http://www.zotero.org/documentation/quick_start_guide')"; Zotero.DB.query(sql); var sql = "INSERT INTO itemData VALUES (1, 1, 2)"; Zotero.DB.query(sql); var sql = "INSERT INTO itemDataValues VALUES (3, CURRENT_TIMESTAMP)"; Zotero.DB.query(sql); var sql = "INSERT INTO itemData VALUES (1, 27, 3)"; Zotero.DB.query(sql); var sql = "INSERT INTO itemNotes (itemID, sourceItemID, note) VALUES (1, NULL, ?)"; var msg = Zotero.getString('install.quickStartGuide.message.welcome') + " " + Zotero.getString('install.quickStartGuide.message.clickViewPage') + "\n\n" + Zotero.getString('install.quickStartGuide.message.thanks'); Zotero.DB.query(sql, msg); */ Zotero.DB.commitTransaction(); self.dbInitialized = true; } catch(e){ Zotero.debug(e, 1); Components.utils.reportError(e); Zotero.DB.rollbackTransaction(); alert('Error initializing Zotero database'); throw(e); } } /* * Update a DB schema version tag in an existing database */ function _updateDBVersion(schema, version){ _dbVersions[schema] = version; var sql = "REPLACE INTO version (schema,version) VALUES (?,?)"; return Zotero.DB.query(sql, [{'string':schema},{'int':version}]); } function _updateSchema(schema){ var dbVersion = _getDBVersion(schema); var schemaVersion = _getSchemaSQLVersion(schema); if (dbVersion == schemaVersion){ return false; } else if (dbVersion < schemaVersion){ Zotero.DB.beginTransaction(); try { Zotero.DB.query(_getSchemaSQL(schema)); _updateDBVersion(schema, schemaVersion); Zotero.DB.commitTransaction(); } catch (e){ Zotero.debug(e, 1); Zotero.DB.rollbackTransaction(); throw(e); } return true; } throw("Zotero '" + schema + "' DB version is newer than SQL file"); } /** * Process the response from the repository **/ function _updateScrapersRemoteCallback(xmlhttp, manual){ if (!xmlhttp.responseXML){ try { if (xmlhttp.status>1000){ Zotero.debug('No network connection', 2); } else { Zotero.debug('Invalid response from repository', 2); } } catch (e){ Zotero.debug('Repository cannot be contacted'); } if (!manual){ _setRepositoryTimer(ZOTERO_CONFIG['REPOSITORY_RETRY_INTERVAL']); } _remoteUpdateInProgress = false; return false; } var currentTime = xmlhttp.responseXML. getElementsByTagName('currentTime')[0].firstChild.nodeValue; var translatorUpdates = xmlhttp.responseXML.getElementsByTagName('translator'); var styleUpdates = xmlhttp.responseXML.getElementsByTagName('style'); Zotero.DB.beginTransaction(); try { var re = /cslup=([0-9]+)/; var matches = re.exec(xmlhttp.channel.URI.spec); if (matches) { _updateDBVersion('sync', matches[1]); } } catch (e) { Zotero.debug(e); } // Store the timestamp provided by the server _updateDBVersion('repository', currentTime); if (!manual){ // And the local timestamp of the update time var d = new Date(); _updateDBVersion('lastcheck', Math.round(d.getTime()/1000)); // JS uses ms } if (!translatorUpdates.length && !styleUpdates.length){ Zotero.debug('All translators and styles are up-to-date'); Zotero.DB.commitTransaction(); if (!manual){ _setRepositoryTimer(ZOTERO_CONFIG['REPOSITORY_CHECK_INTERVAL']); } _remoteUpdateInProgress = false; return -1; } try { for (var i=0, len=translatorUpdates.length; i<len; i++){ _translatorXMLToDB(translatorUpdates[i]); } for (var i=0, len=styleUpdates.length; i<len; i++){ _styleXMLToDB(styleUpdates[i]); } // Rebuild the translator cache Zotero.debug("Clearing translator cache"); Zotero.Translate.cache = null; Zotero.Translate.init(); } catch (e) { Zotero.debug(e, 1); Zotero.DB.rollbackTransaction(); if (!manual){ _setRepositoryTimer(ZOTERO_CONFIG['REPOSITORY_RETRY_INTERVAL']); } _remoteUpdateInProgress = false; return false; } Zotero.DB.commitTransaction(); if (!manual){ _setRepositoryTimer(ZOTERO_CONFIG['REPOSITORY_CHECK_INTERVAL']); } _remoteUpdateInProgress = false; return true; } /** * Set the interval between repository queries * * We add an additional two seconds to avoid race conditions **/ function _setRepositoryTimer(interval){ if (!interval){ interval = ZOTERO_CONFIG['REPOSITORY_CHECK_INTERVAL']; } var fudge = 2; // two seconds var displayInterval = interval + fudge; var interval = (interval + fudge) * 1000; // convert to ms if (!_repositoryTimer || _repositoryTimer.delay!=interval){ Zotero.debug('Setting repository check interval to ' + displayInterval + ' seconds'); _repositoryTimer = Components.classes["@mozilla.org/timer;1"]. createInstance(Components.interfaces.nsITimer); _repositoryTimer.initWithCallback({ // implements nsITimerCallback notify: function(timer){ Zotero.Schema.updateScrapersRemote(); } }, interval, Components.interfaces.nsITimer.TYPE_REPEATING_SLACK); } } /** * Traverse an XML translator node from the repository and * update the local scrapers table with the scraper data **/ function _translatorXMLToDB(xmlnode){ // Don't split >4K chunks into multiple nodes // https://bugzilla.mozilla.org/show_bug.cgi?id=194231 xmlnode.normalize(); // Delete local version of remote translators with priority 0 if (xmlnode.getElementsByTagName('priority')[0].firstChild.nodeValue === "0") { var sql = "DELETE FROM translators WHERE translatorID=?"; return Zotero.DB.query(sql, {string: xmlnode.getAttribute('id')}); } var sqlValues = [ {string: xmlnode.getAttribute('id')}, {string: xmlnode.getAttribute('minVersion')}, {string: xmlnode.getAttribute('maxVersion')}, {string: xmlnode.getAttribute('lastUpdated')}, 1, // inRepository {int: xmlnode.getElementsByTagName('priority')[0].firstChild.nodeValue}, {int: xmlnode.getAttribute('type')}, {string: xmlnode.getElementsByTagName('label')[0].firstChild.nodeValue}, {string: xmlnode.getElementsByTagName('creator')[0].firstChild.nodeValue}, // target (xmlnode.getElementsByTagName('target').item(0) && xmlnode.getElementsByTagName('target')[0].firstChild) ? {string: xmlnode.getElementsByTagName('target')[0].firstChild.nodeValue} : {null: true}, // detectCode can not exist or be empty (xmlnode.getElementsByTagName('detectCode').item(0) && xmlnode.getElementsByTagName('detectCode')[0].firstChild) ? {string: xmlnode.getElementsByTagName('detectCode')[0].firstChild.nodeValue} : {null: true}, {string: xmlnode.getElementsByTagName('code')[0].firstChild.nodeValue} ]; var sql = "REPLACE INTO translators VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; return Zotero.DB.query(sql, sqlValues); } /** * Traverse an XML style node from the repository and * update the local csl table with the style data **/ function _styleXMLToDB(xmlnode){ // Don't split >4K chunks into multiple nodes // https://bugzilla.mozilla.org/show_bug.cgi?id=194231 xmlnode.normalize(); var uri = xmlnode.getAttribute('id'); // // Workaround for URI change -- delete existing versions with old URIs of updated styles // var re = new RegExp("http://www.zotero.org/styles/(.+)"); var matches = uri.match(re); if (matches) { var zoteroReplacements = ['chicago-author-date', 'chicago-note-bibliography']; var purlReplacements = [ 'apa', 'asa', 'chicago-note', 'ieee', 'mhra_note_without_bibliography', 'mla', 'nature', 'nlm' ]; if (zoteroReplacements.indexOf(matches[1]) != -1) { var sql = "DELETE FROM csl WHERE cslID=?"; Zotero.DB.query(sql, 'http://www.zotero.org/namespaces/CSL/' + matches[1] + '.csl'); } else if (purlReplacements.indexOf(matches[1]) != -1) { var sql = "DELETE FROM csl WHERE cslID=?"; Zotero.DB.query(sql, 'http://purl.org/net/xbiblio/csl/styles/' + matches[1] + '.csl'); } } var uri = xmlnode.getAttribute('id'); // Delete local style if CSL code is empty if (!xmlnode.getElementsByTagName('csl')[0].firstChild) { var sql = "DELETE FROM csl WHERE cslID=?"; Zotero.DB.query(sql, uri); return true; } var sqlValues = [ {string: uri}, {string: xmlnode.getAttribute('updated')}, {string: xmlnode.getElementsByTagName('title')[0].firstChild.nodeValue}, {string: xmlnode.getElementsByTagName('csl')[0].firstChild.nodeValue} ]; var sql = "REPLACE INTO csl VALUES (?,?,?,?)"; return Zotero.DB.query(sql, sqlValues); } /* * Migrate user data schema from an older version, preserving data */ function _migrateUserDataSchema(fromVersion){ var toVersion = _getSchemaSQLVersion('userdata'); if (fromVersion==toVersion){ return false; } if (fromVersion > toVersion){ throw("Zotero user data DB version is newer than SQL file"); } Zotero.debug('Updating user data tables from version ' + fromVersion + ' to ' + toVersion); var ZU = new Zotero.Utilities; Zotero.DB.beginTransaction(); try { // Step through version changes until we reach the current version // // Each block performs the changes necessary to move from the // previous revision to that one. for (var i=fromVersion + 1; i<=toVersion; i++){ if (i==1){ Zotero.DB.query("DELETE FROM version WHERE schema='schema'"); } if (i==5){ Zotero.DB.query("REPLACE INTO itemData SELECT itemID, 1, originalPath FROM itemAttachments WHERE linkMode=1"); Zotero.DB.query("REPLACE INTO itemData SELECT itemID, 1, path FROM itemAttachments WHERE linkMode=3"); Zotero.DB.query("REPLACE INTO itemData SELECT itemID, 27, dateAdded FROM items NATURAL JOIN itemAttachments WHERE linkMode IN (1,3)"); Zotero.DB.query("UPDATE itemAttachments SET originalPath=NULL WHERE linkMode=1"); Zotero.DB.query("UPDATE itemAttachments SET path=NULL WHERE linkMode=3"); try { Zotero.DB.query("DELETE FROM fulltextItems WHERE itemID IS NULL"); } catch(e){} } if (i==6){ Zotero.DB.query("CREATE TABLE creatorsTemp (creatorID INT, firstName INT, lastName INT, fieldMode INT)"); Zotero.DB.query("INSERT INTO creatorsTemp SELECT * FROM creators"); Zotero.DB.query("DROP TABLE creators"); Zotero.DB.query("CREATE TABLE creators (\n creatorID INT,\n firstName INT,\n lastName INT,\n fieldMode INT,\n PRIMARY KEY (creatorID)\n);"); Zotero.DB.query("INSERT INTO creators SELECT * FROM creatorsTemp"); Zotero.DB.query("DROP TABLE creatorsTemp"); } if (i==7){ Zotero.DB.query("DELETE FROM itemData WHERE fieldID=17"); Zotero.DB.query("UPDATE itemData SET fieldID=64 WHERE fieldID=20"); Zotero.DB.query("UPDATE itemData SET fieldID=69 WHERE fieldID=24 AND itemID IN (SELECT itemID FROM items WHERE itemTypeID=7)"); Zotero.DB.query("UPDATE itemData SET fieldID=65 WHERE fieldID=24 AND itemID IN (SELECT itemID FROM items WHERE itemTypeID=8)"); Zotero.DB.query("UPDATE itemData SET fieldID=66 WHERE fieldID=24 AND itemID IN (SELECT itemID FROM items WHERE itemTypeID=9)"); Zotero.DB.query("UPDATE itemData SET fieldID=59 WHERE fieldID=24 AND itemID IN (SELECT itemID FROM items WHERE itemTypeID=12)"); } if (i==8){ Zotero.DB.query("DROP TABLE IF EXISTS translators"); Zotero.DB.query("DROP TABLE IF EXISTS csl"); } // 1.0b2 (1.0.0b2.r1) if (i==9){ var attachments = Zotero.DB.query("SELECT itemID, linkMode, path FROM itemAttachments"); for each(var row in attachments){ var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); try { var refDir = (row.linkMode==Zotero.Attachments.LINK_MODE_LINKED_FILE) ? Zotero.getZoteroDirectory() : Zotero.getStorageDirectory(); file.setRelativeDescriptor(refDir, row.path); Zotero.DB.query("UPDATE itemAttachments SET path=? WHERE itemID=?", [file.persistentDescriptor, row.itemID]); } catch (e){} } } // 1.0.0b2.r2 if (i==10){ var dates = Zotero.DB.query("SELECT itemID, value FROM itemData WHERE fieldID=14"); for each(var row in dates){ if (!Zotero.Date.isMultipart(row.value)){ Zotero.DB.query("UPDATE itemData SET value=? WHERE itemID=? AND fieldID=14", [Zotero.Date.strToMultipart(row.value), row.itemID]); } } } if (i==11){ var attachments = Zotero.DB.query("SELECT itemID, linkMode, path FROM itemAttachments WHERE linkMode IN (0,1)"); for each(var row in attachments){ var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); try { file.persistentDescriptor = row.path; var storageDir = Zotero.getStorageDirectory(); storageDir.QueryInterface(Components.interfaces.nsILocalFile); var path = file.getRelativeDescriptor(storageDir); Zotero.DB.query("UPDATE itemAttachments SET path=? WHERE itemID=?", [path, row.itemID]); } catch (e){} } } if (i==12){ Zotero.DB.query("CREATE TABLE translatorsTemp (translatorID TEXT PRIMARY KEY, lastUpdated DATETIME, inRepository INT, priority INT, translatorType INT, label TEXT, creator TEXT, target TEXT, detectCode TEXT, code TEXT);"); if (Zotero.DB.tableExists('translators')) { Zotero.DB.query("INSERT INTO translatorsTemp SELECT * FROM translators"); Zotero.DB.query("DROP TABLE translators"); } Zotero.DB.query("CREATE TABLE translators (\n translatorID TEXT PRIMARY KEY,\n minVersion TEXT,\n maxVersion TEXT,\n lastUpdated DATETIME,\n inRepository INT,\n priority INT,\n translatorType INT,\n label TEXT,\n creator TEXT,\n target TEXT,\n detectCode TEXT,\n code TEXT\n);"); Zotero.DB.query("INSERT INTO translators SELECT translatorID, '', '', lastUpdated, inRepository, priority, translatorType, label, creator, target, detectCode, code FROM translatorsTemp"); Zotero.DB.query("CREATE INDEX translators_type ON translators(translatorType)"); Zotero.DB.query("DROP TABLE translatorsTemp"); } if (i==13) { Zotero.DB.query("CREATE TABLE itemNotesTemp (itemID INT, sourceItemID INT, note TEXT, PRIMARY KEY (itemID), FOREIGN KEY (itemID) REFERENCES items(itemID), FOREIGN KEY (sourceItemID) REFERENCES items(itemID))"); Zotero.DB.query("INSERT INTO itemNotesTemp SELECT * FROM itemNotes"); Zotero.DB.query("DROP TABLE itemNotes"); Zotero.DB.query("CREATE TABLE itemNotes (\n itemID INT,\n sourceItemID INT,\n note TEXT,\n isAbstract INT DEFAULT NULL,\n PRIMARY KEY (itemID),\n FOREIGN KEY (itemID) REFERENCES items(itemID),\n FOREIGN KEY (sourceItemID) REFERENCES items(itemID)\n);"); Zotero.DB.query("INSERT INTO itemNotes SELECT itemID, sourceItemID, note, NULL FROM itemNotesTemp"); Zotero.DB.query("CREATE INDEX itemNotes_sourceItemID ON itemNotes(sourceItemID)"); Zotero.DB.query("DROP TABLE itemNotesTemp"); } // 1.0.0b3.r1 // Repair for interrupted B4 upgrades if (i==14) { var hash = Zotero.DB.getColumnHash('itemNotes'); if (!hash.isAbstract) { // See if itemDataValues exists if (!Zotero.DB.tableExists('itemDataValues')) { // Copied from step 23 var notes = Zotero.DB.query("SELECT itemID, note FROM itemNotes WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=1)"); if (notes) { var f = function(text) { text = text + ''; var t = text.substring(0, 80); var ln = t.indexOf("\n"); if (ln>-1 && ln<80) { t = t.substring(0, ln); } return t; } for (var j=0; j<notes.length; j++) { Zotero.DB.query("REPLACE INTO itemNoteTitles VALUES (?,?)", [notes[j]['itemID'], f(notes[j]['note'])]); } } Zotero.DB.query("CREATE TABLE itemDataValues (\n valueID INT,\n value,\n PRIMARY KEY (valueID)\n);"); var values = Zotero.DB.columnQuery("SELECT DISTINCT value FROM itemData"); if (values) { for (var j=0; j<values.length; j++) { var valueID = Zotero.ID.get('itemDataValues'); Zotero.DB.query("INSERT INTO itemDataValues VALUES (?,?)", [valueID, values[j]]); } } Zotero.DB.query("CREATE TEMPORARY TABLE itemDataTemp AS SELECT itemID, fieldID, (SELECT valueID FROM itemDataValues WHERE value=ID.value) AS valueID FROM itemData ID"); Zotero.DB.query("DROP TABLE itemData"); Zotero.DB.query("CREATE TABLE itemData (\n itemID INT,\n fieldID INT,\n valueID INT,\n PRIMARY KEY (itemID, fieldID),\n FOREIGN KEY (itemID) REFERENCES items(itemID),\n FOREIGN KEY (fieldID) REFERENCES fields(fieldID)\n FOREIGN KEY (valueID) REFERENCES itemDataValues(valueID)\n);"); Zotero.DB.query("INSERT INTO itemData SELECT * FROM itemDataTemp"); Zotero.DB.query("DROP TABLE itemDataTemp"); i = 23; continue; } var rows = Zotero.DB.query("SELECT * FROM itemData WHERE valueID NOT IN (SELECT valueID FROM itemDataValues)"); if (rows) { for (var j=0; j<rows.length; j++) { for (var j=0; j<values.length; j++) { var valueID = Zotero.ID.get('itemDataValues'); Zotero.DB.query("INSERT INTO itemDataValues VALUES (?,?)", [valueID, values[j]]); Zotero.DB.query("UPDATE itemData SET valueID=? WHERE itemID=? AND fieldID=?", [valueID, rows[j]['itemID'], rows[j]['fieldID']]); } } i = 23; continue; } i = 27; continue; } } if (i==15) { Zotero.DB.query("DROP TABLE IF EXISTS annotations"); } if (i==16) { Zotero.DB.query("CREATE TABLE tagsTemp (tagID INT, tag TEXT, PRIMARY KEY (tagID))"); if (Zotero.DB.tableExists("tags")) { Zotero.DB.query("INSERT INTO tagsTemp SELECT * FROM tags"); Zotero.DB.query("DROP TABLE tags"); } Zotero.DB.query("CREATE TABLE tags (\n tagID INT,\n tag TEXT,\n tagType INT,\n PRIMARY KEY (tagID),\n UNIQUE (tag, tagType)\n);"); Zotero.DB.query("INSERT INTO tags SELECT tagID, tag, 0 FROM tagsTemp"); Zotero.DB.query("DROP TABLE tagsTemp"); // Compensate for csl table drop in step 8 for upgraders from early versions, // in case we do something with it in a later step Zotero.DB.query("CREATE TABLE IF NOT EXISTS csl (\n cslID TEXT PRIMARY KEY,\n updated DATETIME,\n title TEXT,\n csl TEXT\n);"); } if (i==17) { Zotero.DB.query("UPDATE itemData SET fieldID=89 WHERE fieldID=8 AND itemID IN (SELECT itemID FROM items WHERE itemTypeID=7)"); } if (i==19) { Zotero.DB.query("INSERT INTO itemData SELECT sourceItemID, 90, note FROM itemNotes WHERE isAbstract=1"); Zotero.DB.query("DELETE FROM items WHERE itemID IN (SELECT itemID FROM itemNotes WHERE isAbstract=1)"); Zotero.DB.query("DELETE FROM itemData WHERE itemID IN (SELECT itemID FROM itemNotes WHERE isAbstract=1)"); Zotero.DB.query("CREATE TEMPORARY TABLE itemNotesTemp (itemID INT, sourceItemID INT, note TEXT)"); Zotero.DB.query("INSERT INTO itemNotesTemp SELECT itemID, sourceItemID, note FROM itemNotes WHERE isAbstract IS NULL"); Zotero.DB.query("DROP TABLE itemNotes"); Zotero.DB.query("CREATE TABLE itemNotes (\n itemID INT,\n sourceItemID INT,\n note TEXT, \n PRIMARY KEY (itemID),\n FOREIGN KEY (itemID) REFERENCES items(itemID),\n FOREIGN KEY (sourceItemID) REFERENCES items(itemID)\n);"); Zotero.DB.query("INSERT INTO itemNotes SELECT * FROM itemNotesTemp") Zotero.DB.query("DROP TABLE itemNotesTemp"); } if (i==20) { Zotero.DB.query("UPDATE itemData SET fieldID=91 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=13) AND fieldID=12;"); Zotero.DB.query("UPDATE itemData SET fieldID=92 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=15) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=93 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=16) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=94 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=16) AND fieldID=4;"); Zotero.DB.query("UPDATE itemData SET fieldID=95 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=16) AND fieldID=10;"); Zotero.DB.query("UPDATE itemData SET fieldID=96 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=17) AND fieldID=14;"); Zotero.DB.query("UPDATE itemData SET fieldID=97 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=17) AND fieldID=4;"); Zotero.DB.query("UPDATE itemData SET fieldID=98 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=17) AND fieldID=10;"); Zotero.DB.query("UPDATE itemData SET fieldID=99 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=18) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=100 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=20) AND fieldID=14;"); Zotero.DB.query("UPDATE itemData SET fieldID=101 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=20) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=102 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=19) AND fieldID=7;"); Zotero.DB.query("UPDATE itemData SET fieldID=103 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=19) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=104 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=25) AND fieldID=12;"); Zotero.DB.query("UPDATE itemData SET fieldID=105 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=29) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=105 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=30) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=105 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=31) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=107 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=23) AND fieldID=12;"); Zotero.DB.query("INSERT OR IGNORE INTO itemData SELECT itemID, 52, value FROM itemData WHERE fieldID IN (14, 52) AND itemID IN (SELECT itemID FROM items WHERE itemTypeID=19) LIMIT 1"); Zotero.DB.query("DELETE FROM itemData WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=19) AND fieldID=14"); } if (i==21) { Zotero.DB.query("INSERT INTO itemData SELECT itemID, 110, title FROM items WHERE title IS NOT NULL AND itemTypeID NOT IN (1,17,20,21)"); Zotero.DB.query("INSERT INTO itemData SELECT itemID, 111, title FROM items WHERE title IS NOT NULL AND itemTypeID = 17"); Zotero.DB.query("INSERT INTO itemData SELECT itemID, 112, title FROM items WHERE title IS NOT NULL AND itemTypeID = 20"); Zotero.DB.query("INSERT INTO itemData SELECT itemID, 113, title FROM items WHERE title IS NOT NULL AND itemTypeID = 21"); Zotero.DB.query("CREATE TEMPORARY TABLE itemsTemp AS SELECT itemID, itemTypeID, dateAdded, dateModified FROM items"); Zotero.DB.query("DROP TABLE items"); Zotero.DB.query("CREATE TABLE IF NOT EXISTS items (\n itemID INTEGER PRIMARY KEY,\n itemTypeID INT,\n dateAdded DATETIME DEFAULT CURRENT_TIMESTAMP,\n dateModified DATETIME DEFAULT CURRENT_TIMESTAMP\n);"); Zotero.DB.query("INSERT INTO items SELECT * FROM itemsTemp"); Zotero.DB.query("DROP TABLE itemsTemp"); } if (i==22) { if (Zotero.DB.valueQuery("SELECT COUNT(*) FROM items WHERE itemID=0")) { var itemID = Zotero.ID.get('items', true); Zotero.DB.query("UPDATE items SET itemID=? WHERE itemID=?", [itemID, 0]); Zotero.DB.query("UPDATE itemData SET itemID=? WHERE itemID=?", [itemID, 0]); Zotero.DB.query("UPDATE itemNotes SET itemID=? WHERE itemID=?", [itemID, 0]); Zotero.DB.query("UPDATE itemAttachments SET itemID=? WHERE itemID=?", [itemID, 0]); } if (Zotero.DB.valueQuery("SELECT COUNT(*) FROM collections WHERE collectionID=0")) { var collectionID = Zotero.ID.get('collections'); Zotero.DB.query("UPDATE collections SET collectionID=? WHERE collectionID=0", [collectionID]); Zotero.DB.query("UPDATE collectionItems SET collectionID=? WHERE collectionID=0", [collectionID]); } Zotero.DB.query("DELETE FROM tags WHERE tagID=0"); Zotero.DB.query("DELETE FROM itemTags WHERE tagID=0"); Zotero.DB.query("DELETE FROM savedSearches WHERE savedSearchID=0"); } if (i==23) { Zotero.DB.query("CREATE TABLE IF NOT EXISTS itemNoteTitles (\n itemID INT,\n title TEXT,\n PRIMARY KEY (itemID),\n FOREIGN KEY (itemID) REFERENCES itemNotes(itemID)\n);"); var notes = Zotero.DB.query("SELECT itemID, note FROM itemNotes WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=1)"); if (notes) { var f = function(text) { var t = text.substring(0, 80); var ln = t.indexOf("\n"); if (ln>-1 && ln<80) { t = t.substring(0, ln); } return t; } for (var j=0; j<notes.length; j++) { Zotero.DB.query("INSERT INTO itemNoteTitles VALUES (?,?)", [notes[j]['itemID'], f(notes[j]['note'])]); } } Zotero.DB.query("CREATE TABLE IF NOT EXISTS itemDataValues (\n valueID INT,\n value,\n PRIMARY KEY (valueID)\n);"); var values = Zotero.DB.columnQuery("SELECT DISTINCT value FROM itemData"); if (values) { for (var j=0; j<values.length; j++) { var valueID = Zotero.ID.get('itemDataValues'); Zotero.DB.query("INSERT INTO itemDataValues VALUES (?,?)", [valueID, values[j]]); } } Zotero.DB.query("CREATE TEMPORARY TABLE itemDataTemp AS SELECT itemID, fieldID, (SELECT valueID FROM itemDataValues WHERE value=ID.value) AS valueID FROM itemData ID"); Zotero.DB.query("DROP TABLE itemData"); Zotero.DB.query("CREATE TABLE itemData (\n itemID INT,\n fieldID INT,\n valueID INT,\n PRIMARY KEY (itemID, fieldID),\n FOREIGN KEY (itemID) REFERENCES items(itemID),\n FOREIGN KEY (fieldID) REFERENCES fields(fieldID)\n FOREIGN KEY (valueID) REFERENCES itemDataValues(valueID)\n);"); Zotero.DB.query("INSERT INTO itemData SELECT * FROM itemDataTemp"); Zotero.DB.query("DROP TABLE itemDataTemp"); } if (i==24) { var rows = Zotero.DB.query("SELECT * FROM itemData NATURAL JOIN itemDataValues WHERE fieldID IN (52,96,100)"); if (rows) { for (var j=0; j<rows.length; j++) { if (!Zotero.Date.isMultipart(rows[j]['value'])) { var value = Zotero.Date.strToMultipart(rows[j]['value']); var valueID = Zotero.DB.valueQuery("SELECT valueID FROM itemDataValues WHERE value=?", rows[j]['value']); if (!valueID) { var valueID = Zotero.ID.get('itemDataValues'); Zotero.DB.query("INSERT INTO itemDataValues VALUES (?,?)", [valueID, value]); } Zotero.DB.query("UPDATE itemData SET valueID=? WHERE itemID=? AND fieldID=?", [valueID, rows[j]['itemID'], rows[j]['fieldID']]); } } } } if (i==25) { Zotero.DB.query("UPDATE itemData SET fieldID=100 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=15) AND fieldID=14;") } if (i==26) { Zotero.DB.query("INSERT INTO itemData SELECT itemID, 114, valueID FROM itemData WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=33) AND fieldID=84"); } if (i==27) { Zotero.DB.query("UPDATE itemData SET fieldID=115 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=3) AND fieldID=12"); } // 1.0.0b4.r1 if (i==28) { var childNotes = Zotero.DB.query("SELECT * FROM itemNotes WHERE itemID IN (SELECT itemID FROM items) AND sourceItemID IS NOT NULL"); if (!childNotes.length) { continue; } Zotero.DB.query("CREATE TEMPORARY TABLE itemNotesTemp AS SELECT * FROM itemNotes WHERE note IN (SELECT itemID FROM items) AND sourceItemID IS NOT NULL"); Zotero.DB.query("CREATE INDEX tmp_itemNotes_pk ON itemNotesTemp(note, sourceItemID);"); var num = Zotero.DB.valueQuery("SELECT COUNT(*) FROM itemNotesTemp"); if (!num) { continue; } for (var j=0; j<childNotes.length; j++) { var reversed = Zotero.DB.query("SELECT * FROM itemNotesTemp WHERE note=? AND sourceItemID=?", [childNotes[j].itemID, childNotes[j].sourceItemID]); if (!reversed.length) { continue; } var maxLength = 0; for (var k=0; k<reversed.length; k++) { if (reversed[k].itemID.length > maxLength) { maxLength = reversed[k].itemID.length; var maxLengthIndex = k; } } if (maxLengthIndex) { Zotero.DB.query("UPDATE itemNotes SET note=? WHERE itemID=?", [reversed[maxLengthIndex].itemID, childNotes[j].itemID]); var f = function(text) { text = text + ''; var t = text.substring(0, 80); var ln = t.indexOf("\n"); if (ln>-1 && ln<80) { t = t.substring(0, ln); } return t; } Zotero.DB.query("UPDATE itemNoteTitles SET title=? WHERE itemID=?", [f(reversed[maxLengthIndex].itemID), childNotes[j].itemID]); } Zotero.DB.query("DELETE FROM itemNotes WHERE note=? AND sourceItemID=?", [childNotes[j].itemID, childNotes[j].sourceItemID]); } } // 1.0.0b4.r2 if (i==29) { Zotero.DB.query("CREATE TABLE IF NOT EXISTS settings (\n setting TEXT,\n key TEXT,\n value,\n PRIMARY KEY (setting, key)\n);"); } if (i==31) { Zotero.DB.query("UPDATE itemData SET fieldID=14 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=15) AND fieldID=100"); } if (i==32) { Zotero.DB.query("UPDATE itemData SET fieldID=100 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=20) AND fieldID=14;"); } // 1.0.0b4.r3 if (i==33) { var rows = Zotero.DB.query("SELECT * FROM itemNotes WHERE itemID NOT IN (SELECT itemID FROM items)"); if (rows) { var colID = Zotero.ID.get('collections'); Zotero.DB.query("INSERT INTO collections VALUES (?,?,?)", [colID, "[Recovered Notes]", null]); for (var j=0; j<rows.length; j++) { if (rows[j].sourceItemID) { var count = Zotero.DB.valueQuery("SELECT COUNT(*) FROM items WHERE itemID=?", rows[j].sourceItemID); if (count == 0) { Zotero.DB.query("UPDATE itemNotes SET sourceItemID=NULL WHERE itemID=?", rows[j].sourceItemID); } } var parsedID = parseInt(rows[j].itemID); if ((parsedID + '').length != rows[j].itemID) { if (parseInt(rows[j].note) != rows[j].note || (parseInt(rows[j].note) + '').length != rows[j].note.length) { Zotero.DB.query("DELETE FROM itemNotes WHERE itemID=?", rows[j].itemID); continue; } var exists = Zotero.DB.valueQuery("SELECT COUNT(*) FROM itemNotes WHERE itemID=?", rows[j].note); if (exists) { var noteItemID = Zotero.ID.get('items', true); } else { var noteItemID = rows[j].note; } Zotero.DB.query("UPDATE itemNotes SET itemID=?, sourceItemID=NULL, note=? WHERE itemID=? AND sourceItemID=?", [noteItemID, rows[j].itemID, rows[j].itemID, rows[j].sourceItemID]); var f = function(text) { text = text + ''; var t = text.substring(0, 80); var ln = t.indexOf("\n"); if (ln>-1 && ln<80) { t = t.substring(0, ln); } return t; } Zotero.DB.query("REPLACE INTO itemNoteTitles VALUES (?,?)", [noteItemID, f(rows[j].itemID)]); Zotero.DB.query("INSERT OR IGNORE INTO items (itemID, itemTypeID) VALUES (?,?)", [noteItemID, 1]); var max = Zotero.DB.valueQuery("SELECT COUNT(*) FROM collectionItems WHERE collectionID=?", colID); Zotero.DB.query("INSERT OR IGNORE INTO collectionItems VALUES (?,?,?)", [colID, noteItemID, max]); continue; } else if (parsedID != rows[j].itemID) { Zotero.DB.query("DELETE FROM itemNotes WHERE itemID=?", rows[j].itemID); continue; } Zotero.DB.query("INSERT INTO items (itemID, itemTypeID) VALUES (?,?)", [rows[j].itemID, 1]); var max = Zotero.DB.valueQuery("SELECT COUNT(*) FROM collectionItems WHERE collectionID=?", colID); Zotero.DB.query("INSERT INTO collectionItems VALUES (?,?,?)", [colID, rows[j].itemID, max]); } } } // 1.0.0b4.r5 if (i==34) { if (!Zotero.DB.tableExists('annotations')) { Zotero.DB.query("CREATE TABLE annotations (\n annotationID INTEGER PRIMARY KEY,\n itemID INT,\n parent TEXT,\n textNode INT,\n offset INT,\n x INT,\n y INT,\n cols INT,\n rows INT,\n text TEXT,\n collapsed BOOL,\n dateModified DATE,\n FOREIGN KEY (itemID) REFERENCES itemAttachments(itemID)\n)"); Zotero.DB.query("CREATE INDEX annotations_itemID ON annotations(itemID)"); } else { Zotero.DB.query("ALTER TABLE annotations ADD collapsed BOOL"); Zotero.DB.query("ALTER TABLE annotations ADD dateModified DATETIME"); } if (!Zotero.DB.tableExists('highlights')) { Zotero.DB.query("CREATE TABLE highlights (\n highlightID INTEGER PRIMARY KEY,\n itemID INTEGER,\n startParent TEXT,\n startTextNode INT,\n startOffset INT,\n endParent TEXT,\n endTextNode INT,\n endOffset INT,\n dateModified DATE,\n FOREIGN KEY (itemID) REFERENCES itemAttachments(itemID)\n)"); Zotero.DB.query("CREATE INDEX highlights_itemID ON highlights(itemID)"); } else { Zotero.DB.query("ALTER TABLE highlights ADD dateModified DATETIME"); } Zotero.DB.query("UPDATE annotations SET dateModified = DATETIME('now')"); Zotero.DB.query("UPDATE highlights SET dateModified = DATETIME('now')"); } if (i==35) { Zotero.DB.query("ALTER TABLE fulltextItems RENAME TO fulltextItemWords"); Zotero.DB.query("CREATE TABLE fulltextItems (\n itemID INT,\n version INT,\n PRIMARY KEY (itemID),\n FOREIGN KEY (itemID) REFERENCES items(itemID)\n);"); } if (i==36) { Zotero.DB.query("ALTER TABLE fulltextItems ADD indexedPages INT"); Zotero.DB.query("ALTER TABLE fulltextItems ADD totalPages INT"); Zotero.DB.query("ALTER TABLE fulltextItems ADD indexedChars INT"); Zotero.DB.query("ALTER TABLE fulltextItems ADD totalChars INT"); Zotero.DB.query("DELETE FROM version WHERE schema='fulltext'"); } // 1.5 if (i==37) { // Some data cleanup from the pre-FK-trigger days Zotero.DB.query("DELETE FROM annotations WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM collectionItems WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM fulltextItems WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM fulltextItemWords WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM highlights WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemAttachments WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemCreators WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemData WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemNotes WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemNoteTitles WHERE itemID NOT IN (SELECT itemID FROM itemNotes)"); Zotero.DB.query("DELETE FROM itemSeeAlso WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemSeeAlso WHERE linkedItemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemTags WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemTags WHERE tagID NOT IN (SELECT tagID FROM tags)"); Zotero.DB.query("DELETE FROM savedSearchConditions WHERE savedSearchID NOT IN (select savedSearchID FROM savedSearches)"); Zotero.DB.query("DELETE FROM itemData WHERE valueID NOT IN (SELECT valueID FROM itemDataValues)"); Zotero.DB.query("DELETE FROM fulltextItemWords WHERE wordID NOT IN (SELECT wordID FROM fulltextWords)"); Zotero.DB.query("DELETE FROM collectionItems WHERE collectionID NOT IN (SELECT collectionID FROM collections)"); Zotero.DB.query("DELETE FROM itemCreators WHERE creatorID NOT IN (SELECT creatorID FROM creators)"); Zotero.DB.query("DELETE FROM itemTags WHERE tagID NOT IN (SELECT tagID FROM tags)"); Zotero.DB.query("DELETE FROM itemData WHERE fieldID NOT IN (SELECT fieldID FROM fields)"); Zotero.DB.query("DELETE FROM itemData WHERE valueID NOT IN (SELECT valueID FROM itemDataValues)"); Zotero.DB.query("DROP TABLE IF EXISTS userFieldMask"); Zotero.DB.query("DROP TABLE IF EXISTS userItemTypes"); Zotero.DB.query("DROP TABLE IF EXISTS userItemTypeMask"); Zotero.DB.query("DROP TABLE IF EXISTS userFields"); Zotero.DB.query("DROP TABLE IF EXISTS userItemTypeFields"); var wordIDs = Zotero.DB.columnQuery("SELECT GROUP_CONCAT(wordID) AS wordIDs FROM fulltextWords GROUP BY word HAVING COUNT(*)>1"); if (wordIDs.length) { Zotero.DB.query("CREATE TEMPORARY TABLE deleteWordIDs (wordID INTEGER PRIMARY KEY)"); for (var j=0, len=wordIDs.length; j<len; j++) { var ids = wordIDs[j].split(','); for (var k=1; k<ids.length; k++) { Zotero.DB.query("INSERT INTO deleteWordIDs VALUES (?)", ids[k]); } } Zotero.DB.query("DELETE FROM fulltextWords WHERE wordID IN (SELECT wordID FROM deleteWordIDs)"); Zotero.DB.query("DROP TABLE deleteWordIDs"); } Zotero.DB.query("REINDEX"); Zotero.DB.transactionVacuum = true; // Set page cache size to 8MB var pageSize = Zotero.DB.valueQuery("PRAGMA page_size"); var cacheSize = 8192000 / pageSize; Zotero.DB.query("PRAGMA default_cache_size=" + cacheSize); Zotero.DB.query("UPDATE itemAttachments SET sourceItemID=NULL WHERE sourceItemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("UPDATE itemNotes SET sourceItemID=NULL WHERE sourceItemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("CREATE TABLE syncDeleteLog (\n syncObjectTypeID INT NOT NULL,\n objectID INT NOT NULL,\n key TEXT NOT NULL,\n timestamp INT NOT NULL,\n FOREIGN KEY (syncObjectTypeID) REFERENCES syncObjectTypes(syncObjectTypeID)\n);"); Zotero.DB.query("CREATE INDEX syncDeleteLog_timestamp ON syncDeleteLog(timestamp);"); // Note titles Zotero.DB.query("ALTER TABLE itemNotes ADD COLUMN title TEXT"); var notes = Zotero.DB.query("SELECT itemID, title FROM itemNoteTitles"); if (notes) { var statement = Zotero.DB.getStatement("UPDATE itemNotes SET title=? WHERE itemID=?"); for (var j=0, len=notes.length; j<len; j++) { statement.bindUTF8StringParameter(0, notes[j].title); statement.bindInt32Parameter(1, notes[j].itemID); try { statement.execute(); } catch (e) { throw (Zotero.DB.getLastErrorString()); } } statement.reset(); } Zotero.DB.query("DROP TABLE itemNoteTitles"); // Creator data Zotero.DB.query("CREATE TABLE creatorData (\n creatorDataID INTEGER PRIMARY KEY,\n firstName TEXT,\n lastName TEXT,\n shortName TEXT,\n fieldMode INT,\n birthYear INT\n)"); Zotero.DB.query("INSERT INTO creatorData SELECT NULL, firstName, lastName, NULL, fieldMode, NULL FROM creators WHERE creatorID IN (SELECT creatorID FROM itemCreators)"); var creatorsOld = Zotero.DB.query("SELECT * FROM creators"); Zotero.DB.query("DROP TABLE creators"); Zotero.DB.query("CREATE TABLE creators (\n creatorID INTEGER PRIMARY KEY,\n creatorDataID INT,\n dateModified DEFAULT CURRENT_TIMESTAMP NOT NULL,\n key TEXT NOT NULL,\n FOREIGN KEY (creatorDataID) REFERENCES creatorData(creatorDataID)\n);"); var data = Zotero.DB.query("SELECT * FROM creatorData"); if (data) { var oldCreatorIDHash = {}; for (var j=0, len=creatorsOld.length; j<len; j++) { oldCreatorIDHash[ ZU.md5( creatorsOld[j].firstName + '_' + creatorsOld[j].lastName + '_' + creatorsOld[j].fieldMode ) ] = creatorsOld[j].creatorID; } var updatedIDs = {}; var insertStatement = Zotero.DB.getStatement("INSERT INTO creators (creatorID, creatorDataID, key) VALUES (?, ?, ?)"); var updateStatement = Zotero.DB.getStatement("UPDATE itemCreators SET creatorID=? WHERE creatorID=?"); for (var j=0, len=data.length; j<len; j++) { insertStatement.bindInt32Parameter(0, data[j].creatorDataID); insertStatement.bindInt32Parameter(1, data[j].creatorDataID); var key = Zotero.ID.getKey(); insertStatement.bindStringParameter(2, key); var oldCreatorID = oldCreatorIDHash[ ZU.md5( data[j].firstName + '_' + data[j].lastName + '_' + data[j].fieldMode ) ]; if (updatedIDs[oldCreatorID]) { continue; } updatedIDs[oldCreatorID] = true; updateStatement.bindInt32Parameter(0, data[j].creatorDataID); updateStatement.bindInt32Parameter(1, oldCreatorID); try { insertStatement.execute(); updateStatement.execute(); } catch (e) { throw (Zotero.DB.getLastErrorString()); } } insertStatement.reset(); updateStatement.reset(); } Zotero.DB.query("CREATE INDEX creators_creatorDataID ON creators(creatorDataID)"); // Items Zotero.DB.query("ALTER TABLE items ADD COLUMN key TEXT"); var items = Zotero.DB.query("SELECT itemID, itemTypeID, dateAdded FROM items"); var titles = Zotero.DB.query("SELECT itemID, value FROM itemData NATURAL JOIN itemDataValues WHERE fieldID BETWEEN 110 AND 112"); var statement = Zotero.DB.getStatement("UPDATE items SET key=? WHERE itemID=?"); for (var j=0, len=items.length; j<len; j++) { var key = Zotero.ID.getKey(); statement.bindStringParameter(0, key); statement.bindInt32Parameter(1, items[j].itemID); try { statement.execute(); } catch (e) { throw (Zotero.DB.getLastErrorString()); } } statement.reset(); Zotero.DB.query("CREATE UNIQUE INDEX items_key ON items(key)"); // Collections var collections = Zotero.DB.query("SELECT * FROM collections"); Zotero.DB.query("DROP TABLE collections"); Zotero.DB.query("CREATE TABLE collections (\n collectionID INTEGER PRIMARY KEY,\n collectionName TEXT,\n parentCollectionID INT,\n dateModified DEFAULT CURRENT_TIMESTAMP NOT NULL,\n key TEXT NOT NULL UNIQUE,\n FOREIGN KEY (parentCollectionID) REFERENCES collections(collectionID)\n);"); var statement = Zotero.DB.getStatement("INSERT INTO collections (collectionID, collectionName, parentCollectionID, key) VALUES (?,?,?,?)"); for (var j=0, len=collections.length; j<len; j++) { statement.bindInt32Parameter(0, collections[j].collectionID); statement.bindUTF8StringParameter(1, collections[j].collectionName); if (collections[j].parentCollectionID) { statement.bindInt32Parameter(2, collections[j].parentCollectionID); } else { statement.bindNullParameter(2); } var key = Zotero.ID.getKey(); statement.bindStringParameter(3, key); try { statement.execute(); } catch (e) { throw (Zotero.DB.getLastErrorString()); } } statement.reset(); // Saved searches var searches = Zotero.DB.query("SELECT * FROM savedSearches"); Zotero.DB.query("DROP TABLE savedSearches"); Zotero.DB.query("CREATE TABLE savedSearches (\n savedSearchID INTEGER PRIMARY KEY,\n savedSearchName TEXT,\n dateModified DEFAULT CURRENT_TIMESTAMP NOT NULL,\n key TEXT NOT NULL UNIQUE\n);"); var statement = Zotero.DB.getStatement("INSERT INTO savedSearches (savedSearchID, savedSearchName, key) VALUES (?,?,?)"); for (var j=0, len=searches.length; j<len; j++) { statement.bindInt32Parameter(0, searches[j].savedSearchID); statement.bindUTF8StringParameter(1, searches[j].savedSearchName); var key = Zotero.ID.getKey(); statement.bindStringParameter(2, key); try { statement.execute(); } catch (e) { throw (Zotero.DB.getLastErrorString()); } } statement.reset(); // Tags var tags = Zotero.DB.query("SELECT * FROM tags"); Zotero.DB.query("DROP TABLE tags"); Zotero.DB.query("CREATE TABLE tags (\n tagID INTEGER PRIMARY KEY,\n name TEXT,\n type INT,\n dateModified DEFAULT CURRENT_TIMESTAMP NOT NULL,\n key TEXT NOT NULL UNIQUE,\n UNIQUE (name, type)\n)"); var statement = Zotero.DB.getStatement("INSERT INTO tags (tagID, name, type, key) VALUES (?,?,?,?)"); for (var j=0, len=tags.length; j<len; j++) { statement.bindInt32Parameter(0, tags[j].tagID); statement.bindUTF8StringParameter(1, tags[j].tag); statement.bindInt32Parameter(2, tags[j].tagType); var key = Zotero.ID.getKey(); statement.bindStringParameter(3, key); try { statement.execute(); } catch (e) { throw (Zotero.DB.getLastErrorString()); } } statement.reset(); } } _updateDBVersion('userdata', toVersion); Zotero.DB.commitTransaction(); } catch(e){ Zotero.DB.rollbackTransaction(); throw(e); } return true; } }
chrome/content/zotero/xpcom/schema.js
/* ***** BEGIN LICENSE BLOCK ***** Copyright (c) 2006 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://chnm.gmu.edu 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. ***** END LICENSE BLOCK ***** */ Zotero.Schema = new function(){ this.userDataUpgradeRequired = userDataUpgradeRequired; this.showUpgradeWizard = showUpgradeWizard; this.updateSchema = updateSchema; this.updateScrapersRemote = updateScrapersRemote; this.stopRepositoryTimer = stopRepositoryTimer; this.rebuildTranslatorsAndStylesTables = rebuildTranslatorsAndStylesTables; this.rebuildTranslatorsTable = rebuildTranslatorsTable; this.dbInitialized = false; this.upgradeFinished = false; this.goToChangeLog = false; var _dbVersions = []; var _schemaVersions = []; var _repositoryTimer; var _remoteUpdateInProgress = false; var self = this; function userDataUpgradeRequired() { var dbVersion = _getDBVersion('userdata'); var schemaVersion = _getSchemaSQLVersion('userdata'); return dbVersion && (dbVersion < schemaVersion); } function showUpgradeWizard() { var dbVersion = _getDBVersion('userdata'); var schemaVersion = _getSchemaSQLVersion('userdata'); var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getService(Components.interfaces.nsIWindowWatcher); var obj = { Zotero: Zotero, data: { success: false } }; var io = { wrappedJSObject: obj }; var win = ww.openWindow(null, "chrome://zotero/content/upgrade.xul", "zotero-schema-upgrade", "chrome,centerscreen,modal", io); if (obj.data.e) { var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getService(Components.interfaces.nsIWindowWatcher); var data = { msg: obj.data.msg, e: obj.data.e, extraData: "Schema upgrade from " + dbVersion + " to " + schemaVersion }; var io = { wrappedJSObject: { Zotero: Zotero, data: data } }; var win = ww.openWindow(null, "chrome://zotero/content/errorReport.xul", "zotero-error-report", "chrome,centerscreen,modal", io); } return obj.data.success; } /* * Checks if the DB schema exists and is up-to-date, updating if necessary */ function updateSchema(){ var dbVersion = _getDBVersion('userdata'); // 'schema' check is for old (<= 1.0b1) schema system, // 'user' is for pre-1.0b2 'user' table if (!dbVersion && !_getDBVersion('schema') && !_getDBVersion('user')){ Zotero.debug('Database does not exist -- creating\n'); _initializeSchema(); return; } var schemaVersion = _getSchemaSQLVersion('userdata'); try { Zotero.UnresponsiveScriptIndicator.disable(); // If upgrading userdata, make backup of database first if (dbVersion < schemaVersion){ Zotero.DB.backupDatabase(dbVersion); } Zotero.DB.beginTransaction(); try { // Old schema system if (!dbVersion){ // Check for pre-1.0b2 'user' table var user = _getDBVersion('user'); if (user) { dbVersion = user; var sql = "UPDATE version SET schema=? WHERE schema=?"; Zotero.DB.query(sql, ['userdata', 'user']); } else { dbVersion = 0; } } var up1 = _migrateUserDataSchema(dbVersion); var up2 = _updateSchema('system'); var up3 = _updateSchema('triggers'); var up4 = _updateSchema('scrapers'); Zotero.DB.commitTransaction(); } catch(e){ Zotero.debug(e); Zotero.DB.rollbackTransaction(); throw(e); } if (up1) { // Upgrade seems to have been a success -- delete any previous backups var maxPrevious = dbVersion - 1; var file = Zotero.getZoteroDirectory(); // directoryEntries.hasMoreElements() throws an error (possibly // because of the temporary SQLite journal file?), so we just look // for all versions for (var i=maxPrevious; i>=29; i--) { var fileName = 'zotero.sqlite.' + i + '.bak'; file.append(fileName); if (file.exists()) { Zotero.debug('Removing previous backup file ' + fileName); file.remove(null); } file = file.parent; } } if (up2 || up3 || up4) { // Run a manual scraper update if upgraded and pref set if (Zotero.Prefs.get('automaticScraperUpdates')){ this.updateScrapersRemote(2); } } } finally { Zotero.UnresponsiveScriptIndicator.enable(); } return; } /** * Send XMLHTTP request for updated scrapers to the central repository * * _force_ forces a repository query regardless of how long it's been * since the last check **/ function updateScrapersRemote(force, callback) { // Little hack to manually update CSLs from repo on upgrades if (!force && Zotero.Prefs.get('automaticScraperUpdates')) { var syncTargetVersion = 3; // increment this when releasing new version that requires it var syncVersion = _getDBVersion('sync'); if (syncVersion < syncTargetVersion) { force = true; var forceCSLUpdate = true; } } if (!force){ if (_remoteUpdateInProgress) { Zotero.debug("A remote update is already in progress -- not checking repository"); return false; } // Check user preference for automatic updates if (!Zotero.Prefs.get('automaticScraperUpdates')){ Zotero.debug('Automatic scraper updating disabled -- not checking repository', 4); return false; } // Determine the earliest local time that we'd query the repository again var nextCheck = new Date(); nextCheck.setTime((parseInt(_getDBVersion('lastcheck')) + ZOTERO_CONFIG['REPOSITORY_CHECK_INTERVAL']) * 1000); // JS uses ms var now = new Date(); // If enough time hasn't passed, don't update if (now < nextCheck){ Zotero.debug('Not enough time since last update -- not checking repository', 4); // Set the repository timer to the remaining time _setRepositoryTimer(Math.round((nextCheck.getTime() - now.getTime()) / 1000)); return false; } } // If transaction already in progress, delay by ten minutes if (Zotero.DB.transactionInProgress()){ Zotero.debug('Transaction in progress -- delaying repository check', 4) _setRepositoryTimer(600); return false; } // Get the last timestamp we got from the server var lastUpdated = _getDBVersion('repository'); var url = ZOTERO_CONFIG['REPOSITORY_URL'] + '/updated?' + (lastUpdated ? 'last=' + lastUpdated + '&' : '') + 'version=' + Zotero.version; Zotero.debug('Checking repository for updates'); _remoteUpdateInProgress = true; if (force) { if (force == 2) { url += '&m=2'; } else { url += '&m=1'; } // Force updating of all public CSLs if (forceCSLUpdate) { url += '&cslup=' + syncTargetVersion; } } var get = Zotero.Utilities.HTTP.doGet(url, function (xmlhttp) { var updated = _updateScrapersRemoteCallback(xmlhttp, !!force); if (callback) { callback(xmlhttp, updated) } }); // TODO: instead, add an observer to start and stop timer on online state change if (!get){ Zotero.debug('Browser is offline -- skipping check'); _setRepositoryTimer(ZOTERO_CONFIG['REPOSITORY_RETRY_INTERVAL']); } } function stopRepositoryTimer(){ if (_repositoryTimer){ Zotero.debug('Stopping repository check timer'); _repositoryTimer.cancel(); } } function rebuildTranslatorsAndStylesTables(callback) { Zotero.debug("Rebuilding translators and styles tables"); Zotero.DB.beginTransaction(); Zotero.DB.query("DELETE FROM translators"); Zotero.DB.query("DELETE FROM csl"); var sql = "DELETE FROM version WHERE schema IN " + "('scrapers', 'repository', 'lastcheck')"; Zotero.DB.query(sql); _dbVersions['scrapers'] = null; _dbVersions['repository'] = null; _dbVersions['lastcheck'] = null; // Rebuild from scrapers.sql _updateSchema('scrapers'); // Rebuild the translator cache Zotero.debug("Clearing translator cache"); Zotero.Translate.cache = null; Zotero.Translate.init(); Zotero.DB.commitTransaction(); // Run a manual update from repository if pref set if (Zotero.Prefs.get('automaticScraperUpdates')) { this.updateScrapersRemote(2, callback); } } function rebuildTranslatorsTable(callback) { Zotero.debug("Rebuilding translators table"); Zotero.DB.beginTransaction(); Zotero.DB.query("DELETE FROM translators"); var sql = "DELETE FROM version WHERE schema IN " + "('scrapers', 'repository', 'lastcheck')"; Zotero.DB.query(sql); _dbVersions['scrapers'] = null; _dbVersions['repository'] = null; _dbVersions['lastcheck'] = null; // Rebuild from scrapers.sql _updateSchema('scrapers'); // Rebuild the translator cache Zotero.debug("Clearing translator cache"); Zotero.Translate.cache = null; Zotero.Translate.init(); Zotero.DB.commitTransaction(); // Run a manual update from repository if pref set if (Zotero.Prefs.get('automaticScraperUpdates')) { this.updateScrapersRemote(2, callback); } } ///////////////////////////////////////////////////////////////// // // Private methods // ///////////////////////////////////////////////////////////////// /* * Retrieve the DB schema version */ function _getDBVersion(schema){ if (_dbVersions[schema]){ return _dbVersions[schema]; } if (Zotero.DB.tableExists('version')){ var dbVersion = Zotero.DB.valueQuery("SELECT version FROM " + "version WHERE schema='" + schema + "'"); _dbVersions[schema] = dbVersion; return dbVersion; } return false; } /* * Retrieve the version from the top line of the schema SQL file */ function _getSchemaSQLVersion(schema){ if (!schema){ throw ('Schema type not provided to _getSchemaSQLVersion()'); } var schemaFile = schema + '.sql'; if (_schemaVersions[schema]){ return _schemaVersions[schema]; } var file = Components.classes["@mozilla.org/extensions/manager;1"] .getService(Components.interfaces.nsIExtensionManager) .getInstallLocation(ZOTERO_CONFIG['GUID']) .getItemLocation(ZOTERO_CONFIG['GUID']); file.append(schemaFile); // Open an input stream from file var istream = Components.classes["@mozilla.org/network/file-input-stream;1"] .createInstance(Components.interfaces.nsIFileInputStream); istream.init(file, 0x01, 0444, 0); istream.QueryInterface(Components.interfaces.nsILineInputStream); var line = {}; // Fetch the schema version from the first line of the file istream.readLine(line); var schemaVersion = line.value.match(/-- ([0-9]+)/)[1]; istream.close(); _schemaVersions[schema] = schemaVersion; return schemaVersion; } /* * Load in SQL schema * * Returns the contents of an SQL file for feeding into query() */ function _getSchemaSQL(schema){ if (!schema){ throw ('Schema type not provided to _getSchemaSQL()'); } var schemaFile = schema + '.sql'; // We pull the schema from an external file so we only have to process // it when necessary var file = Components.classes["@mozilla.org/extensions/manager;1"] .getService(Components.interfaces.nsIExtensionManager) .getInstallLocation(ZOTERO_CONFIG['GUID']) .getItemLocation(ZOTERO_CONFIG['GUID']); file.append(schemaFile); // Open an input stream from file var istream = Components.classes["@mozilla.org/network/file-input-stream;1"] .createInstance(Components.interfaces.nsIFileInputStream); istream.init(file, 0x01, 0444, 0); istream.QueryInterface(Components.interfaces.nsILineInputStream); var line = {}, sql = '', hasmore; // Skip the first line, which contains the schema version istream.readLine(line); //var schemaVersion = line.value.match(/-- ([0-9]+)/)[1]; do { hasmore = istream.readLine(line); sql += line.value + "\n"; } while(hasmore); istream.close(); return sql; } /* * Determine the SQL statements necessary to drop the tables and indexed * in a given schema file * * NOTE: This is not currently used. * * Returns the SQL statements as a string for feeding into query() */ function _getDropCommands(schema){ if (!schema){ throw ('Schema type not provided to _getSchemaSQL()'); } var schemaFile = schema + '.sql'; // We pull the schema from an external file so we only have to process // it when necessary var file = Components.classes["@mozilla.org/extensions/manager;1"] .getService(Components.interfaces.nsIExtensionManager) .getInstallLocation(ZOTERO_CONFIG['GUID']) .getItemLocation(ZOTERO_CONFIG['GUID']); file.append(schemaFile); // Open an input stream from file var istream = Components.classes["@mozilla.org/network/file-input-stream;1"] .createInstance(Components.interfaces.nsIFileInputStream); istream.init(file, 0x01, 0444, 0); istream.QueryInterface(Components.interfaces.nsILineInputStream); var line = {}, str = '', hasmore; // Skip the first line, which contains the schema version istream.readLine(line); do { hasmore = istream.readLine(line); var matches = line.value.match(/CREATE (TABLE|INDEX) IF NOT EXISTS ([^\s]+)/); if (matches){ str += "DROP " + matches[1] + " IF EXISTS " + matches[2] + ";\n"; } } while(hasmore); istream.close(); return str; } /* * Create new DB schema */ function _initializeSchema(){ Zotero.DB.beginTransaction(); try { // Enable auto-vacuuming Zotero.DB.query("PRAGMA page_size = 4096"); Zotero.DB.query("PRAGMA encoding = 'UTF-8'"); Zotero.DB.query("PRAGMA auto_vacuum = 1"); Zotero.DB.query(_getSchemaSQL('system')); Zotero.DB.query(_getSchemaSQL('userdata')); Zotero.DB.query(_getSchemaSQL('triggers')); Zotero.DB.query(_getSchemaSQL('scrapers')); _updateDBVersion('system', _getSchemaSQLVersion('system')); _updateDBVersion('userdata', _getSchemaSQLVersion('userdata')); _updateDBVersion('triggers', _getSchemaSQLVersion('triggers')); _updateDBVersion('scrapers', _getSchemaSQLVersion('scrapers')); /* TODO: uncomment for release var sql = "INSERT INTO items VALUES(1, 14, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 'AJ4PT6IT')"; Zotero.DB.query(sql); var sql = "INSERT INTO itemAttachments VALUES (1, NULL, 3, 'text/html', 25, NULL, NULL)"; Zotero.DB.query(sql); var sql = "INSERT INTO itemDataValues VALUES (?, ?)"; Zotero.DB.query(sql, [1, "Zotero - " + Zotero.getString('install.quickStartGuide')]); var sql = "INSERT INTO itemData VALUES (1, 110, 1)"; Zotero.DB.query(sql); var sql = "INSERT INTO itemDataValues VALUES (2, 'http://www.zotero.org/documentation/quick_start_guide')"; Zotero.DB.query(sql); var sql = "INSERT INTO itemData VALUES (1, 1, 2)"; Zotero.DB.query(sql); var sql = "INSERT INTO itemDataValues VALUES (3, CURRENT_TIMESTAMP)"; Zotero.DB.query(sql); var sql = "INSERT INTO itemData VALUES (1, 27, 3)"; Zotero.DB.query(sql); var sql = "INSERT INTO itemNotes (itemID, sourceItemID, note) VALUES (1, NULL, ?)"; var msg = Zotero.getString('install.quickStartGuide.message.welcome') + " " + Zotero.getString('install.quickStartGuide.message.clickViewPage') + "\n\n" + Zotero.getString('install.quickStartGuide.message.thanks'); Zotero.DB.query(sql, msg); */ Zotero.DB.commitTransaction(); self.dbInitialized = true; } catch(e){ Zotero.debug(e, 1); Components.utils.reportError(e); Zotero.DB.rollbackTransaction(); alert('Error initializing Zotero database'); throw(e); } } /* * Update a DB schema version tag in an existing database */ function _updateDBVersion(schema, version){ _dbVersions[schema] = version; var sql = "REPLACE INTO version (schema,version) VALUES (?,?)"; return Zotero.DB.query(sql, [{'string':schema},{'int':version}]); } function _updateSchema(schema){ var dbVersion = _getDBVersion(schema); var schemaVersion = _getSchemaSQLVersion(schema); if (dbVersion == schemaVersion){ return false; } else if (dbVersion < schemaVersion){ Zotero.DB.beginTransaction(); try { Zotero.DB.query(_getSchemaSQL(schema)); _updateDBVersion(schema, schemaVersion); Zotero.DB.commitTransaction(); } catch (e){ Zotero.debug(e, 1); Zotero.DB.rollbackTransaction(); throw(e); } return true; } throw("Zotero '" + schema + "' DB version is newer than SQL file"); } /** * Process the response from the repository **/ function _updateScrapersRemoteCallback(xmlhttp, manual){ if (!xmlhttp.responseXML){ try { if (xmlhttp.status>1000){ Zotero.debug('No network connection', 2); } else { Zotero.debug('Invalid response from repository', 2); } } catch (e){ Zotero.debug('Repository cannot be contacted'); } if (!manual){ _setRepositoryTimer(ZOTERO_CONFIG['REPOSITORY_RETRY_INTERVAL']); } _remoteUpdateInProgress = false; return false; } var currentTime = xmlhttp.responseXML. getElementsByTagName('currentTime')[0].firstChild.nodeValue; var translatorUpdates = xmlhttp.responseXML.getElementsByTagName('translator'); var styleUpdates = xmlhttp.responseXML.getElementsByTagName('style'); Zotero.DB.beginTransaction(); try { var re = /cslup=([0-9]+)/; var matches = re.exec(xmlhttp.channel.URI.spec); if (matches) { _updateDBVersion('sync', matches[1]); } } catch (e) { Zotero.debug(e); } // Store the timestamp provided by the server _updateDBVersion('repository', currentTime); if (!manual){ // And the local timestamp of the update time var d = new Date(); _updateDBVersion('lastcheck', Math.round(d.getTime()/1000)); // JS uses ms } if (!translatorUpdates.length && !styleUpdates.length){ Zotero.debug('All translators and styles are up-to-date'); Zotero.DB.commitTransaction(); if (!manual){ _setRepositoryTimer(ZOTERO_CONFIG['REPOSITORY_CHECK_INTERVAL']); } _remoteUpdateInProgress = false; return -1; } try { for (var i=0, len=translatorUpdates.length; i<len; i++){ _translatorXMLToDB(translatorUpdates[i]); } for (var i=0, len=styleUpdates.length; i<len; i++){ _styleXMLToDB(styleUpdates[i]); } // Rebuild the translator cache Zotero.debug("Clearing translator cache"); Zotero.Translate.cache = null; Zotero.Translate.init(); } catch (e) { Zotero.debug(e, 1); Zotero.DB.rollbackTransaction(); if (!manual){ _setRepositoryTimer(ZOTERO_CONFIG['REPOSITORY_RETRY_INTERVAL']); } _remoteUpdateInProgress = false; return false; } Zotero.DB.commitTransaction(); if (!manual){ _setRepositoryTimer(ZOTERO_CONFIG['REPOSITORY_CHECK_INTERVAL']); } _remoteUpdateInProgress = false; return true; } /** * Set the interval between repository queries * * We add an additional two seconds to avoid race conditions **/ function _setRepositoryTimer(interval){ if (!interval){ interval = ZOTERO_CONFIG['REPOSITORY_CHECK_INTERVAL']; } var fudge = 2; // two seconds var displayInterval = interval + fudge; var interval = (interval + fudge) * 1000; // convert to ms if (!_repositoryTimer || _repositoryTimer.delay!=interval){ Zotero.debug('Setting repository check interval to ' + displayInterval + ' seconds'); _repositoryTimer = Components.classes["@mozilla.org/timer;1"]. createInstance(Components.interfaces.nsITimer); _repositoryTimer.initWithCallback({ // implements nsITimerCallback notify: function(timer){ Zotero.Schema.updateScrapersRemote(); } }, interval, Components.interfaces.nsITimer.TYPE_REPEATING_SLACK); } } /** * Traverse an XML translator node from the repository and * update the local scrapers table with the scraper data **/ function _translatorXMLToDB(xmlnode){ // Don't split >4K chunks into multiple nodes // https://bugzilla.mozilla.org/show_bug.cgi?id=194231 xmlnode.normalize(); // Delete local version of remote translators with priority 0 if (xmlnode.getElementsByTagName('priority')[0].firstChild.nodeValue === "0") { var sql = "DELETE FROM translators WHERE translatorID=?"; return Zotero.DB.query(sql, {string: xmlnode.getAttribute('id')}); } var sqlValues = [ {string: xmlnode.getAttribute('id')}, {string: xmlnode.getAttribute('minVersion')}, {string: xmlnode.getAttribute('maxVersion')}, {string: xmlnode.getAttribute('lastUpdated')}, 1, // inRepository {int: xmlnode.getElementsByTagName('priority')[0].firstChild.nodeValue}, {int: xmlnode.getAttribute('type')}, {string: xmlnode.getElementsByTagName('label')[0].firstChild.nodeValue}, {string: xmlnode.getElementsByTagName('creator')[0].firstChild.nodeValue}, // target (xmlnode.getElementsByTagName('target').item(0) && xmlnode.getElementsByTagName('target')[0].firstChild) ? {string: xmlnode.getElementsByTagName('target')[0].firstChild.nodeValue} : {null: true}, // detectCode can not exist or be empty (xmlnode.getElementsByTagName('detectCode').item(0) && xmlnode.getElementsByTagName('detectCode')[0].firstChild) ? {string: xmlnode.getElementsByTagName('detectCode')[0].firstChild.nodeValue} : {null: true}, {string: xmlnode.getElementsByTagName('code')[0].firstChild.nodeValue} ]; var sql = "REPLACE INTO translators VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; return Zotero.DB.query(sql, sqlValues); } /** * Traverse an XML style node from the repository and * update the local csl table with the style data **/ function _styleXMLToDB(xmlnode){ // Don't split >4K chunks into multiple nodes // https://bugzilla.mozilla.org/show_bug.cgi?id=194231 xmlnode.normalize(); var uri = xmlnode.getAttribute('id'); // // Workaround for URI change -- delete existing versions with old URIs of updated styles // var re = new RegExp("http://www.zotero.org/styles/(.+)"); var matches = uri.match(re); if (matches) { var zoteroReplacements = ['chicago-author-date', 'chicago-note-bibliography']; var purlReplacements = [ 'apa', 'asa', 'chicago-note', 'ieee', 'mhra_note_without_bibliography', 'mla', 'nature', 'nlm' ]; if (zoteroReplacements.indexOf(matches[1]) != -1) { var sql = "DELETE FROM csl WHERE cslID=?"; Zotero.DB.query(sql, 'http://www.zotero.org/namespaces/CSL/' + matches[1] + '.csl'); } else if (purlReplacements.indexOf(matches[1]) != -1) { var sql = "DELETE FROM csl WHERE cslID=?"; Zotero.DB.query(sql, 'http://purl.org/net/xbiblio/csl/styles/' + matches[1] + '.csl'); } } var uri = xmlnode.getAttribute('id'); // Delete local style if CSL code is empty if (!xmlnode.getElementsByTagName('csl')[0].firstChild) { var sql = "DELETE FROM csl WHERE cslID=?"; Zotero.DB.query(sql, uri); return true; } var sqlValues = [ {string: uri}, {string: xmlnode.getAttribute('updated')}, {string: xmlnode.getElementsByTagName('title')[0].firstChild.nodeValue}, {string: xmlnode.getElementsByTagName('csl')[0].firstChild.nodeValue} ]; var sql = "REPLACE INTO csl VALUES (?,?,?,?)"; return Zotero.DB.query(sql, sqlValues); } /* * Migrate user data schema from an older version, preserving data */ function _migrateUserDataSchema(fromVersion){ var toVersion = _getSchemaSQLVersion('userdata'); if (fromVersion==toVersion){ return false; } if (fromVersion > toVersion){ throw("Zotero user data DB version is newer than SQL file"); } Zotero.debug('Updating user data tables from version ' + fromVersion + ' to ' + toVersion); var ZU = new Zotero.Utilities; Zotero.DB.beginTransaction(); try { // Step through version changes until we reach the current version // // Each block performs the changes necessary to move from the // previous revision to that one. for (var i=fromVersion + 1; i<=toVersion; i++){ if (i==1){ Zotero.DB.query("DELETE FROM version WHERE schema='schema'"); } if (i==5){ Zotero.DB.query("REPLACE INTO itemData SELECT itemID, 1, originalPath FROM itemAttachments WHERE linkMode=1"); Zotero.DB.query("REPLACE INTO itemData SELECT itemID, 1, path FROM itemAttachments WHERE linkMode=3"); Zotero.DB.query("REPLACE INTO itemData SELECT itemID, 27, dateAdded FROM items NATURAL JOIN itemAttachments WHERE linkMode IN (1,3)"); Zotero.DB.query("UPDATE itemAttachments SET originalPath=NULL WHERE linkMode=1"); Zotero.DB.query("UPDATE itemAttachments SET path=NULL WHERE linkMode=3"); try { Zotero.DB.query("DELETE FROM fulltextItems WHERE itemID IS NULL"); } catch(e){} } if (i==6){ Zotero.DB.query("CREATE TABLE creatorsTemp (creatorID INT, firstName INT, lastName INT, fieldMode INT)"); Zotero.DB.query("INSERT INTO creatorsTemp SELECT * FROM creators"); Zotero.DB.query("DROP TABLE creators"); Zotero.DB.query("CREATE TABLE creators (\n creatorID INT,\n firstName INT,\n lastName INT,\n fieldMode INT,\n PRIMARY KEY (creatorID)\n);"); Zotero.DB.query("INSERT INTO creators SELECT * FROM creatorsTemp"); Zotero.DB.query("DROP TABLE creatorsTemp"); } if (i==7){ Zotero.DB.query("DELETE FROM itemData WHERE fieldID=17"); Zotero.DB.query("UPDATE itemData SET fieldID=64 WHERE fieldID=20"); Zotero.DB.query("UPDATE itemData SET fieldID=69 WHERE fieldID=24 AND itemID IN (SELECT itemID FROM items WHERE itemTypeID=7)"); Zotero.DB.query("UPDATE itemData SET fieldID=65 WHERE fieldID=24 AND itemID IN (SELECT itemID FROM items WHERE itemTypeID=8)"); Zotero.DB.query("UPDATE itemData SET fieldID=66 WHERE fieldID=24 AND itemID IN (SELECT itemID FROM items WHERE itemTypeID=9)"); Zotero.DB.query("UPDATE itemData SET fieldID=59 WHERE fieldID=24 AND itemID IN (SELECT itemID FROM items WHERE itemTypeID=12)"); } if (i==8){ Zotero.DB.query("DROP TABLE IF EXISTS translators"); Zotero.DB.query("DROP TABLE IF EXISTS csl"); } // 1.0b2 (1.0.0b2.r1) if (i==9){ var attachments = Zotero.DB.query("SELECT itemID, linkMode, path FROM itemAttachments"); for each(var row in attachments){ var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); try { var refDir = (row.linkMode==Zotero.Attachments.LINK_MODE_LINKED_FILE) ? Zotero.getZoteroDirectory() : Zotero.getStorageDirectory(); file.setRelativeDescriptor(refDir, row.path); Zotero.DB.query("UPDATE itemAttachments SET path=? WHERE itemID=?", [file.persistentDescriptor, row.itemID]); } catch (e){} } } // 1.0.0b2.r2 if (i==10){ var dates = Zotero.DB.query("SELECT itemID, value FROM itemData WHERE fieldID=14"); for each(var row in dates){ if (!Zotero.Date.isMultipart(row.value)){ Zotero.DB.query("UPDATE itemData SET value=? WHERE itemID=? AND fieldID=14", [Zotero.Date.strToMultipart(row.value), row.itemID]); } } } if (i==11){ var attachments = Zotero.DB.query("SELECT itemID, linkMode, path FROM itemAttachments WHERE linkMode IN (0,1)"); for each(var row in attachments){ var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); try { file.persistentDescriptor = row.path; var storageDir = Zotero.getStorageDirectory(); storageDir.QueryInterface(Components.interfaces.nsILocalFile); var path = file.getRelativeDescriptor(storageDir); Zotero.DB.query("UPDATE itemAttachments SET path=? WHERE itemID=?", [path, row.itemID]); } catch (e){} } } if (i==12){ Zotero.DB.query("CREATE TABLE translatorsTemp (translatorID TEXT PRIMARY KEY, lastUpdated DATETIME, inRepository INT, priority INT, translatorType INT, label TEXT, creator TEXT, target TEXT, detectCode TEXT, code TEXT);"); if (Zotero.DB.tableExists('translators')) { Zotero.DB.query("INSERT INTO translatorsTemp SELECT * FROM translators"); Zotero.DB.query("DROP TABLE translators"); } Zotero.DB.query("CREATE TABLE translators (\n translatorID TEXT PRIMARY KEY,\n minVersion TEXT,\n maxVersion TEXT,\n lastUpdated DATETIME,\n inRepository INT,\n priority INT,\n translatorType INT,\n label TEXT,\n creator TEXT,\n target TEXT,\n detectCode TEXT,\n code TEXT\n);"); Zotero.DB.query("INSERT INTO translators SELECT translatorID, '', '', lastUpdated, inRepository, priority, translatorType, label, creator, target, detectCode, code FROM translatorsTemp"); Zotero.DB.query("CREATE INDEX translators_type ON translators(translatorType)"); Zotero.DB.query("DROP TABLE translatorsTemp"); } if (i==13) { Zotero.DB.query("CREATE TABLE itemNotesTemp (itemID INT, sourceItemID INT, note TEXT, PRIMARY KEY (itemID), FOREIGN KEY (itemID) REFERENCES items(itemID), FOREIGN KEY (sourceItemID) REFERENCES items(itemID))"); Zotero.DB.query("INSERT INTO itemNotesTemp SELECT * FROM itemNotes"); Zotero.DB.query("DROP TABLE itemNotes"); Zotero.DB.query("CREATE TABLE itemNotes (\n itemID INT,\n sourceItemID INT,\n note TEXT,\n isAbstract INT DEFAULT NULL,\n PRIMARY KEY (itemID),\n FOREIGN KEY (itemID) REFERENCES items(itemID),\n FOREIGN KEY (sourceItemID) REFERENCES items(itemID)\n);"); Zotero.DB.query("INSERT INTO itemNotes SELECT itemID, sourceItemID, note, NULL FROM itemNotesTemp"); Zotero.DB.query("CREATE INDEX itemNotes_sourceItemID ON itemNotes(sourceItemID)"); Zotero.DB.query("DROP TABLE itemNotesTemp"); } // 1.0.0b3.r1 // Repair for interrupted B4 upgrades if (i==14) { var hash = Zotero.DB.getColumnHash('itemNotes'); if (!hash.isAbstract) { // See if itemDataValues exists if (!Zotero.DB.tableExists('itemDataValues')) { // Copied from step 23 var notes = Zotero.DB.query("SELECT itemID, note FROM itemNotes WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=1)"); if (notes) { var f = function(text) { text = text + ''; var t = text.substring(0, 80); var ln = t.indexOf("\n"); if (ln>-1 && ln<80) { t = t.substring(0, ln); } return t; } for (var j=0; j<notes.length; j++) { Zotero.DB.query("REPLACE INTO itemNoteTitles VALUES (?,?)", [notes[j]['itemID'], f(notes[j]['note'])]); } } Zotero.DB.query("CREATE TABLE itemDataValues (\n valueID INT,\n value,\n PRIMARY KEY (valueID)\n);"); var values = Zotero.DB.columnQuery("SELECT DISTINCT value FROM itemData"); if (values) { for (var j=0; j<values.length; j++) { var valueID = Zotero.ID.get('itemDataValues'); Zotero.DB.query("INSERT INTO itemDataValues VALUES (?,?)", [valueID, values[j]]); } } Zotero.DB.query("CREATE TEMPORARY TABLE itemDataTemp AS SELECT itemID, fieldID, (SELECT valueID FROM itemDataValues WHERE value=ID.value) AS valueID FROM itemData ID"); Zotero.DB.query("DROP TABLE itemData"); Zotero.DB.query("CREATE TABLE itemData (\n itemID INT,\n fieldID INT,\n valueID INT,\n PRIMARY KEY (itemID, fieldID),\n FOREIGN KEY (itemID) REFERENCES items(itemID),\n FOREIGN KEY (fieldID) REFERENCES fields(fieldID)\n FOREIGN KEY (valueID) REFERENCES itemDataValues(valueID)\n);"); Zotero.DB.query("INSERT INTO itemData SELECT * FROM itemDataTemp"); Zotero.DB.query("DROP TABLE itemDataTemp"); i = 23; continue; } var rows = Zotero.DB.query("SELECT * FROM itemData WHERE valueID NOT IN (SELECT valueID FROM itemDataValues)"); if (rows) { for (var j=0; j<rows.length; j++) { for (var j=0; j<values.length; j++) { var valueID = Zotero.ID.get('itemDataValues'); Zotero.DB.query("INSERT INTO itemDataValues VALUES (?,?)", [valueID, values[j]]); Zotero.DB.query("UPDATE itemData SET valueID=? WHERE itemID=? AND fieldID=?", [valueID, rows[j]['itemID'], rows[j]['fieldID']]); } } i = 23; continue; } i = 27; continue; } } if (i==15) { Zotero.DB.query("DROP TABLE IF EXISTS annotations"); } if (i==16) { Zotero.DB.query("CREATE TABLE tagsTemp (tagID INT, tag TEXT, PRIMARY KEY (tagID))"); if (Zotero.DB.tableExists("tags")) { Zotero.DB.query("INSERT INTO tagsTemp SELECT * FROM tags"); Zotero.DB.query("DROP TABLE tags"); } Zotero.DB.query("CREATE TABLE tags (\n tagID INT,\n tag TEXT,\n tagType INT,\n PRIMARY KEY (tagID),\n UNIQUE (tag, tagType)\n);"); Zotero.DB.query("INSERT INTO tags SELECT tagID, tag, 0 FROM tagsTemp"); Zotero.DB.query("DROP TABLE tagsTemp"); // Compensate for csl table drop in step 8 for upgraders from early versions, // in case we do something with it in a later step Zotero.DB.query("CREATE TABLE IF NOT EXISTS csl (\n cslID TEXT PRIMARY KEY,\n updated DATETIME,\n title TEXT,\n csl TEXT\n);"); } if (i==17) { Zotero.DB.query("UPDATE itemData SET fieldID=89 WHERE fieldID=8 AND itemID IN (SELECT itemID FROM items WHERE itemTypeID=7)"); } if (i==19) { Zotero.DB.query("INSERT INTO itemData SELECT sourceItemID, 90, note FROM itemNotes WHERE isAbstract=1"); Zotero.DB.query("DELETE FROM items WHERE itemID IN (SELECT itemID FROM itemNotes WHERE isAbstract=1)"); Zotero.DB.query("DELETE FROM itemData WHERE itemID IN (SELECT itemID FROM itemNotes WHERE isAbstract=1)"); Zotero.DB.query("CREATE TEMPORARY TABLE itemNotesTemp (itemID INT, sourceItemID INT, note TEXT)"); Zotero.DB.query("INSERT INTO itemNotesTemp SELECT itemID, sourceItemID, note FROM itemNotes WHERE isAbstract IS NULL"); Zotero.DB.query("DROP TABLE itemNotes"); Zotero.DB.query("CREATE TABLE itemNotes (\n itemID INT,\n sourceItemID INT,\n note TEXT, \n PRIMARY KEY (itemID),\n FOREIGN KEY (itemID) REFERENCES items(itemID),\n FOREIGN KEY (sourceItemID) REFERENCES items(itemID)\n);"); Zotero.DB.query("INSERT INTO itemNotes SELECT * FROM itemNotesTemp") Zotero.DB.query("DROP TABLE itemNotesTemp"); } if (i==20) { Zotero.DB.query("UPDATE itemData SET fieldID=91 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=13) AND fieldID=12;"); Zotero.DB.query("UPDATE itemData SET fieldID=92 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=15) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=93 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=16) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=94 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=16) AND fieldID=4;"); Zotero.DB.query("UPDATE itemData SET fieldID=95 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=16) AND fieldID=10;"); Zotero.DB.query("UPDATE itemData SET fieldID=96 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=17) AND fieldID=14;"); Zotero.DB.query("UPDATE itemData SET fieldID=97 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=17) AND fieldID=4;"); Zotero.DB.query("UPDATE itemData SET fieldID=98 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=17) AND fieldID=10;"); Zotero.DB.query("UPDATE itemData SET fieldID=99 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=18) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=100 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=20) AND fieldID=14;"); Zotero.DB.query("UPDATE itemData SET fieldID=101 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=20) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=102 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=19) AND fieldID=7;"); Zotero.DB.query("UPDATE itemData SET fieldID=103 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=19) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=104 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=25) AND fieldID=12;"); Zotero.DB.query("UPDATE itemData SET fieldID=105 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=29) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=105 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=30) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=105 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=31) AND fieldID=60;"); Zotero.DB.query("UPDATE itemData SET fieldID=107 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=23) AND fieldID=12;"); Zotero.DB.query("INSERT OR IGNORE INTO itemData SELECT itemID, 52, value FROM itemData WHERE fieldID IN (14, 52) AND itemID IN (SELECT itemID FROM items WHERE itemTypeID=19) LIMIT 1"); Zotero.DB.query("DELETE FROM itemData WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=19) AND fieldID=14"); } if (i==21) { Zotero.DB.query("INSERT INTO itemData SELECT itemID, 110, title FROM items WHERE title IS NOT NULL AND itemTypeID NOT IN (1,17,20,21)"); Zotero.DB.query("INSERT INTO itemData SELECT itemID, 111, title FROM items WHERE title IS NOT NULL AND itemTypeID = 17"); Zotero.DB.query("INSERT INTO itemData SELECT itemID, 112, title FROM items WHERE title IS NOT NULL AND itemTypeID = 20"); Zotero.DB.query("INSERT INTO itemData SELECT itemID, 113, title FROM items WHERE title IS NOT NULL AND itemTypeID = 21"); Zotero.DB.query("CREATE TEMPORARY TABLE itemsTemp AS SELECT itemID, itemTypeID, dateAdded, dateModified FROM items"); Zotero.DB.query("DROP TABLE items"); Zotero.DB.query("CREATE TABLE IF NOT EXISTS items (\n itemID INTEGER PRIMARY KEY,\n itemTypeID INT,\n dateAdded DATETIME DEFAULT CURRENT_TIMESTAMP,\n dateModified DATETIME DEFAULT CURRENT_TIMESTAMP\n);"); Zotero.DB.query("INSERT INTO items SELECT * FROM itemsTemp"); Zotero.DB.query("DROP TABLE itemsTemp"); } if (i==22) { if (Zotero.DB.valueQuery("SELECT COUNT(*) FROM items WHERE itemID=0")) { var itemID = Zotero.ID.get('items', true); Zotero.DB.query("UPDATE items SET itemID=? WHERE itemID=?", [itemID, 0]); Zotero.DB.query("UPDATE itemData SET itemID=? WHERE itemID=?", [itemID, 0]); Zotero.DB.query("UPDATE itemNotes SET itemID=? WHERE itemID=?", [itemID, 0]); Zotero.DB.query("UPDATE itemAttachments SET itemID=? WHERE itemID=?", [itemID, 0]); } if (Zotero.DB.valueQuery("SELECT COUNT(*) FROM collections WHERE collectionID=0")) { var collectionID = Zotero.ID.get('collections'); Zotero.DB.query("UPDATE collections SET collectionID=? WHERE collectionID=0", [collectionID]); Zotero.DB.query("UPDATE collectionItems SET collectionID=? WHERE collectionID=0", [collectionID]); } Zotero.DB.query("DELETE FROM tags WHERE tagID=0"); Zotero.DB.query("DELETE FROM itemTags WHERE tagID=0"); Zotero.DB.query("DELETE FROM savedSearches WHERE savedSearchID=0"); } if (i==23) { Zotero.DB.query("CREATE TABLE IF NOT EXISTS itemNoteTitles (\n itemID INT,\n title TEXT,\n PRIMARY KEY (itemID),\n FOREIGN KEY (itemID) REFERENCES itemNotes(itemID)\n);"); var notes = Zotero.DB.query("SELECT itemID, note FROM itemNotes WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=1)"); if (notes) { var f = function(text) { var t = text.substring(0, 80); var ln = t.indexOf("\n"); if (ln>-1 && ln<80) { t = t.substring(0, ln); } return t; } for (var j=0; j<notes.length; j++) { Zotero.DB.query("INSERT INTO itemNoteTitles VALUES (?,?)", [notes[j]['itemID'], f(notes[j]['note'])]); } } Zotero.DB.query("CREATE TABLE IF NOT EXISTS itemDataValues (\n valueID INT,\n value,\n PRIMARY KEY (valueID)\n);"); var values = Zotero.DB.columnQuery("SELECT DISTINCT value FROM itemData"); if (values) { for (var j=0; j<values.length; j++) { var valueID = Zotero.ID.get('itemDataValues'); Zotero.DB.query("INSERT INTO itemDataValues VALUES (?,?)", [valueID, values[j]]); } } Zotero.DB.query("CREATE TEMPORARY TABLE itemDataTemp AS SELECT itemID, fieldID, (SELECT valueID FROM itemDataValues WHERE value=ID.value) AS valueID FROM itemData ID"); Zotero.DB.query("DROP TABLE itemData"); Zotero.DB.query("CREATE TABLE itemData (\n itemID INT,\n fieldID INT,\n valueID INT,\n PRIMARY KEY (itemID, fieldID),\n FOREIGN KEY (itemID) REFERENCES items(itemID),\n FOREIGN KEY (fieldID) REFERENCES fields(fieldID)\n FOREIGN KEY (valueID) REFERENCES itemDataValues(valueID)\n);"); Zotero.DB.query("INSERT INTO itemData SELECT * FROM itemDataTemp"); Zotero.DB.query("DROP TABLE itemDataTemp"); } if (i==24) { var rows = Zotero.DB.query("SELECT * FROM itemData NATURAL JOIN itemDataValues WHERE fieldID IN (52,96,100)"); if (rows) { for (var j=0; j<rows.length; j++) { if (!Zotero.Date.isMultipart(rows[j]['value'])) { var value = Zotero.Date.strToMultipart(rows[j]['value']); var valueID = Zotero.DB.valueQuery("SELECT valueID FROM itemDataValues WHERE value=?", rows[j]['value']); if (!valueID) { var valueID = Zotero.ID.get('itemDataValues'); Zotero.DB.query("INSERT INTO itemDataValues VALUES (?,?)", [valueID, value]); } Zotero.DB.query("UPDATE itemData SET valueID=? WHERE itemID=? AND fieldID=?", [valueID, rows[j]['itemID'], rows[j]['fieldID']]); } } } } if (i==25) { Zotero.DB.query("UPDATE itemData SET fieldID=100 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=15) AND fieldID=14;") } if (i==26) { Zotero.DB.query("INSERT INTO itemData SELECT itemID, 114, valueID FROM itemData WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=33) AND fieldID=84"); } if (i==27) { Zotero.DB.query("UPDATE itemData SET fieldID=115 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=3) AND fieldID=12"); } // 1.0.0b4.r1 if (i==28) { var childNotes = Zotero.DB.query("SELECT * FROM itemNotes WHERE itemID IN (SELECT itemID FROM items) AND sourceItemID IS NOT NULL"); if (!childNotes.length) { continue; } Zotero.DB.query("CREATE TEMPORARY TABLE itemNotesTemp AS SELECT * FROM itemNotes WHERE note IN (SELECT itemID FROM items) AND sourceItemID IS NOT NULL"); Zotero.DB.query("CREATE INDEX tmp_itemNotes_pk ON itemNotesTemp(note, sourceItemID);"); var num = Zotero.DB.valueQuery("SELECT COUNT(*) FROM itemNotesTemp"); if (!num) { continue; } for (var j=0; j<childNotes.length; j++) { var reversed = Zotero.DB.query("SELECT * FROM itemNotesTemp WHERE note=? AND sourceItemID=?", [childNotes[j].itemID, childNotes[j].sourceItemID]); if (!reversed.length) { continue; } var maxLength = 0; for (var k=0; k<reversed.length; k++) { if (reversed[k].itemID.length > maxLength) { maxLength = reversed[k].itemID.length; var maxLengthIndex = k; } } if (maxLengthIndex) { Zotero.DB.query("UPDATE itemNotes SET note=? WHERE itemID=?", [reversed[maxLengthIndex].itemID, childNotes[j].itemID]); var f = function(text) { text = text + ''; var t = text.substring(0, 80); var ln = t.indexOf("\n"); if (ln>-1 && ln<80) { t = t.substring(0, ln); } return t; } Zotero.DB.query("UPDATE itemNoteTitles SET title=? WHERE itemID=?", [f(reversed[maxLengthIndex].itemID), childNotes[j].itemID]); } Zotero.DB.query("DELETE FROM itemNotes WHERE note=? AND sourceItemID=?", [childNotes[j].itemID, childNotes[j].sourceItemID]); } } // 1.0.0b4.r2 if (i==29) { Zotero.DB.query("CREATE TABLE IF NOT EXISTS settings (\n setting TEXT,\n key TEXT,\n value,\n PRIMARY KEY (setting, key)\n);"); } if (i==31) { Zotero.DB.query("UPDATE itemData SET fieldID=14 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=15) AND fieldID=100"); } if (i==32) { Zotero.DB.query("UPDATE itemData SET fieldID=100 WHERE itemID IN (SELECT itemID FROM items WHERE itemTypeID=20) AND fieldID=14;"); } // 1.0.0b4.r3 if (i==33) { var rows = Zotero.DB.query("SELECT * FROM itemNotes WHERE itemID NOT IN (SELECT itemID FROM items)"); if (rows) { var colID = Zotero.ID.get('collections'); Zotero.DB.query("INSERT INTO collections VALUES (?,?,?)", [colID, "[Recovered Notes]", null]); for (var j=0; j<rows.length; j++) { if (rows[j].sourceItemID) { var count = Zotero.DB.valueQuery("SELECT COUNT(*) FROM items WHERE itemID=?", rows[j].sourceItemID); if (count == 0) { Zotero.DB.query("UPDATE itemNotes SET sourceItemID=NULL WHERE itemID=?", rows[j].sourceItemID); } } var parsedID = parseInt(rows[j].itemID); if ((parsedID + '').length != rows[j].itemID) { if (parseInt(rows[j].note) != rows[j].note || (parseInt(rows[j].note) + '').length != rows[j].note.length) { Zotero.DB.query("DELETE FROM itemNotes WHERE itemID=?", rows[j].itemID); continue; } var exists = Zotero.DB.valueQuery("SELECT COUNT(*) FROM itemNotes WHERE itemID=?", rows[j].note); if (exists) { var noteItemID = Zotero.ID.get('items', true); } else { var noteItemID = rows[j].note; } Zotero.DB.query("UPDATE itemNotes SET itemID=?, sourceItemID=NULL, note=? WHERE itemID=? AND sourceItemID=?", [noteItemID, rows[j].itemID, rows[j].itemID, rows[j].sourceItemID]); var f = function(text) { text = text + ''; var t = text.substring(0, 80); var ln = t.indexOf("\n"); if (ln>-1 && ln<80) { t = t.substring(0, ln); } return t; } Zotero.DB.query("REPLACE INTO itemNoteTitles VALUES (?,?)", [noteItemID, f(rows[j].itemID)]); Zotero.DB.query("INSERT OR IGNORE INTO items (itemID, itemTypeID) VALUES (?,?)", [noteItemID, 1]); var max = Zotero.DB.valueQuery("SELECT COUNT(*) FROM collectionItems WHERE collectionID=?", colID); Zotero.DB.query("INSERT OR IGNORE INTO collectionItems VALUES (?,?,?)", [colID, noteItemID, max]); continue; } else if (parsedID != rows[j].itemID) { Zotero.DB.query("DELETE FROM itemNotes WHERE itemID=?", rows[j].itemID); continue; } Zotero.DB.query("INSERT INTO items (itemID, itemTypeID) VALUES (?,?)", [rows[j].itemID, 1]); var max = Zotero.DB.valueQuery("SELECT COUNT(*) FROM collectionItems WHERE collectionID=?", colID); Zotero.DB.query("INSERT INTO collectionItems VALUES (?,?,?)", [colID, rows[j].itemID, max]); } } } // 1.0.0b4.r5 if (i==34) { if (!Zotero.DB.tableExists('annotations')) { Zotero.DB.query("CREATE TABLE annotations (\n annotationID INTEGER PRIMARY KEY,\n itemID INT,\n parent TEXT,\n textNode INT,\n offset INT,\n x INT,\n y INT,\n cols INT,\n rows INT,\n text TEXT,\n collapsed BOOL,\n dateModified DATE,\n FOREIGN KEY (itemID) REFERENCES itemAttachments(itemID)\n)"); Zotero.DB.query("CREATE INDEX annotations_itemID ON annotations(itemID)"); } else { Zotero.DB.query("ALTER TABLE annotations ADD collapsed BOOL"); Zotero.DB.query("ALTER TABLE annotations ADD dateModified DATETIME"); } if (!Zotero.DB.tableExists('highlights')) { Zotero.DB.query("CREATE TABLE highlights (\n highlightID INTEGER PRIMARY KEY,\n itemID INTEGER,\n startParent TEXT,\n startTextNode INT,\n startOffset INT,\n endParent TEXT,\n endTextNode INT,\n endOffset INT,\n dateModified DATE,\n FOREIGN KEY (itemID) REFERENCES itemAttachments(itemID)\n)"); Zotero.DB.query("CREATE INDEX highlights_itemID ON highlights(itemID)"); } else { Zotero.DB.query("ALTER TABLE highlights ADD dateModified DATETIME"); } Zotero.DB.query("UPDATE annotations SET dateModified = DATETIME('now')"); Zotero.DB.query("UPDATE highlights SET dateModified = DATETIME('now')"); } if (i==35) { Zotero.DB.query("ALTER TABLE fulltextItems RENAME TO fulltextItemWords"); Zotero.DB.query("CREATE TABLE fulltextItems (\n itemID INT,\n version INT,\n PRIMARY KEY (itemID),\n FOREIGN KEY (itemID) REFERENCES items(itemID)\n);"); } if (i==36) { Zotero.DB.query("ALTER TABLE fulltextItems ADD indexedPages INT"); Zotero.DB.query("ALTER TABLE fulltextItems ADD totalPages INT"); Zotero.DB.query("ALTER TABLE fulltextItems ADD indexedChars INT"); Zotero.DB.query("ALTER TABLE fulltextItems ADD totalChars INT"); Zotero.DB.query("DELETE FROM version WHERE schema='fulltext'"); } // 1.5 if (i==37) { // Some data cleanup from the pre-FK-trigger days Zotero.DB.query("DELETE FROM annotations WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM collectionItems WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM fulltextItems WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM fulltextItemWords WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM highlights WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemAttachments WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemCreators WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemData WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemNotes WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemNoteTitles WHERE itemID NOT IN (SELECT itemID FROM itemNotes)"); Zotero.DB.query("DELETE FROM itemSeeAlso WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemSeeAlso WHERE linkedItemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemTags WHERE itemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("DELETE FROM itemTags WHERE tagID NOT IN (SELECT tagID FROM tags)"); Zotero.DB.query("DELETE FROM savedSearchConditions WHERE savedSearchID NOT IN (select savedSearchID FROM savedSearches)"); Zotero.DB.query("DELETE FROM itemData WHERE valueID NOT IN (SELECT valueID FROM itemDataValues)"); Zotero.DB.query("DELETE FROM fulltextItemWords WHERE wordID NOT IN (SELECT wordID FROM fulltextWords)"); Zotero.DB.query("DELETE FROM collectionItems WHERE collectionID NOT IN (SELECT collectionID FROM collections)"); Zotero.DB.query("DELETE FROM itemCreators WHERE creatorID NOT IN (SELECT creatorID FROM creators)"); Zotero.DB.query("DELETE FROM itemTags WHERE tagID NOT IN (SELECT tagID FROM tags)"); Zotero.DB.query("DELETE FROM itemData WHERE fieldID NOT IN (SELECT fieldID FROM fields)"); Zotero.DB.query("DELETE FROM itemData WHERE valueID NOT IN (SELECT valueID FROM itemDataValues)"); Zotero.DB.query("DROP TABLE IF EXISTS userFieldMask"); Zotero.DB.query("DROP TABLE IF EXISTS userItemTypes"); Zotero.DB.query("DROP TABLE IF EXISTS userItemTypeMask"); Zotero.DB.query("DROP TABLE IF EXISTS userFields"); Zotero.DB.query("DROP TABLE IF EXISTS userItemTypeFields"); var wordIDs = Zotero.DB.columnQuery("SELECT GROUP_CONCAT(wordID) AS wordIDs FROM fulltextWords GROUP BY word HAVING COUNT(*)>1"); if (wordIDs.length) { Zotero.DB.query("CREATE TEMPORARY TABLE deleteWordIDs (wordID INTEGER PRIMARY KEY)"); for (var j=0, len=wordIDs.length; j<len; j++) { var ids = wordIDs[j].split(','); for (var k=1; k<ids.length; k++) { Zotero.DB.query("INSERT INTO deleteWordIDs VALUES (?)", ids[k]); } } Zotero.DB.query("DELETE FROM fulltextWords WHERE wordID IN (SELECT wordID FROM deleteWordIDs)"); Zotero.DB.query("DROP TABLE deleteWordIDs"); } Zotero.DB.query("REINDEX"); Zotero.DB.transactionVacuum = true; // Set page cache size to 8MB var pageSize = Zotero.DB.valueQuery("PRAGMA page_size"); var cacheSize = 8192000 / pageSize; Zotero.DB.query("PRAGMA default_cache_size=" + cacheSize); Zotero.DB.query("UPDATE itemAttachments SET sourceItemID=NULL WHERE sourceItemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("UPDATE itemNotes SET sourceItemID=NULL WHERE sourceItemID NOT IN (SELECT itemID FROM items)"); Zotero.DB.query("CREATE TABLE syncDeleteLog (\n syncObjectTypeID INT NOT NULL,\n objectID INT NOT NULL,\n key TEXT NOT NULL,\n timestamp INT NOT NULL,\n FOREIGN KEY (syncObjectTypeID) REFERENCES syncObjectTypes(syncObjectTypeID)\n);"); Zotero.DB.query("CREATE INDEX syncDeleteLog_timestamp ON syncDeleteLog(timestamp);"); // Note titles Zotero.DB.query("ALTER TABLE itemNotes ADD COLUMN title TEXT"); var notes = Zotero.DB.query("SELECT itemID, title FROM itemNoteTitles"); if (notes) { var statement = Zotero.DB.getStatement("UPDATE itemNotes SET title=? WHERE itemID=?"); for (var j=0, len=notes.length; j<len; j++) { statement.bindUTF8StringParameter(0, notes[j].title); statement.bindInt32Parameter(1, notes[j].itemID); try { statement.execute(); } catch (e) { throw (Zotero.DB.getLastErrorString()); } } statement.reset(); } Zotero.DB.query("DROP TABLE itemNoteTitles"); // Creator data Zotero.DB.query("CREATE TABLE creatorData (\n creatorDataID INTEGER PRIMARY KEY,\n firstName TEXT,\n lastName TEXT,\n shortName TEXT,\n fieldMode INT,\n birthYear INT\n)"); Zotero.DB.query("INSERT INTO creatorData SELECT NULL, firstName, lastName, NULL, fieldMode, NULL FROM creators WHERE creatorID IN (SELECT creatorID FROM itemCreators)"); var creatorsOld = Zotero.DB.query("SELECT * FROM creators"); Zotero.DB.query("DROP TABLE creators"); Zotero.DB.query("CREATE TABLE creators (\n creatorID INTEGER PRIMARY KEY,\n creatorDataID INT,\n dateModified DEFAULT CURRENT_TIMESTAMP NOT NULL,\n key TEXT NOT NULL,\n FOREIGN KEY (creatorDataID) REFERENCES creatorData(creatorDataID)\n);"); var data = Zotero.DB.query("SELECT * FROM creatorData"); if (data) { var oldCreatorIDHash = {}; for (var j=0, len=creatorsOld.length; j<len; j++) { oldCreatorIDHash[ ZU.md5( creatorsOld[j].firstName + '_' + creatorsOld[j].lastName + '_' + creatorsOld[j].fieldMode ) ] = creatorsOld[j].creatorID; } var updatedIDs = {}; var insertStatement = Zotero.DB.getStatement("INSERT INTO creators (creatorID, creatorDataID, key) VALUES (?, ?, ?)"); var updateStatement = Zotero.DB.getStatement("UPDATE itemCreators SET creatorID=? WHERE creatorID=?"); for (var j=0, len=data.length; j<len; j++) { insertStatement.bindInt32Parameter(0, data[j].creatorDataID); insertStatement.bindInt32Parameter(1, data[j].creatorDataID); var key = Zotero.ID.getKey(); insertStatement.bindStringParameter(2, key); var oldCreatorID = oldCreatorIDHash[ ZU.md5( data[j].firstName + '_' + data[j].lastName + '_' + data[j].fieldMode ) ]; if (updatedIDs[oldCreatorID]) { continue; } updatedIDs[oldCreatorID] = true; updateStatement.bindInt32Parameter(0, data[j].creatorDataID); updateStatement.bindInt32Parameter(1, oldCreatorID); try { insertStatement.execute(); updateStatement.execute(); } catch (e) { throw (Zotero.DB.getLastErrorString()); } } insertStatement.reset(); updateStatement.reset(); } Zotero.DB.query("CREATE INDEX creators_creatorDataID ON creators(creatorDataID)"); // Items Zotero.DB.query("ALTER TABLE items ADD COLUMN key TEXT"); var items = Zotero.DB.query("SELECT itemID, itemTypeID, dateAdded FROM items"); var titles = Zotero.DB.query("SELECT itemID, value FROM itemData NATURAL JOIN itemDataValues WHERE fieldID BETWEEN 110 AND 112"); var statement = Zotero.DB.getStatement("UPDATE items SET key=? WHERE itemID=?"); for (var j=0, len=items.length; j<len; j++) { var key = Zotero.ID.getKey(); statement.bindStringParameter(0, key); statement.bindInt32Parameter(1, items[j].itemID); try { statement.execute(); } catch (e) { throw (Zotero.DB.getLastErrorString()); } } statement.reset(); Zotero.DB.query("CREATE UNIQUE INDEX items_key ON items(key)"); // Collections var collections = Zotero.DB.query("SELECT * FROM collections"); Zotero.DB.query("DROP TABLE collections"); Zotero.DB.query("CREATE TABLE collections (\n collectionID INTEGER PRIMARY KEY,\n collectionName TEXT,\n parentCollectionID INT,\n dateModified DEFAULT CURRENT_TIMESTAMP NOT NULL,\n key TEXT NOT NULL UNIQUE,\n FOREIGN KEY (parentCollectionID) REFERENCES collections(collectionID)\n);"); var statement = Zotero.DB.getStatement("INSERT INTO collections (collectionID, collectionName, parentCollectionID, key) VALUES (?,?,?,?)"); for (var j=0, len=collections.length; j<len; j++) { statement.bindInt32Parameter(0, collections[j].collectionID); statement.bindUTF8StringParameter(1, collections[j].collectionName); if (collections[j].parentCollectionID) { statement.bindInt32Parameter(2, collections[j].parentCollectionID); } else { statement.bindNullParameter(2); } var key = Zotero.ID.getKey(); statement.bindStringParameter(3, key); try { statement.execute(); } catch (e) { throw (Zotero.DB.getLastErrorString()); } } statement.reset(); // Saved searches var searches = Zotero.DB.query("SELECT * FROM savedSearches"); Zotero.DB.query("DROP TABLE savedSearches"); Zotero.DB.query("CREATE TABLE savedSearches (\n savedSearchID INTEGER PRIMARY KEY,\n savedSearchName TEXT,\n dateModified DEFAULT CURRENT_TIMESTAMP NOT NULL,\n key TEXT NOT NULL UNIQUE\n);"); var statement = Zotero.DB.getStatement("INSERT INTO savedSearches (savedSearchID, savedSearchName, key) VALUES (?,?,?)"); for (var j=0, len=searches.length; j<len; j++) { statement.bindInt32Parameter(0, searches[j].savedSearchID); statement.bindUTF8StringParameter(1, searches[j].savedSearchName); var key = Zotero.ID.getKey(); statement.bindStringParameter(2, key); try { statement.execute(); } catch (e) { throw (Zotero.DB.getLastErrorString()); } } statement.reset(); // Tags var tags = Zotero.DB.query("SELECT * FROM tags"); Zotero.DB.query("DROP TABLE tags"); Zotero.DB.query("CREATE TABLE tags (\n tagID INTEGER PRIMARY KEY,\n name TEXT,\n type INT,\n dateModified DEFAULT CURRENT_TIMESTAMP NOT NULL,\n key TEXT NOT NULL UNIQUE,\n UNIQUE (name, type)\n)"); var statement = Zotero.DB.getStatement("INSERT INTO tags (tagID, name, type, key) VALUES (?,?,?,?)"); for (var j=0, len=searches.length; j<len; j++) { statement.bindInt32Parameter(0, tags[j].tagID); statement.bindUTF8StringParameter(1, tags[j].tag); statement.bindInt32Parameter(2, tags[j].tagType); var key = Zotero.ID.getKey(); statement.bindStringParameter(3, key); try { statement.execute(); } catch (e) { throw (Zotero.DB.getLastErrorString()); } } statement.reset(); } } _updateDBVersion('userdata', toVersion); Zotero.DB.commitTransaction(); } catch(e){ Zotero.DB.rollbackTransaction(); throw(e); } return true; } }
Don't drop all tags on DB upgrade
chrome/content/zotero/xpcom/schema.js
Don't drop all tags on DB upgrade
<ide><path>hrome/content/zotero/xpcom/schema.js <ide> Zotero.DB.query("DROP TABLE tags"); <ide> Zotero.DB.query("CREATE TABLE tags (\n tagID INTEGER PRIMARY KEY,\n name TEXT,\n type INT,\n dateModified DEFAULT CURRENT_TIMESTAMP NOT NULL,\n key TEXT NOT NULL UNIQUE,\n UNIQUE (name, type)\n)"); <ide> var statement = Zotero.DB.getStatement("INSERT INTO tags (tagID, name, type, key) VALUES (?,?,?,?)"); <del> for (var j=0, len=searches.length; j<len; j++) { <add> for (var j=0, len=tags.length; j<len; j++) { <ide> statement.bindInt32Parameter(0, tags[j].tagID); <ide> statement.bindUTF8StringParameter(1, tags[j].tag); <ide> statement.bindInt32Parameter(2, tags[j].tagType);
Java
mit
65b0e8ef8cd51e7f23ca30a558d6258125b75bc4
0
AlexxEG/Sense-6-Transparent-Recents
package com.gmail.alexellingsen.sense6transparentrecents; import android.app.Activity; import android.content.res.Resources; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.LinearLayout; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; public class Sense6TransparentRecents implements IXposedHookLoadPackage { public static final String PACKAGE = "com.android.systemui"; public static final String TAG = "Sense6TransparentRecents"; @Override public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable { if (!lpparam.packageName.equals(PACKAGE)) return; Class<?> findClass; try { findClass = XposedHelpers.findClass( PACKAGE + ".recent.RecentAppFxActivity", lpparam.classLoader ); } catch (Throwable e) { XposedBridge.log(e); return; } XposedHelpers.findAndHookMethod( findClass, "onCreate", android.os.Bundle.class, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { Activity thiz = (Activity) param.thisObject; // Show status bar thiz.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); // Enable translucent status bar thiz.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // Get status bar height final int statusBarHeight = getStatusBarHeight(thiz.getResources()); View actionBarView; // Get the action bar view try { // Try to get 'actionContainer' field. It will throw an NoSuchFieldError if it doesn't exists, // and if it doesn't try an alternative method. actionBarView = (View) XposedHelpers.getObjectField(thiz, "actionContainer"); } catch (NoSuchFieldError e) { // Find root layout. ID is from decompiling SystemUI.apk LinearLayout rootLayout = (LinearLayout) thiz.findViewById(0x7f070044); // Get first child view actionBarView = rootLayout.getChildAt(0); } // Insert a new View to color the status bar & move action bar down View statusBarColor = new View(actionBarView.getContext()); // Match action bar background, and set minimum height statusBarColor.setBackground(actionBarView.getBackground()); statusBarColor.setMinimumHeight(statusBarHeight); // Insert view before action bar into parent ((ViewGroup) actionBarView.getParent()).addView( statusBarColor, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight) ); // Enable translucent navigation bar thiz.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); // Get 3rd child view to fix bottom padding View background = ((ViewGroup) actionBarView.getParent()).getChildAt(2); // Get navigation bar height int navigationBarHeight = getNavigationBarHeight(thiz.getResources()); // Increase the bottom padding by navigation bar height background.setPadding( background.getPaddingLeft(), background.getPaddingTop(), background.getPaddingRight(), background.getPaddingBottom() + navigationBarHeight ); } }); XposedBridge.log("[" + TAG + "] Hooked recent apps activity"); } public int getNavigationBarHeight(Resources resources) { int result = 0; int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { result = resources.getDimensionPixelSize(resourceId); } return result; } public int getStatusBarHeight(Resources resources) { int result = 0; int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = resources.getDimensionPixelSize(resourceId); } return result; } }
src/com/gmail/alexellingsen/sense6transparentrecents/Sense6TransparentRecents.java
package com.gmail.alexellingsen.sense6transparentrecents; import android.app.Activity; import android.content.res.Resources; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; public class Sense6TransparentRecents implements IXposedHookLoadPackage { public static final String PACKAGE = "com.android.systemui"; public static final String TAG = "Sense6TransparentRecents"; @Override public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable { if (!lpparam.packageName.equals(PACKAGE)) return; Class<?> findClass; try { findClass = XposedHelpers.findClass( PACKAGE + ".recent.RecentAppFxActivity", lpparam.classLoader ); } catch (Throwable e) { XposedBridge.log(e); return; } XposedHelpers.findAndHookMethod( findClass, "onCreate", android.os.Bundle.class, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { Activity thiz = (Activity) param.thisObject; // Show status bar thiz.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); // Enable translucent status bar thiz.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // Get status bar height final int statusBarHeight = getStatusBarHeight(thiz.getResources()); // Get the action bar view final View actionBarView = (View) XposedHelpers.getObjectField(thiz, "actionContainer"); // Insert a new View to color the status bar & move action bar down View statusBarColor = new View(actionBarView.getContext()); // Match action bar background, and set minimum height statusBarColor.setBackground(actionBarView.getBackground()); statusBarColor.setMinimumHeight(statusBarHeight); // Insert view before action bar into parent ((ViewGroup) actionBarView.getParent()).addView( statusBarColor, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight) ); // Enable translucent navigation bar thiz.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); // Get 3rd child view to fix bottom padding View background = ((ViewGroup) actionBarView.getParent()).getChildAt(2); // Get navigation bar height int navigationBarHeight = getNavigationBarHeight(thiz.getResources()); // Increase the bottom padding by navigation bar height background.setPadding( background.getPaddingLeft(), background.getPaddingTop(), background.getPaddingRight(), background.getPaddingBottom() + navigationBarHeight ); } }); XposedBridge.log("[" + TAG + "] Hooked recent apps activity"); } public int getNavigationBarHeight(Resources resources) { int result = 0; int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { result = resources.getDimensionPixelSize(resourceId); } return result; } public int getStatusBarHeight(Resources resources) { int result = 0; int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = resources.getDimensionPixelSize(resourceId); } return result; } }
Add support for newer Sense 6
src/com/gmail/alexellingsen/sense6transparentrecents/Sense6TransparentRecents.java
Add support for newer Sense 6
<ide><path>rc/com/gmail/alexellingsen/sense6transparentrecents/Sense6TransparentRecents.java <ide> import android.view.View; <ide> import android.view.ViewGroup; <ide> import android.view.WindowManager; <add>import android.widget.LinearLayout; <ide> import de.robv.android.xposed.IXposedHookLoadPackage; <ide> import de.robv.android.xposed.XC_MethodHook; <ide> import de.robv.android.xposed.XposedBridge; <ide> // Get status bar height <ide> final int statusBarHeight = getStatusBarHeight(thiz.getResources()); <ide> <add> View actionBarView; <add> <ide> // Get the action bar view <del> final View actionBarView = (View) XposedHelpers.getObjectField(thiz, "actionContainer"); <add> try { <add> // Try to get 'actionContainer' field. It will throw an NoSuchFieldError if it doesn't exists, <add> // and if it doesn't try an alternative method. <add> actionBarView = (View) XposedHelpers.getObjectField(thiz, "actionContainer"); <add> } catch (NoSuchFieldError e) { <add> // Find root layout. ID is from decompiling SystemUI.apk <add> LinearLayout rootLayout = (LinearLayout) thiz.findViewById(0x7f070044); <add> <add> // Get first child view <add> actionBarView = rootLayout.getChildAt(0); <add> } <ide> <ide> // Insert a new View to color the status bar & move action bar down <ide> View statusBarColor = new View(actionBarView.getContext());
Java
apache-2.0
error: pathspec 'console/src/main/java/im/vector/util/VectorUtils.java' did not match any file(s) known to git
f30914e5c5b9f00960b37e73ef7aff52b11ea71e
1
vector-im/riot-android,vector-im/riot-android,vector-im/vector-android,riot-spanish/riot-android,noepitome/neon-android,vt0r/vector-android,vector-im/riot-android,riot-spanish/riot-android,vector-im/riot-android,floviolleau/vector-android,floviolleau/vector-android,noepitome/neon-android,noepitome/neon-android,floviolleau/vector-android,vt0r/vector-android,vector-im/vector-android,riot-spanish/riot-android,vector-im/riot-android,vector-im/vector-android,vt0r/vector-android,riot-spanish/riot-android,vector-im/vector-android,noepitome/neon-android
/* * Copyright 2016 OpenMarket 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 im.vector.util; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.support.v4.util.LruCache; import android.text.TextUtils; import android.widget.ImageView; import java.util.ArrayList; import java.util.Arrays; public class VectorUtils { //============================================================================================================== // Avatars generation //============================================================================================================== // avatars cache static LruCache<String, Bitmap> mAvatarImageByKeyDict = new LruCache<String, Bitmap>(2 * 1024 * 1024); // the avatars background color static ArrayList<Integer> mColorList = new ArrayList<Integer>(Arrays.asList(0xff76cfa6, 0xff50e2c2, 0xfff4c371)); /** * Provides the avatar background color from a text. * @param text the text. * @return the color. */ private static int getAvatarcolor(String text) { long colorIndex = 0; if (!TextUtils.isEmpty(text)) { long sum = 0; for(int i = 0; i < text.length(); i++) { sum += text.charAt(i); } colorIndex = sum % mColorList.size(); } return mColorList.get((int)colorIndex); } /** * Create an avatar bitmap from a text. * @param context the context. * @param text the text to display. * @return the generated bitmap */ private static Bitmap createAvatar(Context context, String text) { android.graphics.Bitmap.Config bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888; // the bitmap size int thumbnailSide = 42; float densityScale = context.getResources().getDisplayMetrics().density; int side = (int)(thumbnailSide * densityScale); Bitmap bitmap = Bitmap.createBitmap(side, side, bitmapConfig); Canvas canvas = new Canvas(bitmap); // prepare the text drawing Paint textPaint = new Paint(); textPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD)); textPaint.setColor(Color.WHITE); textPaint.setTextSize(28 * densityScale); // get its size Rect textBounds = new Rect(); textPaint.getTextBounds(text, 0, text.length(), textBounds); // draw the text in center canvas.drawText(text, (canvas.getWidth() - textBounds.width() - textBounds.left) / 2 , (canvas.getHeight() + textBounds.height() - textBounds.bottom) / 2, textPaint); // Return the avatar return bitmap; } /** * Returns an avatar from a text. * @param context the context. * @param aText the text. * @return the avatar. */ public static Bitmap getAvatar(Context context, String aText) { // ignore some characters if (!TextUtils.isEmpty(aText) && (aText.startsWith("@") || aText.startsWith("#"))) { aText = aText.substring(1); } String firstChar = " "; if (!TextUtils.isEmpty(aText)) { firstChar = aText.substring(0, 1).toUpperCase(); } // check if the avatar is already defined Bitmap thumbnail = mAvatarImageByKeyDict.get(firstChar); if (null == thumbnail) { thumbnail = VectorUtils.createAvatar(context, firstChar); mAvatarImageByKeyDict.put(firstChar, thumbnail); } return thumbnail; } /** * Set the avatar for a text. * @param imageView the imageView to set. * @param text the text. */ public static void setTextAvatar(ImageView imageView, String text) { VectorUtils.setMemberAvatar(imageView, text, text); } /** * Set the avatar for a member. * @param imageView the imageView to set. * @param userId the member userId. * @param displayName the member display name. */ public static void setMemberAvatar(ImageView imageView, String userId, String displayName) { // sanity checks if (null != imageView && !TextUtils.isEmpty(userId)) { imageView.setBackgroundColor(VectorUtils.getAvatarcolor(userId)); imageView.setImageBitmap(VectorUtils.getAvatar(imageView.getContext(), TextUtils.isEmpty(displayName) ? userId : displayName)); } } /** * Set the room avatar. * @param imageView the image view. * @param roomId the room id. * @param displayName the room displayname. */ public static void setRoomVectorAvatar(ImageView imageView, String roomId, String displayName) { VectorUtils.setMemberAvatar(imageView, roomId, displayName); } }
console/src/main/java/im/vector/util/VectorUtils.java
Add VectorUtils : it is a vector toolsbox. -> its first task consists in generating avatars.
console/src/main/java/im/vector/util/VectorUtils.java
Add VectorUtils : it is a vector toolsbox.
<ide><path>onsole/src/main/java/im/vector/util/VectorUtils.java <add>/* <add> * Copyright 2016 OpenMarket Ltd <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package im.vector.util; <add> <add>import android.content.Context; <add>import android.graphics.Bitmap; <add>import android.graphics.Canvas; <add>import android.graphics.Color; <add>import android.graphics.Paint; <add>import android.graphics.Rect; <add>import android.graphics.Typeface; <add>import android.support.v4.util.LruCache; <add>import android.text.TextUtils; <add>import android.widget.ImageView; <add> <add>import java.util.ArrayList; <add>import java.util.Arrays; <add> <add>public class VectorUtils { <add> <add> //============================================================================================================== <add> // Avatars generation <add> //============================================================================================================== <add> <add> // avatars cache <add> static LruCache<String, Bitmap> mAvatarImageByKeyDict = new LruCache<String, Bitmap>(2 * 1024 * 1024); <add> // the avatars background color <add> static ArrayList<Integer> mColorList = new ArrayList<Integer>(Arrays.asList(0xff76cfa6, 0xff50e2c2, 0xfff4c371)); <add> <add> /** <add> * Provides the avatar background color from a text. <add> * @param text the text. <add> * @return the color. <add> */ <add> private static int getAvatarcolor(String text) { <add> long colorIndex = 0; <add> <add> if (!TextUtils.isEmpty(text)) { <add> long sum = 0; <add> <add> for(int i = 0; i < text.length(); i++) { <add> sum += text.charAt(i); <add> } <add> <add> colorIndex = sum % mColorList.size(); <add> } <add> <add> return mColorList.get((int)colorIndex); <add> } <add> <add> /** <add> * Create an avatar bitmap from a text. <add> * @param context the context. <add> * @param text the text to display. <add> * @return the generated bitmap <add> */ <add> private static Bitmap createAvatar(Context context, String text) { <add> android.graphics.Bitmap.Config bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888; <add> <add> // the bitmap size <add> int thumbnailSide = 42; <add> <add> float densityScale = context.getResources().getDisplayMetrics().density; <add> int side = (int)(thumbnailSide * densityScale); <add> <add> Bitmap bitmap = Bitmap.createBitmap(side, side, bitmapConfig); <add> Canvas canvas = new Canvas(bitmap); <add> <add> // prepare the text drawing <add> Paint textPaint = new Paint(); <add> textPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD)); <add> textPaint.setColor(Color.WHITE); <add> textPaint.setTextSize(28 * densityScale); <add> <add> // get its size <add> Rect textBounds = new Rect(); <add> textPaint.getTextBounds(text, 0, text.length(), textBounds); <add> <add> // draw the text in center <add> canvas.drawText(text, (canvas.getWidth() - textBounds.width() - textBounds.left) / 2 , (canvas.getHeight() + textBounds.height() - textBounds.bottom) / 2, textPaint); <add> <add> // Return the avatar <add> return bitmap; <add> } <add> <add> /** <add> * Returns an avatar from a text. <add> * @param context the context. <add> * @param aText the text. <add> * @return the avatar. <add> */ <add> public static Bitmap getAvatar(Context context, String aText) { <add> // ignore some characters <add> if (!TextUtils.isEmpty(aText) && (aText.startsWith("@") || aText.startsWith("#"))) { <add> aText = aText.substring(1); <add> } <add> <add> String firstChar = " "; <add> <add> if (!TextUtils.isEmpty(aText)) { <add> firstChar = aText.substring(0, 1).toUpperCase(); <add> } <add> <add> // check if the avatar is already defined <add> Bitmap thumbnail = mAvatarImageByKeyDict.get(firstChar); <add> <add> if (null == thumbnail) { <add> thumbnail = VectorUtils.createAvatar(context, firstChar); <add> mAvatarImageByKeyDict.put(firstChar, thumbnail); <add> } <add> <add> return thumbnail; <add> } <add> <add> /** <add> * Set the avatar for a text. <add> * @param imageView the imageView to set. <add> * @param text the text. <add> */ <add> public static void setTextAvatar(ImageView imageView, String text) { <add> VectorUtils.setMemberAvatar(imageView, text, text); <add> } <add> <add> /** <add> * Set the avatar for a member. <add> * @param imageView the imageView to set. <add> * @param userId the member userId. <add> * @param displayName the member display name. <add> */ <add> public static void setMemberAvatar(ImageView imageView, String userId, String displayName) { <add> // sanity checks <add> if (null != imageView && !TextUtils.isEmpty(userId)) { <add> imageView.setBackgroundColor(VectorUtils.getAvatarcolor(userId)); <add> imageView.setImageBitmap(VectorUtils.getAvatar(imageView.getContext(), TextUtils.isEmpty(displayName) ? userId : displayName)); <add> } <add> } <add> <add> /** <add> * Set the room avatar. <add> * @param imageView the image view. <add> * @param roomId the room id. <add> * @param displayName the room displayname. <add> */ <add> public static void setRoomVectorAvatar(ImageView imageView, String roomId, String displayName) { <add> VectorUtils.setMemberAvatar(imageView, roomId, displayName); <add> } <add>}
Java
apache-2.0
1f32605da78bb1220ef7cfaaa4950504287441d7
0
opencb/opencga,opencb/opencga,opencb/opencga,opencb/opencga,j-coll/opencga,opencb/opencga,j-coll/opencga,j-coll/opencga,j-coll/opencga,j-coll/opencga,opencb/opencga,j-coll/opencga
package org.opencb.opencga.catalog.stats.solr; import org.apache.commons.lang3.StringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.opencb.commons.datastore.core.Query; import org.opencb.commons.datastore.core.QueryOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; /** * Created by wasim on 09/07/18. */ public class CatalogSolrQueryParser { private static List<String> queryParameters = new ArrayList<>(); protected static Logger logger = LoggerFactory.getLogger(CatalogSolrQueryParser.class); static { // common queryParameters.add("study"); queryParameters.add("type"); queryParameters.add("status"); queryParameters.add("creationDate"); queryParameters.add("release"); queryParameters.add("formart"); queryParameters.add("bioformart"); queryParameters.add("size"); queryParameters.add("samples"); queryParameters.add("sex"); queryParameters.add("ethnicity"); queryParameters.add("population"); queryParameters.add("source"); queryParameters.add("somatic"); } public CatalogSolrQueryParser() { } /** * Create a SolrQuery object from Query and QueryOptions. * * @param query Query * @param queryOptions Query Options * @return SolrQuery */ public SolrQuery parse(Query query, QueryOptions queryOptions) { List<String> filterList = new ArrayList<>(); SolrQuery solrQuery = new SolrQuery(); //------------------------------------- // Facet processing //------------------------------------- // facet fields (query parameter: facet) // multiple faceted fields are separated by ";", they can be: // - non-nested faceted fields, e.g.: biotype // - nested faceted fields (i.e., Solr pivots) are separated by ">>", e.g.: studies>>type // - ranges, field_name:start:end:gap, e.g.: sift:0:1:0.5 // - intersections, field_name:value1^value2[^value3], e.g.: studies:1kG^ESP if (queryOptions.containsKey(QueryOptions.FACET) && StringUtils.isNotEmpty(queryOptions.getString(QueryOptions.FACET))) { parseSolrFacets(queryOptions.get(QueryOptions.FACET).toString(), solrQuery); } // facet ranges, // query parameter name: facetRange // multiple facet ranges are separated by ";" // query parameter value: field:start:end:gap, e.g.: sift:0:1:0.5 if (queryOptions.containsKey(QueryOptions.FACET_RANGE) && StringUtils.isNotEmpty(queryOptions.getString(QueryOptions.FACET_RANGE))) { parseSolrFacetRanges(queryOptions.get(QueryOptions.FACET_RANGE).toString(), solrQuery); } queryParameters.forEach(queryParam -> { if (query.containsKey(queryParam)) { filterList.add(query.getString(queryParam)); } }); logger.debug("query = {}\n", query.toJson()); solrQuery.setQuery("*:*"); filterList.forEach(filter -> { solrQuery.addFilterQuery(filter); logger.debug("Solr fq: {}\n", filter); }); return solrQuery; } /** * Parse facets. * Multiple facets are separated by semicolons (;) * E.g.: chromosome[1,2,3,4,5];studies[1kg,exac]>>type[snv,indel];sift:0:1:0.2;gerp:-1:3:0.5;studies:1kG_phase3^EXAC^ESP6500 * * @param strFields String containing the facet definitions * @param solrQuery Solr query */ public void parseSolrFacets(String strFields, SolrQuery solrQuery) { if (StringUtils.isNotEmpty(strFields) && solrQuery != null) { String[] fields = strFields.split("[;]"); for (String field : fields) { if (field.contains("^")) { // intersections parseSolrFacetIntersections(field, solrQuery); } else if (field.contains(":")) { // ranges parseSolrFacetRanges(field, solrQuery); } else { // fields (simple or nested) parseSolrFacetFields(field, solrQuery); } } } } /** * Parse Solr facet fields. * This format is: field_name[field_values_1,field_values_2...]:skip:limit * * @param field String containing the facet field * @param solrQuery Solr query */ private void parseSolrFacetFields(String field, SolrQuery solrQuery) { String[] splits = field.split(">>"); if (splits.length == 1) { // Solr field //solrQuery.addFacetField(field); parseFacetField(field, solrQuery, false); } else { // Solr pivots (nested fields) StringBuilder sb = new StringBuilder(); for (String split : splits) { String name = parseFacetField(split, solrQuery, true); if (sb.length() > 0) { sb.append(","); } sb.append(name); } solrQuery.addFacetPivotField(sb.toString()); } } /** * Parse field string. * The expected format is: field_name[field_value_1,field_value_2,...]:skip:limit. * * @param field The string to parse * @retrun The field name */ private String parseFacetField(String field, SolrQuery solrQuery, boolean pivot) { String name = ""; String[] splits1 = field.split("[\\[\\]]"); if (splits1.length == 1) { String[] splits2 = field.split(":"); if (splits2.length >= 1) { name = splits2[0]; if (!pivot) { solrQuery.addFacetField(name); } } if (splits2.length >= 2 && StringUtils.isNotEmpty(splits2[1])) { solrQuery.set("f." + name + ".facet.offset", splits2[1]); } if (splits2.length >= 3 && StringUtils.isNotEmpty(splits2[2])) { solrQuery.set("f." + name + ".facet.limit", splits2[2]); } } else { // first, field name name = splits1[0]; if (!pivot) { solrQuery.addFacetField(name); } // second, includes // nothing to do, if includes, the other ones will be removed later // third, skip and limit if (splits1.length >= 3) { String[] splits2 = splits1[2].split(":"); if (splits2.length >= 2 && StringUtils.isNotEmpty(splits2[1])) { solrQuery.set("f." + name + ".facet.offset", splits2[1]); } if (splits2.length >= 3 && StringUtils.isNotEmpty(splits2[2])) { solrQuery.set("f." + name + ".facet.limit", splits2[2]); } } } return name; } /** * Parse Solr facet range. * This format is: field_name:start:end:gap, e.g.: sift:0:1:0.2 * * @param range String containing the facet range definition * @param solrQuery Solr query */ public void parseSolrFacetRanges(String range, SolrQuery solrQuery) { String[] split = range.split(":"); if (split.length != 4) { logger.warn("Facet range '" + range + "' malformed. The expected range format is 'name:start:end:gap'"); } else { try { Number start, end, gap; if (("start").equals(split[0])) { start = Integer.parseInt(split[1]); end = Integer.parseInt(split[2]); gap = Integer.parseInt(split[3]); } else { start = Double.parseDouble(split[1]); end = Double.parseDouble(split[2]); gap = Double.parseDouble(split[3]); } // Solr ranges solrQuery.addNumericRangeFacet(split[0], start, end, gap); } catch (NumberFormatException e) { logger.warn("Facet range '" + range + "' malformed. Range format is 'name:start:end:gap'" + " where start, end and gap values are numbers."); } } } /** * Parse Solr facet intersection. * * @param intersection String containing the facet intersection * @param solrQuery Solr query */ public void parseSolrFacetIntersections(String intersection, SolrQuery solrQuery) { boolean error = true; String[] splitA = intersection.split(":"); if (splitA.length == 2) { String[] splitB = splitA[1].split("\\^"); if (splitB.length == 2) { error = false; solrQuery.addFacetQuery("{!key=" + splitB[0] + "}" + splitA[0] + ":" + splitB[0]); solrQuery.addFacetQuery("{!key=" + splitB[1] + "}" + splitA[0] + ":" + splitB[1]); solrQuery.addFacetQuery("{!key=" + splitB[0] + "__" + splitB[1] + "}" + splitA[0] + ":" + splitB[0] + " AND " + splitA[0] + ":" + splitB[1]); } else if (splitB.length == 3) { error = false; solrQuery.addFacetQuery("{!key=" + splitB[0] + "}" + splitA[0] + ":" + splitB[0]); solrQuery.addFacetQuery("{!key=" + splitB[1] + "}" + splitA[0] + ":" + splitB[1]); solrQuery.addFacetQuery("{!key=" + splitB[2] + "}" + splitA[0] + ":" + splitB[2]); solrQuery.addFacetQuery("{!key=" + splitB[0] + "__" + splitB[1] + "}" + splitA[0] + ":" + splitB[0] + " AND " + splitA[0] + ":" + splitB[1]); solrQuery.addFacetQuery("{!key=" + splitB[0] + "__" + splitB[2] + "}" + splitA[0] + ":" + splitB[0] + " AND " + splitA[0] + ":" + splitB[2]); solrQuery.addFacetQuery("{!key=" + splitB[1] + "__" + splitB[2] + "}" + splitA[0] + ":" + splitB[1] + " AND " + splitA[0] + ":" + splitB[2]); solrQuery.addFacetQuery("{!key=" + splitB[0] + "__" + splitB[1] + "__" + splitB[2] + "}" + splitA[0] + ":" + splitB[0] + " AND " + splitA[0] + ":" + splitB[1] + " AND " + splitA[0] + ":" + splitB[2]); } } if (error) { logger.warn("Facet intersection '" + intersection + "' malformed. The expected intersection format" + " is 'name:value1^value2[^value3]', value3 is optional"); } } }
opencga-catalog/src/main/java/org/opencb/opencga/catalog/stats/solr/CatalogSolrQueryParser.java
package org.opencb.opencga.catalog.stats.solr; import org.apache.commons.lang3.StringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.opencb.commons.datastore.core.Query; import org.opencb.commons.datastore.core.QueryOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; /** * Created by wasim on 09/07/18. */ public class CatalogSolrQueryParser { private static List<String> queryParameters = new ArrayList<>(); protected static Logger logger = LoggerFactory.getLogger(CatalogSolrQueryParser.class); static { // common queryParameters.add("study"); queryParameters.add("type"); queryParameters.add("status"); queryParameters.add("creationDate"); queryParameters.add("release"); queryParameters.add("formart"); queryParameters.add("bioformart"); queryParameters.add("size"); queryParameters.add("samples"); } public CatalogSolrQueryParser() { } /** * Create a SolrQuery object from Query and QueryOptions. * * @param query Query * @param queryOptions Query Options * @return SolrQuery */ public SolrQuery parse(Query query, QueryOptions queryOptions) { List<String> filterList = new ArrayList<>(); SolrQuery solrQuery = new SolrQuery(); //------------------------------------- // Facet processing //------------------------------------- // facet fields (query parameter: facet) // multiple faceted fields are separated by ";", they can be: // - non-nested faceted fields, e.g.: biotype // - nested faceted fields (i.e., Solr pivots) are separated by ">>", e.g.: studies>>type // - ranges, field_name:start:end:gap, e.g.: sift:0:1:0.5 // - intersections, field_name:value1^value2[^value3], e.g.: studies:1kG^ESP if (queryOptions.containsKey(QueryOptions.FACET) && StringUtils.isNotEmpty(queryOptions.getString(QueryOptions.FACET))) { parseSolrFacets(queryOptions.get(QueryOptions.FACET).toString(), solrQuery); } // facet ranges, // query parameter name: facetRange // multiple facet ranges are separated by ";" // query parameter value: field:start:end:gap, e.g.: sift:0:1:0.5 if (queryOptions.containsKey(QueryOptions.FACET_RANGE) && StringUtils.isNotEmpty(queryOptions.getString(QueryOptions.FACET_RANGE))) { parseSolrFacetRanges(queryOptions.get(QueryOptions.FACET_RANGE).toString(), solrQuery); } queryParameters.forEach(queryParam -> { if (query.containsKey(queryParam)) { filterList.add(query.getString(queryParam)); } }); logger.debug("query = {}\n", query.toJson()); solrQuery.setQuery("*:*"); filterList.forEach(filter -> { solrQuery.addFilterQuery(filter); logger.debug("Solr fq: {}\n", filter); }); return solrQuery; } /** * Parse facets. * Multiple facets are separated by semicolons (;) * E.g.: chromosome[1,2,3,4,5];studies[1kg,exac]>>type[snv,indel];sift:0:1:0.2;gerp:-1:3:0.5;studies:1kG_phase3^EXAC^ESP6500 * * @param strFields String containing the facet definitions * @param solrQuery Solr query */ public void parseSolrFacets(String strFields, SolrQuery solrQuery) { if (StringUtils.isNotEmpty(strFields) && solrQuery != null) { String[] fields = strFields.split("[;]"); for (String field : fields) { if (field.contains("^")) { // intersections parseSolrFacetIntersections(field, solrQuery); } else if (field.contains(":")) { // ranges parseSolrFacetRanges(field, solrQuery); } else { // fields (simple or nested) parseSolrFacetFields(field, solrQuery); } } } } /** * Parse Solr facet fields. * This format is: field_name[field_values_1,field_values_2...]:skip:limit * * @param field String containing the facet field * @param solrQuery Solr query */ private void parseSolrFacetFields(String field, SolrQuery solrQuery) { String[] splits = field.split(">>"); if (splits.length == 1) { // Solr field //solrQuery.addFacetField(field); parseFacetField(field, solrQuery, false); } else { // Solr pivots (nested fields) StringBuilder sb = new StringBuilder(); for (String split : splits) { String name = parseFacetField(split, solrQuery, true); if (sb.length() > 0) { sb.append(","); } sb.append(name); } solrQuery.addFacetPivotField(sb.toString()); } } /** * Parse field string. * The expected format is: field_name[field_value_1,field_value_2,...]:skip:limit. * * @param field The string to parse * @retrun The field name */ private String parseFacetField(String field, SolrQuery solrQuery, boolean pivot) { String name = ""; String[] splits1 = field.split("[\\[\\]]"); if (splits1.length == 1) { String[] splits2 = field.split(":"); if (splits2.length >= 1) { name = splits2[0]; if (!pivot) { solrQuery.addFacetField(name); } } if (splits2.length >= 2 && StringUtils.isNotEmpty(splits2[1])) { solrQuery.set("f." + name + ".facet.offset", splits2[1]); } if (splits2.length >= 3 && StringUtils.isNotEmpty(splits2[2])) { solrQuery.set("f." + name + ".facet.limit", splits2[2]); } } else { // first, field name name = splits1[0]; if (!pivot) { solrQuery.addFacetField(name); } // second, includes // nothing to do, if includes, the other ones will be removed later // third, skip and limit if (splits1.length >= 3) { String[] splits2 = splits1[2].split(":"); if (splits2.length >= 2 && StringUtils.isNotEmpty(splits2[1])) { solrQuery.set("f." + name + ".facet.offset", splits2[1]); } if (splits2.length >= 3 && StringUtils.isNotEmpty(splits2[2])) { solrQuery.set("f." + name + ".facet.limit", splits2[2]); } } } return name; } /** * Parse Solr facet range. * This format is: field_name:start:end:gap, e.g.: sift:0:1:0.2 * * @param range String containing the facet range definition * @param solrQuery Solr query */ public void parseSolrFacetRanges(String range, SolrQuery solrQuery) { String[] split = range.split(":"); if (split.length != 4) { logger.warn("Facet range '" + range + "' malformed. The expected range format is 'name:start:end:gap'"); } else { try { Number start, end, gap; if (("start").equals(split[0])) { start = Integer.parseInt(split[1]); end = Integer.parseInt(split[2]); gap = Integer.parseInt(split[3]); } else { start = Double.parseDouble(split[1]); end = Double.parseDouble(split[2]); gap = Double.parseDouble(split[3]); } // Solr ranges solrQuery.addNumericRangeFacet(split[0], start, end, gap); } catch (NumberFormatException e) { logger.warn("Facet range '" + range + "' malformed. Range format is 'name:start:end:gap'" + " where start, end and gap values are numbers."); } } } /** * Parse Solr facet intersection. * * @param intersection String containing the facet intersection * @param solrQuery Solr query */ public void parseSolrFacetIntersections(String intersection, SolrQuery solrQuery) { boolean error = true; String[] splitA = intersection.split(":"); if (splitA.length == 2) { String[] splitB = splitA[1].split("\\^"); if (splitB.length == 2) { error = false; solrQuery.addFacetQuery("{!key=" + splitB[0] + "}" + splitA[0] + ":" + splitB[0]); solrQuery.addFacetQuery("{!key=" + splitB[1] + "}" + splitA[0] + ":" + splitB[1]); solrQuery.addFacetQuery("{!key=" + splitB[0] + "__" + splitB[1] + "}" + splitA[0] + ":" + splitB[0] + " AND " + splitA[0] + ":" + splitB[1]); } else if (splitB.length == 3) { error = false; solrQuery.addFacetQuery("{!key=" + splitB[0] + "}" + splitA[0] + ":" + splitB[0]); solrQuery.addFacetQuery("{!key=" + splitB[1] + "}" + splitA[0] + ":" + splitB[1]); solrQuery.addFacetQuery("{!key=" + splitB[2] + "}" + splitA[0] + ":" + splitB[2]); solrQuery.addFacetQuery("{!key=" + splitB[0] + "__" + splitB[1] + "}" + splitA[0] + ":" + splitB[0] + " AND " + splitA[0] + ":" + splitB[1]); solrQuery.addFacetQuery("{!key=" + splitB[0] + "__" + splitB[2] + "}" + splitA[0] + ":" + splitB[0] + " AND " + splitA[0] + ":" + splitB[2]); solrQuery.addFacetQuery("{!key=" + splitB[1] + "__" + splitB[2] + "}" + splitA[0] + ":" + splitB[1] + " AND " + splitA[0] + ":" + splitB[2]); solrQuery.addFacetQuery("{!key=" + splitB[0] + "__" + splitB[1] + "__" + splitB[2] + "}" + splitA[0] + ":" + splitB[0] + " AND " + splitA[0] + ":" + splitB[1] + " AND " + splitA[0] + ":" + splitB[2]); } } if (error) { logger.warn("Facet intersection '" + intersection + "' malformed. The expected intersection format" + " is 'name:value1^value2[^value3]', value3 is optional"); } } }
Stats: added more filters for Solr Facet Queries
opencga-catalog/src/main/java/org/opencb/opencga/catalog/stats/solr/CatalogSolrQueryParser.java
Stats: added more filters for Solr Facet Queries
<ide><path>pencga-catalog/src/main/java/org/opencb/opencga/catalog/stats/solr/CatalogSolrQueryParser.java <ide> queryParameters.add("bioformart"); <ide> queryParameters.add("size"); <ide> queryParameters.add("samples"); <add> <add> queryParameters.add("sex"); <add> queryParameters.add("ethnicity"); <add> queryParameters.add("population"); <add> queryParameters.add("source"); <add> queryParameters.add("somatic"); <ide> <ide> } <ide>