answer
stringlengths
17
10.2M
package com.fishercoder.solutions; import com.fishercoder.common.classes.TreeNode; /**101. Symmetric Tree Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following [1,2,2,null,3,null,3] is not: 1 / \ 2 2 \ \ 3 3 Note: Bonus points if you could solve it both recursively and iteratively. */ public class _101 { public boolean isSymmetric(TreeNode root) { if (root == null) { return true; } return isSymmetric(root.left, root.right); } private boolean isSymmetric(TreeNode left, TreeNode right) { if (left == null || right == null) { return left == right; } if (left.val != right.val) { return false; } return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left); } }
package ccm.pay2spawn.util; import ccm.pay2spawn.Pay2Spawn; import ccm.pay2spawn.hud.CountDownHudEntry; import ccm.pay2spawn.hud.Hud; import ccm.pay2spawn.misc.Donation; import ccm.pay2spawn.misc.Reward; import ccm.pay2spawn.network.RewardMessage; import com.google.common.base.Strings; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; import java.util.HashSet; import java.util.Iterator; public class ClientTickHandler { public static final ClientTickHandler INSTANCE = new ClientTickHandler(); HashSet<QueEntry> entries = new HashSet<>(); private CountDownHudEntry countDownHudEntry; private int i = 0; private ClientTickHandler() { FMLCommonHandler.instance().bus().register(this); } @SubscribeEvent public void tickEvent(TickEvent.ClientTickEvent event) { if (event.phase != TickEvent.Phase.START) return; if (i++ != 20) return; i = 0; countDownHudEntry.lines.clear(); Iterator<QueEntry> rewardIterator = entries.iterator(); while (rewardIterator.hasNext()) { QueEntry queEntry = rewardIterator.next(); if (queEntry.remaining == 0) { queEntry.send(); rewardIterator.remove(); } else { if (countDownHudEntry.getPosition() != 0 && queEntry.addToHUD) countDownHudEntry.lines.add(countDownHudEntry.getFormat().replace("$name", queEntry.reward.getName()).replace("$time", queEntry.remaining + "")); queEntry.remaining } } if (countDownHudEntry.getPosition() != 0 && !countDownHudEntry.lines.isEmpty()) { if (!Strings.isNullOrEmpty(countDownHudEntry.getHeader())) Helper.addWithEmptyLines(countDownHudEntry.lines, countDownHudEntry.getHeader()); } } public void add(Reward reward, Donation donation, boolean addToHUD, Reward actualReward) { entries.add(new QueEntry(reward, donation, addToHUD, actualReward)); } public void init() { countDownHudEntry = new CountDownHudEntry("countdown", 1, "$name incoming in $time sec.", "-- Countdown --"); Hud.INSTANCE.set.add(countDownHudEntry); } public class QueEntry { int remaining; Donation donation; Reward reward; Reward actualReward; boolean addToHUD; public QueEntry(Reward reward, Donation donation, boolean addToHUD, Reward actualReward) { this.remaining = reward.getCountdown(); this.donation = donation; this.reward = reward; this.addToHUD = addToHUD; this.actualReward = actualReward; } public void send() { Pay2Spawn.getSnw().sendToServer(new RewardMessage(reward, donation, actualReward)); } } }
package com.fishercoder.solutions; /** * 238. Product of Array Except Self * * Given an array of n integers where n > 1, nums, * return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. * Solve it without division and in O(n). * For example, given [1,2,3,4], return [24,12,8,6]. Follow up: Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) */ public class _238 { public static class Solution1 { /** * Very straightforward idea: iterate through the array twice: * first time: get res[i] = res[i-1]*nums[i-1] * second time: have a variable called right, which means all the numbers product to its right, then do * res[i] *= right; * right *= nums[i]; * that's it. * * This could be very well illustrated with this example: [1,2,3,4] */ public int[] productExceptSelf(int[] nums) { int n = nums.length; int[] result = new int[n]; result[0] = 1; for (int i = 1; i < n; i++) { result[i] = result[i - 1] * nums[i - 1]; } int right = 1; for (int i = n - 1; i >= 0; i result[i] *= right; right *= nums[i]; } return result; } } }
package ch.furthermore.demo.st; import java.util.Properties; import com.amazonaws.regions.Regions; public class Configuration { private Properties props = new Properties(); private static Configuration singleton = null; public static interface Keys { public static final String DYNAMO_REGION = "dynamoRegion"; public static final String DYNAMO_DBGEO_ACCESS_KEY = "dynamoDBGeoAccessKey"; public static final String DYNAMO_DBGEO_SECRET_KEY = "dynamoDBGeoSecretKey"; } private Configuration() { props.put( Keys.DYNAMO_REGION, System.getProperty(Keys.DYNAMO_REGION,Regions.US_WEST_2.getName()) ); props.put( Keys.DYNAMO_DBGEO_ACCESS_KEY, System.getProperty(Keys.DYNAMO_DBGEO_ACCESS_KEY,"*************" ) ); props.put( Keys.DYNAMO_DBGEO_SECRET_KEY, System.getProperty(Keys.DYNAMO_DBGEO_SECRET_KEY,"********************" ) ); } public static Configuration instance() { if( singleton == null ) { singleton = new Configuration(); } return singleton; } public String getProperty( String key ) { return props.getProperty( key ); } public String getProperty( String key, String defaultValue ) { return props.getProperty( key, defaultValue ); } }
package com.fishercoder.solutions; public class _278 { public static class Solution1 { public int firstBadVersion(int n) { int left = 1; int right = n; while (left < right) { int mid = left + (right - left) / 2; if (isBadVersion(mid)) { right = mid; } else { left = mid + 1; } } return left; } private boolean isBadVersion(int left) { //this is a fake method to make Eclipse happy return false; } } }
package com.akiban.server; import com.akiban.server.error.PersistitAdapterException; import com.akiban.server.service.tree.TreeService; import com.persistit.Accumulator; import com.persistit.Exchange; import com.persistit.Transaction; import com.persistit.Tree; import com.persistit.exception.PersistitException; import com.persistit.exception.PersistitInterruptedException; public class AccumulatorAdapter { public static long getSnapshot(AccumInfo accumInfo, TreeService treeService, Tree tree) throws PersistitInterruptedException { Accumulator accumulator = getAccumulator(accumInfo, tree); Transaction txn = getCurrentTrx(treeService); return accumulator.getSnapshotValue(txn); } public static long updateAndGet(AccumInfo accumInfo, Exchange exchange, long value) { Accumulator accumulator = getAccumulator(accumInfo, exchange.getTree()); return accumulator.update(value, exchange.getTransaction()); } public static long getLiveValue(AccumInfo accumInfo, TreeService treeService, Tree tree) { Accumulator accumulator = getAccumulator(accumInfo, tree); return accumulator.getLiveValue(); } public long getSnapshot() throws PersistitInterruptedException { return accumulator.getSnapshotValue(getCurrentTrx()); } public long updateAndGet(long value) { return accumulator.update(value, getCurrentTrx()); } public long getLiveValue() { return accumulator.getLiveValue(); } public void set(long value) throws PersistitInterruptedException { set(value, true); } void set(long value, boolean evenIfLess) throws PersistitInterruptedException { long current = getSnapshot(); if(evenIfLess || value > current) { long diff = value - current; this.updateAndGet(diff); } } public AccumulatorAdapter(AccumInfo accumInfo, TreeService treeService, Tree tree) { this.treeService = treeService; this.accumulator = getAccumulator(accumInfo, tree); } private static Accumulator getAccumulator(AccumInfo accumInfo, Tree tree) { try { return tree.getAccumulator(accumInfo.getType(), accumInfo.getIndex()); } catch (PersistitException e) { throw new PersistitAdapterException(e); } } private Transaction getCurrentTrx() { return getCurrentTrx(treeService); } private static Transaction getCurrentTrx(TreeService treeService) { return treeService.getDb().getTransaction(); } private final TreeService treeService; private final Accumulator accumulator; /** * Mapping of indexes and types for the Accumulators used by the table status. * <p> * Note: Remember that <i>any</i> modification to existing values is an * <b>incompatible</b> data format change. It is only safe to stop using * an index position or add new ones at the end of the range. * </p> */ public static enum AccumInfo { ORDINAL(0, Accumulator.Type.SUM), ROW_COUNT(1, Accumulator.Type.SUM), UNIQUE_ID(2, Accumulator.Type.SEQ), AUTO_INC(3, Accumulator.Type.SUM), SEQUENCE(4, Accumulator.Type.SEQ) ; AccumInfo(int index, Accumulator.Type type) { this.index = index; this.type = type; } private int getIndex() { return index; } private Accumulator.Type getType() { return type; } private final int index; private final Accumulator.Type type; } }
package com.fishercoder.solutions; public class _302 { public static class Solution1 { private char[][] image; public int minArea(char[][] iImage, int x, int y) { image = iImage; int m = image.length; int n = image[0].length; int left = searchColumns(0, y, 0, m, true); int right = searchColumns(y + 1, n, 0, m, false); int top = searchRows(0, x, left, right, true); int bottom = searchRows(x + 1, m, left, right, false); return (right - left) * (bottom - top); } private int searchColumns(int i, int j, int top, int bottom, boolean opt) { while (i != j) { int k = top; int mid = (i + j) / 2; while (k < bottom && image[k][mid] == '0') { ++k; } if (k < bottom == opt) { j = mid; } else { i = mid + 1; } } return i; } private int searchRows(int i, int j, int left, int right, boolean opt) { while (i != j) { int k = left; int mid = (i + j) / 2; while (k < right && image[mid][k] == '0') { ++k; } if (k < right == opt) { j = mid; } else { i = mid + 1; } } return i; } } }
package com.akiban.sql.compiler; import com.akiban.sql.parser.*; import com.akiban.sql.StandardException; import com.akiban.sql.types.DataTypeDescriptor; import com.akiban.sql.types.TypeId; import java.util.*; /** Calculate types from schema information. */ public class TypeComputer implements Visitor { public TypeComputer() { } public void compute(StatementNode stmt) throws StandardException { stmt.accept(this); } /** Probably need to subclass and handle <code>NodeTypes.COLUMN_REFERENCE</code> * to get type propagation started. */ protected DataTypeDescriptor computeType(ValueNode node) throws StandardException { switch (node.getNodeType()) { case NodeTypes.RESULT_COLUMN: return resultColumn((ResultColumn)node); case NodeTypes.AND_NODE: case NodeTypes.OR_NODE: case NodeTypes.IS_NODE: return binaryLogicalOperatorNode((BinaryLogicalOperatorNode)node); case NodeTypes.BINARY_PLUS_OPERATOR_NODE: case NodeTypes.BINARY_TIMES_OPERATOR_NODE: case NodeTypes.BINARY_DIVIDE_OPERATOR_NODE: case NodeTypes.BINARY_MINUS_OPERATOR_NODE: return binaryArithmeticOperatorNode((BinaryArithmeticOperatorNode)node); case NodeTypes.BINARY_EQUALS_OPERATOR_NODE: case NodeTypes.BINARY_NOT_EQUALS_OPERATOR_NODE: case NodeTypes.BINARY_GREATER_THAN_OPERATOR_NODE: case NodeTypes.BINARY_GREATER_EQUALS_OPERATOR_NODE: case NodeTypes.BINARY_LESS_THAN_OPERATOR_NODE: case NodeTypes.BINARY_LESS_EQUALS_OPERATOR_NODE: return binaryComparisonOperatorNode((BinaryComparisonOperatorNode)node); case NodeTypes.BETWEEN_OPERATOR_NODE: return betweenOperatorNode((BetweenOperatorNode)node); case NodeTypes.IN_LIST_OPERATOR_NODE: return inListOperatorNode((InListOperatorNode)node); case NodeTypes.SUBQUERY_NODE: return subqueryNode((SubqueryNode)node); case NodeTypes.CONDITIONAL_NODE: return conditionalNode((ConditionalNode)node); case NodeTypes.COALESCE_FUNCTION_NODE: return coalesceFunctionNode((CoalesceFunctionNode)node); case NodeTypes.AGGREGATE_NODE: return aggregateNode((AggregateNode)node); case NodeTypes.CONCATENATION_OPERATOR_NODE: return concatenationOperatorNode((ConcatenationOperatorNode)node); case NodeTypes.IS_NULL_NODE: case NodeTypes.IS_NOT_NULL_NODE: return new DataTypeDescriptor(TypeId.BOOLEAN_ID, false); default: // assert false; return null; } } protected DataTypeDescriptor resultColumn(ResultColumn node) throws StandardException { ValueNode expr = node.getExpression(); if (expr == null) return null; if (expr.isParameterNode() && (expr.getType() == null)) { ColumnReference column = node.getReference(); if (column != null) expr.setType(column.getType()); } return expr.getType(); } protected DataTypeDescriptor binaryLogicalOperatorNode(BinaryLogicalOperatorNode node) throws StandardException { ValueNode leftOperand = node.getLeftOperand(); ValueNode rightOperand = node.getRightOperand(); DataTypeDescriptor leftType = leftOperand.getType(); DataTypeDescriptor rightType = rightOperand.getType(); if ((leftType != null) && !leftType.getTypeId().isBooleanTypeId()) { leftType = new DataTypeDescriptor(TypeId.BOOLEAN_ID, leftType.isNullable()); leftOperand = (ValueNode)node.getNodeFactory() .getNode(NodeTypes.CAST_NODE, leftOperand, leftType, node.getParserContext()); node.setLeftOperand(leftOperand); } if ((rightType != null) && !rightType.getTypeId().isBooleanTypeId()) { rightType = new DataTypeDescriptor(TypeId.BOOLEAN_ID, rightType.isNullable()); rightOperand = (ValueNode)node.getNodeFactory() .getNode(NodeTypes.CAST_NODE, rightOperand, rightType, node.getParserContext()); node.setRightOperand(rightOperand); } if (node.getNodeType() == NodeTypes.IS_NODE) return new DataTypeDescriptor(TypeId.BOOLEAN_ID, false); if (leftType == null) return rightType; else if (rightType == null) return leftType; else return leftType.getNullabilityType(leftType.isNullable() || rightType.isNullable()); } protected DataTypeDescriptor binaryArithmeticOperatorNode(BinaryArithmeticOperatorNode node) throws StandardException { ValueNode leftOperand = node.getLeftOperand(); ValueNode rightOperand = node.getRightOperand(); DataTypeDescriptor leftType = leftOperand.getType(); DataTypeDescriptor rightType = rightOperand.getType(); if (leftOperand.isParameterNode() && (rightType != null)) { leftType = rightType.getNullabilityType(true); leftOperand.setType(leftType); } else if (rightOperand.isParameterNode() && (leftType != null)) { rightType = leftType.getNullabilityType(true); rightOperand.setType(rightType); } TypeId leftTypeId = leftType.getTypeId(); TypeId rightTypeId = rightType.getTypeId(); /* Do any implicit conversions from (long) (var)char. */ if (leftTypeId.isStringTypeId() && rightTypeId.isNumericTypeId()) { boolean nullableResult; nullableResult = leftType.isNullable() || rightType.isNullable(); /* If other side is decimal/numeric, then we need to diddle * with the precision, scale and max width in order to handle * computations like: 1.1 + '0.111' */ int precision = rightType.getPrecision(); int scale = rightType.getScale(); int maxWidth = rightType.getMaximumWidth(); if (rightTypeId.isDecimalTypeId()) { int charMaxWidth = leftType.getMaximumWidth(); precision += (2 * charMaxWidth); scale += charMaxWidth; maxWidth = precision + 3; } leftOperand = (ValueNode)node.getNodeFactory() .getNode(NodeTypes.CAST_NODE, leftOperand, new DataTypeDescriptor(rightTypeId, precision, scale, nullableResult, maxWidth), node.getParserContext()); node.setLeftOperand(leftOperand); } else if (rightTypeId.isStringTypeId() && leftTypeId.isNumericTypeId()) { boolean nullableResult; nullableResult = leftType.isNullable() || rightType.isNullable(); /* If other side is decimal/numeric, then we need to diddle * with the precision, scale and max width in order to handle * computations like: 1.1 + '0.111' */ int precision = leftType.getPrecision(); int scale = leftType.getScale(); int maxWidth = leftType.getMaximumWidth(); if (leftTypeId.isDecimalTypeId()) { int charMaxWidth = rightType.getMaximumWidth(); precision += (2 * charMaxWidth); scale += charMaxWidth; maxWidth = precision + 3; } rightOperand = (ValueNode)node.getNodeFactory() .getNode(NodeTypes.CAST_NODE, rightOperand, new DataTypeDescriptor(leftTypeId, precision, scale, nullableResult, maxWidth), node.getParserContext()); node.setRightOperand(rightOperand); } /* ** Set the result type of this operator based on the operands. ** By convention, the left operand gets to decide the result type ** of a binary operator. */ return getTypeCompiler(leftOperand). resolveArithmeticOperation(leftOperand.getType(), rightOperand.getType(), node.getOperator()); } protected DataTypeDescriptor binaryComparisonOperatorNode(BinaryComparisonOperatorNode node) throws StandardException { ValueNode leftOperand = node.getLeftOperand(); ValueNode rightOperand = node.getRightOperand(); // Infer type for parameters from other comparand. if (leftOperand.isParameterNode()) { DataTypeDescriptor rightType = rightOperand.getType(); if (rightType != null) leftOperand.setType(rightType.getNullabilityType(true)); } else if (rightOperand.isParameterNode()) { DataTypeDescriptor leftType = leftOperand.getType(); if (leftType != null) rightOperand.setType(leftType.getNullabilityType(true)); } TypeId leftTypeId = leftOperand.getTypeId(); TypeId rightTypeId = rightOperand.getTypeId(); if ((leftTypeId == null) || (rightTypeId == null)) return null; /* * If we are comparing a non-string with a string type, then we * must prevent the non-string value from being used to probe into * an index on a string column. This is because the string types * are all of low precedence, so the comparison rules of the non-string * value are used, so it may not find values in a string index because * it will be in the wrong order. */ if (!leftTypeId.isStringTypeId() && rightTypeId.isStringTypeId()) { DataTypeDescriptor leftType = leftOperand.getType(); DataTypeDescriptor rightType = rightOperand.getType(); rightOperand = (ValueNode)node.getNodeFactory() .getNode(NodeTypes.CAST_NODE, rightOperand, leftType.getNullabilityType(rightType.isNullable()), node.getParserContext()); node.setRightOperand(rightOperand); } else if (!rightTypeId.isStringTypeId() && leftTypeId.isStringTypeId()) { DataTypeDescriptor leftType = leftOperand.getType(); DataTypeDescriptor rightType = rightOperand.getType(); leftOperand = (ValueNode)node.getNodeFactory() .getNode(NodeTypes.CAST_NODE, leftOperand, rightType.getNullabilityType(leftType.isNullable()), node.getParserContext()); node.setLeftOperand(leftOperand); } // Bypass the comparable check if this is a rewrite from the // optimizer. We will assume Mr. Optimizer knows what he is doing. if (!node.isForQueryRewrite()) { String operator = node.getOperator(); boolean forEquals = operator.equals("=") || operator.equals("<>"); boolean cmp = leftOperand.getType().comparable(rightOperand.getType(), forEquals); if (!cmp) { throw new StandardException("Types not comparable: " + leftOperand.getType().getTypeName() + " and " + rightOperand.getType().getTypeName()); } } /* ** Set the result type of this comparison operator based on the ** operands. The result type is always Boolean - the only question ** is whether it is nullable or not. If either of the operands is ** nullable, the result of the comparison must be nullable, too, so ** we can represent the unknown truth value. */ boolean nullableResult = leftOperand.getType().isNullable() || rightOperand.getType().isNullable(); return new DataTypeDescriptor(TypeId.BOOLEAN_ID, nullableResult); } protected DataTypeDescriptor betweenOperatorNode(BetweenOperatorNode node) throws StandardException { ValueNode leftOperand = node.getLeftOperand(); DataTypeDescriptor leftType = leftOperand.getType(); if (leftType == null) return null; ValueNodeList rightOperands = node.getRightOperandList(); ValueNode lowOperand = rightOperands.get(0); ValueNode highOperand = rightOperands.get(1); if (lowOperand.isParameterNode()) { lowOperand.setType(leftType.getNullabilityType(true)); } if (highOperand.isParameterNode()) { highOperand.setType(leftType.getNullabilityType(true)); } TypeId leftTypeId = leftOperand.getTypeId(); DataTypeDescriptor lowType = lowOperand.getType(); DataTypeDescriptor highType = highOperand.getType(); if (!leftTypeId.isStringTypeId()) { if ((lowType != null) && lowType.getTypeId().isStringTypeId()) { lowOperand = (ValueNode)node.getNodeFactory() .getNode(NodeTypes.CAST_NODE, lowOperand, leftType.getNullabilityType(lowType.isNullable()), node.getParserContext()); rightOperands.set(0, lowOperand); } if ((highType != null) && highType.getTypeId().isStringTypeId()) { highOperand = (ValueNode)node.getNodeFactory() .getNode(NodeTypes.CAST_NODE, highOperand, leftType.getNullabilityType(highType.isNullable()), node.getParserContext()); rightOperands.set(1, highOperand); } } if ((lowType == null) || (highType == null)) return null; boolean nullableResult = leftType.isNullable() || lowType.isNullable() || highType.isNullable(); return new DataTypeDescriptor(TypeId.BOOLEAN_ID, nullableResult); } protected DataTypeDescriptor inListOperatorNode(InListOperatorNode node) throws StandardException { ValueNode leftOperand = node.getLeftOperand(); DataTypeDescriptor leftType = leftOperand.getType(); if (leftType == null) return null; boolean nullableResult = leftType.isNullable(); for (ValueNode rightOperand : node.getRightOperandList()) { DataTypeDescriptor rightType; if (rightOperand.isParameterNode()) { rightType = leftType.getNullabilityType(true); rightOperand.setType(rightType); } else { rightType = rightOperand.getType(); } if ((rightType == null) || rightType.isNullable()) nullableResult = true; } return new DataTypeDescriptor(TypeId.BOOLEAN_ID, nullableResult); } protected DataTypeDescriptor subqueryNode(SubqueryNode node) throws StandardException { if (node.getSubqueryType() == SubqueryNode.SubqueryType.EXPRESSION) return node.getResultSet().getResultColumns().get(0) .getType().getNullabilityType(true); else return new DataTypeDescriptor(TypeId.BOOLEAN_ID, true); } protected DataTypeDescriptor conditionalNode(ConditionalNode node) throws StandardException { checkBooleanClause(node.getTestCondition(), "WHEN"); return dominantType(node.getThenElseList()); } protected DataTypeDescriptor coalesceFunctionNode(CoalesceFunctionNode node) throws StandardException { return dominantType(node.getArgumentsList()); } protected DataTypeDescriptor aggregateNode(AggregateNode node) throws StandardException { if (node.getAggregateName().equals("COUNT") || node.getAggregateName().equals("COUNT(*)")) return new DataTypeDescriptor(TypeId.INTEGER_ID, false); ValueNode operand = node.getOperand(); if ((operand == null) || (operand.getType() == null)) return null; return operand.getType().getNullabilityType(true); } protected DataTypeDescriptor concatenationOperatorNode(ConcatenationOperatorNode node) throws StandardException { ValueNode leftOperand = node.getLeftOperand(); ValueNode rightOperand = node.getRightOperand(); DataTypeDescriptor leftType = leftOperand.getType(); DataTypeDescriptor rightType = rightOperand.getType(); if ((leftType != null) && !leftType.getTypeId().isStringTypeId()) { leftType = new DataTypeDescriptor(TypeId.VARCHAR_ID, leftType.isNullable(), leftType.getMaximumWidth()); leftOperand = (ValueNode)node.getNodeFactory() .getNode(NodeTypes.CAST_NODE, leftOperand, leftType, node.getParserContext()); node.setLeftOperand(leftOperand); } else if (leftOperand.isParameterNode()) { leftType = new DataTypeDescriptor(TypeId.VARCHAR_ID, true); leftOperand.setType(leftType); } if ((rightType != null) && !rightType.getTypeId().isStringTypeId()) { rightType = new DataTypeDescriptor(TypeId.VARCHAR_ID, rightType.isNullable(), rightType.getMaximumWidth()); rightOperand = (ValueNode)node.getNodeFactory() .getNode(NodeTypes.CAST_NODE, rightOperand, rightType, node.getParserContext()); node.setRightOperand(rightOperand); } else if (rightOperand.isParameterNode()) { rightType = new DataTypeDescriptor(TypeId.VARCHAR_ID, true); rightOperand.setType(rightType); } if ((leftType == null) || (rightType == null)) return null; return new DataTypeDescriptor(TypeId.VARCHAR_ID, leftType.isNullable() || rightType.isNullable(), leftType.getMaximumWidth() + rightType.getMaximumWidth()); } protected DataTypeDescriptor dominantType(ValueNodeList nodeList) throws StandardException { DataTypeDescriptor result = null; for (ValueNode node : nodeList) { if (node.getType() == null) continue; if (result == null) result = node.getType(); else result = result.getDominantType(node.getType()); } if (result != null) { for (int i = 0; i < nodeList.size(); i++) { ValueNode node = nodeList.get(i); if (node.isParameterNode()) node.setType(result.getNullabilityType(true)); else if (addDominantCast(result, node.getType())) { node = (ValueNode)node.getNodeFactory() .getNode(NodeTypes.CAST_NODE, node, result.getNullabilityType(node.getType().isNullable()), node.getParserContext()); nodeList.set(i, node); } } } return result; } protected boolean addDominantCast(DataTypeDescriptor toType, DataTypeDescriptor fromType) { if (fromType == null) return false; if (toType.getTypeId().isStringTypeId()) return !fromType.getTypeId().isStringTypeId(); return fromType.getTypeId() != toType.getTypeId(); } protected void selectNode(SelectNode node) throws StandardException { // Probably the only possible case syntactically is a // ColumnReference to a non-boolean column. checkBooleanClause(node.getWhereClause(), "WHERE"); checkBooleanClause(node.getHavingClause(), "HAVING"); // Children first wasn't enough to ensure that subqueries were done first. if (node.getResultColumns() != null) node.getResultColumns().accept(this); } private void checkBooleanClause(ValueNode clause, String which) throws StandardException { if (clause != null) { DataTypeDescriptor type = clause.getType(); if (type == null) { assert false : "Type not set yet"; return; } if (!type.getTypeId().isBooleanTypeId()) throw new StandardException("Non-boolean " + which + " clause"); } } private void fromSubquery(FromSubquery node) throws StandardException { if (node.getResultColumns() != null) { ResultColumnList rcl1 = node.getResultColumns(); ResultColumnList rcl2 = node.getSubquery().getResultColumns(); int size = rcl1.size(); for (int i = 0; i < size; i++) { rcl1.get(i).setType(rcl2.get(i).getType()); } } } /* Visitor interface. */ public Visitable visit(Visitable node) throws StandardException { if (node instanceof ValueNode) { // Value nodes compute type if necessary. ValueNode valueNode = (ValueNode)node; if (valueNode.getType() == null) { valueNode.setType(computeType(valueNode)); } } else { // Some structural nodes require special handling. switch (((QueryTreeNode)node).getNodeType()) { case NodeTypes.SELECT_NODE: selectNode((SelectNode)node); break; case NodeTypes.FROM_SUBQUERY: fromSubquery((FromSubquery)node); break; } } return node; } public boolean skipChildren(Visitable node) throws StandardException { return false; } public boolean visitChildrenFirst(Visitable node) { return true; } public boolean stopTraversal() { return false; } /** * Get the TypeCompiler associated with the given TypeId * * @param typeId The TypeId to get a TypeCompiler for * * @return The corresponding TypeCompiler * */ protected TypeCompiler getTypeCompiler(TypeId typeId) { return TypeCompiler.getTypeCompiler(typeId); } /** * Get the TypeCompiler from this ValueNode, based on its TypeId * using getTypeId(). * * @return This ValueNode's TypeCompiler * */ protected TypeCompiler getTypeCompiler(ValueNode valueNode) throws StandardException { return getTypeCompiler(valueNode.getTypeId()); } }
package com.fishercoder.solutions; public class _414 { public static class Solution1 { public int thirdMax(int[] nums) { long max1 = Long.MIN_VALUE; long max2 = Long.MIN_VALUE; long max3 = Long.MIN_VALUE; for (int i : nums) { max1 = Math.max(max1, i); } for (int i : nums) { if (i == max1) { continue; } max2 = Math.max(max2, i); } for (int i : nums) { if (i == max1 || i == max2) { continue; } max3 = Math.max(max3, i); } return (int) (max3 == Long.MIN_VALUE ? max1 : max3); } } }
package com.fishercoder.solutions; import com.fishercoder.common.classes.Node; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class _429 { public static class Solution1 { public List<List<Integer>> levelOrder(Node root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) { return result; } Queue<Node> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); List<Integer> level = new ArrayList<>(); for (int i = 0; i < size; i++) { Node currentNode = queue.poll(); if (currentNode != null) { level.add(currentNode.val); for (Node child : currentNode.children) { queue.offer(child); } } } result.add(level); } return result; } } }
package com.fishercoder.solutions; public class _521 { public static class Solution1 { /** * The gotcha point of this question is: * 1. if a and b are identical, then there will be no common subsequence, return -1 * 2. else if a and b are of equal length, then any one of them will be a subsequence of the other string * 3. else if a and b are of different length, then the longer one is a required subsequence because the longer string cannot be a subsequence of the shorter one * Or in other words, when a.length() != b.length(), no subsequence of b will be equal to a, so return Math.max(a.length(), b.length()) */ public int findLUSlength(String a, String b) { if (a.equals(b)) { return -1; } return Math.max(a.length(), b.length()); } } }
package com.carpentersblocks.data; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import com.carpentersblocks.tileentity.TEBase; import com.carpentersblocks.util.BlockProperties; import com.carpentersblocks.util.registry.BlockRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class GarageDoor extends AbstractMultiBlock implements ISided { /** * 16-bit data components: * * [000000] [0] [0] [0] [000] [0000] * Unused Host Rigid State Dir Type */ public final static GarageDoor INSTANCE = new GarageDoor(); public static final int TYPE_DEFAULT = 0; public static final int TYPE_GLASS_TOP = 1; public static final int TYPE_GLASS = 2; public static final int TYPE_SIDING = 3; public static final int TYPE_HIDDEN = 4; public final static int STATE_CLOSED = 0; public final static int STATE_OPEN = 1; public final static byte DOOR_NONRIGID = 0; public final static byte DOOR_RIGID = 1; /** * Returns type. */ public int getType(TEBase TE) { return TE.getData() & 0xf; } /** * Sets type. */ public void setType(TEBase TE, int type) { int temp = (TE.getData() & ~0xf) | type; TE.setData(temp); } /** * Returns direction. */ @Override public ForgeDirection getDirection(TEBase TE) { int side = (TE.getData() & 0x70) >> 4; return ForgeDirection.getOrientation(side); } /** * Sets direction. */ @Override public boolean setDirection(TEBase TE, ForgeDirection dir) { int temp = (TE.getData() & ~0x70) | (dir.ordinal() << 4); return TE.setData(temp); } /** * Returns state (open or closed). */ public int getState(TEBase TE) { return (TE.getData() & 0x80) >> 7; } /** * Sets state (open or closed). */ public void setState(TEBase TE, int state) { int temp = (TE.getData() & ~0x80) | (state << 7); TE.setData(temp); } /** * Whether garage door is rigid (requires redstone). */ public boolean isRigid(TEBase TE) { return getRigidity(TE) == DOOR_RIGID; } /** * Returns rigidity (requiring redstone). */ public int getRigidity(TEBase TE) { return (TE.getData() & 0x100) >> 8; } /** * Sets rigidity (requiring redstone). */ public void setRigidity(TEBase TE, int rigidity) { int temp = (TE.getData() & ~0x100) | (rigidity << 8); TE.setData(temp); } /** * Sets host door (the topmost). */ public void setHost(TEBase TE) { int temp = TE.getData() | 0x200; TE.setData(temp); } /** * Returns true if door is host (the topmost). */ public boolean isHost(TEBase TE) { return (TE.getData() & 0x200) > 0; } /** * Compares door pieces by distance from player. */ @SideOnly(Side.CLIENT) class DoorPieceDistanceComparator implements Comparator<TEBase> { @Override public int compare(TEBase tileEntity1, TEBase tileEntity2) { double dist1 = Minecraft.getMinecraft().thePlayer.getDistance(tileEntity1.xCoord, tileEntity1.yCoord, tileEntity1.zCoord); double dist2 = Minecraft.getMinecraft().thePlayer.getDistance(tileEntity2.xCoord, tileEntity2.yCoord, tileEntity2.zCoord); return dist1 < dist2 ? -1 : 1; } } /** * When passed a TEBase, will play state change sound * if piece is nearest to player out of all connecting * door pieces. * <p> * The server would normally handle this and send notification * to all nearby players, but sound source will be dependent * on each player's location. * * @param list an {@link ArrayList<TEBase>} of door pieces * @param entityPlayer the source {@link EntityPlayer} * @return the {@link TEBase} nearest to {@link EntityPlayer} */ @SideOnly(Side.CLIENT) public void playStateChangeSound(TEBase TE) { Set<TEBase> set = getBlocks(TE, BlockRegistry.blockCarpentersGarageDoor); List<TEBase> list = new ArrayList<TEBase>(set); // For sorting // Only play sound if piece is nearest to player Collections.sort(list, new DoorPieceDistanceComparator()); if (list.get(0).equals(TE)) { TE.getWorldObj().playAuxSFXAtEntity((EntityPlayer)null, 1003, TE.xCoord, TE.yCoord, TE.zCoord, 0); } } /** * Helper function for determining properties based on a * nearby garage door piece around the given coordinates. * * @param world the {@link World} * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @return a {@link TEBase} with relevant properties */ public TEBase findReferencePiece(World world, int x, int y, int z, ForgeDirection axis) { ForgeDirection dir = axis.getRotation(ForgeDirection.UP); do { TEBase temp1 = BlockProperties.getTileEntity(BlockRegistry.blockCarpentersGarageDoor, world, x + dir.offsetX, y, z + dir.offsetZ); TEBase temp2 = BlockProperties.getTileEntity(BlockRegistry.blockCarpentersGarageDoor, world, x - dir.offsetX, y, z - dir.offsetZ); if (temp1 != null && getDirection(temp1).equals(axis)) { return temp1; } else if (temp2 != null && getDirection(temp2).equals(axis)) { return temp2; } } while (y > 0 && world.getBlock(x, --y, z).equals(Blocks.air)); return null; } /** * Copies relevant properties and owner from source tile * entity to destination tile entity. * * @param src the source {@link TEBase} * @param dest the destination {@link TEBase} */ public void replicate(final TEBase src, TEBase dest) { setDirection(dest, getDirection(src)); setRigidity(dest, getRigidity(src)); setState(dest, getState(src)); setType(dest, getType(src)); dest.copyOwner(src); } /** * Whether garage door is open. * * @param TE the {@link TEBase} * @return <code>true</code> if garage door is open */ public boolean isOpen(TEBase TE) { return getState(TE) == STATE_OPEN; } /** * Weather panel is the bottommost. * * @param TE the {@link TEBase} * @return true if panel is the bottommost */ public boolean isBottommost(TEBase TE) { return !TE.getWorldObj().getBlock(TE.xCoord, TE.yCoord - 1, TE.zCoord).equals(BlockRegistry.blockCarpentersGarageDoor); } /** * Gets the topmost garage door tile entity. * * @param TE the {@link TEBase} * @return the {@link TEBase} */ public TEBase getTopmost(World world, int x, int y, int z) { do { ++y; } while (world.getBlock(x, y, z).equals(BlockRegistry.blockCarpentersGarageDoor)); return (TEBase) world.getTileEntity(x, y - 1, z); } /** * Gets the bottommost garage door tile entity. * * @param TE the {@link TEBase} * @return the {@link TEBase} */ public TEBase getBottommost(World world, int x, int y, int z) { do { --y; } while (world.getBlock(x, y, z).equals(BlockRegistry.blockCarpentersGarageDoor)); return (TEBase) world.getTileEntity(x, y + 1, z); } /** * Whether block is visible. * <p> * If a block is open and not in the topmost position, * it cannot be selected or collided with. * * @param TE the {@link TEBase} * @return true if visible */ public boolean isVisible(TEBase TE) { if (isOpen(TE)) { return isHost(TE); } else { return true; } } @Override public int getMatchingDataPattern(TEBase TE) { return TE.getData() & 0x70; } @Override public ForgeDirection[] getLocateDirs(TEBase TE) { ForgeDirection dirPlane = getDirection(TE).getRotation(ForgeDirection.UP); ForgeDirection[] dirs = { ForgeDirection.UP, ForgeDirection.DOWN, dirPlane, dirPlane.getOpposite() }; return dirs; } }
package components.data; import com.sun.istack.internal.NotNull; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumnModel; import java.awt.*; import java.awt.event.MouseEvent; public class TitanTable extends JTable { private int[][] group; private static final Color[] colors = { new Color(0, 152, 207), new Color(255, 233, 0), new Color(255, 115, 119), new Color(239, 44, 193) }; public TitanTable() { // Super Constructor super(null); // Init Table setAutoResizeMode(JTable.AUTO_RESIZE_OFF); setTableHeader(null); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setRowSelectionAllowed(false); } public void setTableContents(String[] names, boolean[][] data, int[][] group) { this.group = group; // Init variables int dataSize = names.length; int tableSize = names.length + 1; DefaultTableModel tableModel = new DefaultTableModel(0, tableSize) { // Non Editable @Override public boolean isCellEditable(int row, int column) { return false; } }; setModel(tableModel); TableColumnModel columnModel = getColumnModel(); // Add Header String[] columnNames = new String[tableSize]; columnNames[0] = ""; for (int i = 1; i < tableSize; i++) { columnNames[i] = String.valueOf(i); columnModel.getColumn(i).setMaxWidth(15); } tableModel.addRow(columnNames); // Add Rows for (int i = 0; i < dataSize; i++) { String[] tempRow = new String[tableSize]; tempRow[0] = names[i]; for (int j = 0; j < dataSize; j++) { String stringData; if (i == j) { stringData = "."; } else if (data[i][j]) { stringData = "x"; } else { stringData = " "; } tempRow[j + 1] = stringData; } tableModel.addRow(tempRow); } // Set first column size int maxSize = 0; for (int i = 0; i < tableSize; i++) { TableCellRenderer renderer = getCellRenderer(i, 0); Component component = prepareRenderer(renderer, i, 0); maxSize = Math.max(maxSize, component.getPreferredSize().width); } columnModel.getColumn(0).setMinWidth(maxSize + 10); } @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component component = super.prepareRenderer(renderer, row, column); component.setBackground(Color.WHITE); component.setForeground(Color.BLACK); if (group != null) { if (row > 0 && column > 0) { if (group[row - 1][column - 1] > 0) { component.setBackground(colors[(group[row - 1][column - 1] - 1) % colors.length]); } } } return component; } @Override public String getToolTipText(@NotNull MouseEvent event) { String tooltip = null; Point p = event.getPoint(); int row = rowAtPoint(p); int column = columnAtPoint(p); if (row > 0 && column > 0) { tooltip = String.format("<html>%s<br>%s<br><b>Click to change value</b></html>", getValueAt(row, 0).toString(), getValueAt(column, 0).toString()); } if (tooltip == null) { tooltip = getToolTipText(); } return tooltip; } }
package com.conveyal.r5.analyst; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClient; import com.amazonaws.services.sqs.model.MessageAttributeValue; import com.amazonaws.services.sqs.model.SendMessageRequest; import com.conveyal.r5.analyst.cluster.GridRequest; import com.conveyal.r5.analyst.cluster.Origin; import com.conveyal.r5.analyst.cluster.TaskStatistics; import com.conveyal.r5.api.util.LegMode; import com.conveyal.r5.profile.FastRaptorWorker; import com.conveyal.r5.profile.PerTargetPropagater; import com.conveyal.r5.profile.Propagater; import com.conveyal.r5.profile.RaptorWorker; import com.conveyal.r5.profile.StreetMode; import com.conveyal.r5.streets.LinkedPointSet; import com.conveyal.r5.streets.StreetRouter; import com.conveyal.r5.transit.TransportNetwork; import com.google.common.io.LittleEndianDataOutputStream; import gnu.trove.iterator.TIntIntIterator; import gnu.trove.map.TIntIntMap; import org.apache.commons.math3.random.MersenneTwister; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Base64; import java.util.BitSet; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.DoubleStream; import java.util.stream.Stream; /** * Computes an accessibility indicator at a single cell in a Web Mercator grid, using destination densities from * a Web Mercator density grid. Both grids must be at the same zoom level. The accessibility indicator is calculated * separately for each iteration of the range RAPTOR algorithm (each departure minute and randomization of the schedules * for the frequency-based routes) and all of these different values of the indicator are retained to allow * probabilistic scenario comparison. This does freeze the travel time cutoff and destination grid in the interest of * keeping the results down to an acceptable size. The results are placed on an Amazon SQS queue for collation by * a GridResultConsumer and a GridResultAssembler. * * These requests are enqueued by the frontend one for each origin in a regional analysis. */ public class GridComputer { private static final Logger LOG = LoggerFactory.getLogger(GridComputer.class); /** The number of iterations used to bootstrap the sampling distribution of the percentiles */ public static final int BOOTSTRAP_ITERATIONS = 1000; /** SQS client. TODO: async? */ private static final AmazonSQS sqs = new AmazonSQSClient(); private static final Base64.Encoder base64 = Base64.getEncoder(); private final GridCache gridCache; public final GridRequest request; private static WebMercatorGridPointSetCache pointSetCache = new WebMercatorGridPointSetCache(); public final TransportNetwork network; public GridComputer(GridRequest request, GridCache gridCache, TransportNetwork network) { this.request = request; this.gridCache = gridCache; this.network = network; } public void run() throws IOException { final Grid grid = gridCache.get(request.grid); // ensure they both have the same zoom level if (request.zoom != grid.zoom) throw new IllegalArgumentException("grid zooms do not match!"); // use the middle of the grid cell request.request.fromLat = Grid.pixelToLat(request.north + request.y + 0.5, request.zoom); request.request.fromLon = Grid.pixelToLon(request.west + request.x + 0.5, request.zoom); // Run the raptor algorithm to get times at each destination for each iteration // first, find the access stops StreetMode mode; if (request.request.accessModes.contains(LegMode.CAR)) mode = StreetMode.CAR; else if (request.request.accessModes.contains(LegMode.BICYCLE)) mode = StreetMode.BICYCLE; else mode = StreetMode.WALK; LOG.info("Maximum number of rides: {}", request.request.maxRides); LOG.info("Maximum trip duration: {}", request.request.maxTripDurationMinutes); // Use the extent of the grid as the targets; this avoids having to convert between coordinate systems, // and avoids including thousands of extra points in the weeds where there happens to be a transit stop. WebMercatorGridPointSet targets = pointSetCache.get(grid); // TODO recast using egress mode final LinkedPointSet linkedTargets = targets.link(network.streetLayer, mode); StreetRouter sr = new StreetRouter(network.streetLayer); sr.distanceLimitMeters = 2000; sr.setOrigin(request.request.fromLat, request.request.fromLon); sr.dominanceVariable = StreetRouter.State.RoutingVariable.DISTANCE_MILLIMETERS; sr.route(); TIntIntMap reachedStops = sr.getReachedStops(); // convert millimeters to seconds int millimetersPerSecond = (int) (request.request.walkSpeed * 1000); for (TIntIntIterator it = reachedStops.iterator(); it.hasNext();) { it.advance(); it.setValue(it.value() / millimetersPerSecond); } FastRaptorWorker router = new FastRaptorWorker(network.transitLayer, request.request, reachedStops); // Run the raptor algorithm int[][] timesAtStopsEachIteration = router.route(); // compute bootstrap weights // the Mersenne Twister is a high-quality RNG well-suited to Monte Carlo situations MersenneTwister twister = new MersenneTwister(); int[][] bootstrapWeights = new int[BOOTSTRAP_ITERATIONS + 1][router.nMinutes * router.monteCarloDrawsPerMinute]; Arrays.fill(bootstrapWeights[0], 1); // equal weight to all observations (sample mean) for first sample for (int bootstrap = 1; bootstrap < bootstrapWeights.length; bootstrap++) { for (int draw = 0; draw < timesAtStopsEachIteration.length; draw++) { bootstrapWeights[bootstrap][twister.nextInt(timesAtStopsEachIteration.length)]++; } } // Do propagation int[] nonTransferTravelTimesToStops = linkedTargets.eval(sr::getTravelTimeToVertex).travelTimes; PerTargetPropagater propagater = new PerTargetPropagater(timesAtStopsEachIteration, nonTransferTravelTimesToStops, linkedTargets, request.request, request.cutoffMinutes * 60); // compute the percentiles double[] samples = new double[BOOTSTRAP_ITERATIONS + 1]; propagater.propagate((target, reachable) -> { int gridx = target % grid.width; int gridy = target / grid.width; double opportunityCountAtTarget = grid.grid[gridx][gridy]; if (opportunityCountAtTarget < 1e-6) return; // don't bother with destinations that contain no opportunities boolean foundAbove = false; boolean foundBelow = false; for (boolean currentReachable : reachable) { if (!currentReachable) foundAbove = true; else foundBelow = true; } if (foundAbove && foundBelow) { // This origin is sometimes reachable within the time window, do bootstrapping to determine // the distribution of how often BOOTSTRAP: for (int bootstrap = 0; bootstrap < BOOTSTRAP_ITERATIONS + 1; bootstrap++) { int count = 0; // include all departure minutes, but create a sample of the same size as the original for (int iteration = 0; iteration < reachable.length; iteration++) { if (reachable[iteration]) { count += bootstrapWeights[bootstrap][iteration]; } } if (count > timesAtStopsEachIteration.length / 2) { samples[bootstrap] += opportunityCountAtTarget; } } } else if (foundBelow && !foundAbove) { // this destination is always reachable and will be included in all bootstrap samples, no need to do the // bootstrapping for (int i = 0; i < samples.length; i++) samples[i] += grid.grid[gridx][gridy]; } // otherwise, this destination is never reachable, no need to do bootstrapping or increment samples }); int[] intSamples = DoubleStream.of(samples).mapToInt(d -> (int) Math.round(d)).toArray(); // now construct the output // these things are tiny, no problem storing in memory ByteArrayOutputStream baos = new ByteArrayOutputStream(); new Origin(request, intSamples).write(baos); // send this origin to an SQS queue as a binary payload; it will be consumed by GridResultConsumer // and GridResultAssembler SendMessageRequest smr = new SendMessageRequest(request.outputQueue, base64.encodeToString(baos.toByteArray())); smr = smr.addMessageAttributesEntry("jobId", new MessageAttributeValue().withDataType("String").withStringValue(request.jobId)); sqs.sendMessage(smr); } }
/** * Created Jan 8, 2008 */ package com.crawljax.browser; import java.io.File; import javax.transaction.NotSupportedException; import org.openqa.selenium.WebElement; import com.crawljax.core.CrawljaxException; import com.crawljax.core.state.Eventable; import com.crawljax.core.state.Identification; import com.crawljax.forms.FormInput; /** * @author mesbah * @version $Id$ */ public interface EmbeddedBrowser extends Cloneable { /** * Browser types. */ public enum BrowserType { firefox, ie, chrome } /** * Opens the url in the browser. * * @param url * the URL. * @throws CrawljaxException * if fails. */ void goToUrl(String url) throws CrawljaxException; /** * fires the event. * * @param event * the event. * @throws CrawljaxException * on Error. * @return if fails. */ boolean fireEvent(Eventable event) throws CrawljaxException; /** * @return the DOM string with all the iframe contents. * @throws CrawljaxException * if fails. */ String getDom() throws CrawljaxException; /** * @return the DOM string without the iframe contents * @throws CrawljaxException * if fails. */ String getDomWithoutIframeContent() throws CrawljaxException; /** * Closes the browser. */ void close(); /** * Closes all other windows. */ void closeOtherWindows(); /** * Go back to the previous state. */ void goBack(); /** * @param identification * the identification. * @param text * the text. * @return true if succeeded. * @throws CrawljaxException * if fails. */ boolean input(Identification identification, String text) throws CrawljaxException; /** * Execute JavaScript in the browser. * * @param script * The script to execute. * @return The JavaScript return object. * @throws CrawljaxException * On error. */ Object executeJavaScript(String script) throws CrawljaxException; /** * Checks if an element is visible. * * @param identification * identification to use. * @return true if the element is visible. */ boolean isVisible(Identification identification); /** * @return The current browser url. */ String getCurrentUrl(); /** * Make a clone of the current EmbeddedBrowser using the custom settings as provided earlier. * * @return a new instance of a EmbeddedBrowser */ EmbeddedBrowser clone(); /** * @param inputForm * the input form. * @return a FormInput filled with random data. */ FormInput getInputWithRandomValue(FormInput inputForm); /** * @param iframeIdentification * the iframe's name or id. * @return the DOM string of the corresponding iframe. */ String getFrameDom(String iframeIdentification); /** * @param identification * the identification of the element to be checked. * @return true if the element can be found in the browser's DOM tree. */ boolean elementExists(Identification identification); /** * @param identification * the identification of the element to be found. * @return the corresponding WebElement from the browser. */ WebElement getWebElement(Identification identification); /** * @param file * the file to write the screenshot to (png). * @throws NotSupportedException * if saving screenshots is not supported by the implementing class. */ void saveScreenShot(File file) throws NotSupportedException; }
package com.filestack.util; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; /** * Intercepts requests to add Filestack-specific headers. */ public class HeaderInterceptor implements Interceptor { public static String HEADER_USER_AGENT = "User-Agent"; public static String HEADER_FILESTACK_SOURCE = "Filestack-Source"; public static String USER_AGENT = "filestack-java %s"; public static String FILESTACK_SOURCE = "Java-%s"; private String version; public HeaderInterceptor() { this.version = Util.getVersion(); } @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); Request modified = original.newBuilder() .addHeader(HEADER_USER_AGENT, String.format(USER_AGENT, version)) .addHeader(HEADER_FILESTACK_SOURCE, String.format(FILESTACK_SOURCE, version)) .build(); return chain.proceed(modified); } }
package com.github.nkzawa.socketio.client; import com.github.nkzawa.socketio.parser.Parser; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; public class IO { private static final Logger logger = Logger.getLogger(IO.class.getName()); private static final ConcurrentHashMap<String, Manager> managers = new ConcurrentHashMap<String, Manager>(); /** * Protocol version. */ public static int protocol = Parser.protocol; private IO() {} public static Socket socket(String uri) throws URISyntaxException { return socket(uri, null); } public static Socket socket(String uri, Options opts) throws URISyntaxException { return socket(new URI(uri), opts); } public static Socket socket(URI uri) throws URISyntaxException { return socket(uri, null); } /** * Initializes a {@link Socket} from an existing {@link Manager} for multiplexing. * * @param uri uri to connect. * @param opts options for socket. * @return {@link Socket} instance. * @throws URISyntaxException */ public static Socket socket(URI uri, Options opts) throws URISyntaxException { if (opts == null) { opts = new Options(); } URL parsed; try { parsed = Url.parse(uri); } catch (MalformedURLException e) { throw new URISyntaxException(uri.toString(), e.getMessage()); } URI source = parsed.toURI(); Manager io; if (opts.forceNew || !opts.multiplex) { logger.info(String.format("ignoring socket cache for %s", source)); io = new Manager(source, opts); } else { String id = Url.extractId(parsed); if (!managers.containsKey(id)) { logger.info(String.format("new io instance for %s", source)); managers.putIfAbsent(id, new Manager(source, opts)); } io = managers.get(id); } return io.socket(parsed.getPath()); } public static class Options extends com.github.nkzawa.engineio.client.Socket.Options { public boolean forceNew; /** * Whether to enable multiplexing. Default is true. */ public boolean multiplex = true; public boolean reconnection = true; public int reconnectionAttempts; public long reconnectionDelay; public long reconnectionDelayMax; public long timeout = -1; } }
package com.gliwka.hyperscan.wrapper; import com.sun.jna.*; import com.gliwka.hyperscan.jna.*; import com.sun.jna.ptr.PointerByReference; import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.List; /** * Scanner, can be used with databases to scan for expressions in input string * In case of multithreaded scanning, you need one scanner instance per thread. */ public class Scanner { private PointerByReference scratchReference = new PointerByReference(); private Pointer scratch; /** * Check if the hardware platform is supported * @return true if supported, otherwise false */ public static boolean getIsValidPlatform() { return HyperscanLibrary.INSTANCE.hs_valid_platform() == 0; } /** * Get the version information for the underlying hyperscan library * @return version string */ public static String getVersion() { return HyperscanLibrary.INSTANCE.hs_version(); } /** * Get the scratch space size in bytes * @return count of bytes */ public long getSize() { SizeTByReference size = new SizeTByReference(); HyperscanLibrary.INSTANCE.hs_scratch_size(scratch, size); return size.getValue().longValue(); } /** * Allocate a scratch space. Must be called at least once with each * database that will be used before scan is called. * @param db Database containing expressions to use for matching * @throws Throwable Throws if out of memory or platform not supported * or if the allocation fails */ public synchronized void allocScratch(final Database db) throws Throwable { Pointer dbPointer = db.getPointer(); int hsError = HyperscanLibrary.INSTANCE.hs_alloc_scratch(dbPointer, scratchReference); if(hsError != 0) throw new OutOfMemoryError("Not enough memory to allocate scratch space"); } private LinkedList<long[]> matchedIds = new LinkedList<>(); private HyperscanLibrary.match_event_handler matchHandler = new HyperscanLibrary.match_event_handler() { public int invoke(int id, long from, long to, int flags, Pointer context) { long[] tuple = { id, from, to }; matchedIds.add(tuple); return 0; } }; /** * scan for a match in a string using a compiled expression database * Can only be executed one at a time on a per instance basis * @param db Database containing expressions to use for matching * @param input String to match against * @return List of Matches * @throws Throwable Throws if out of memory or platform not supported */ public synchronized List<Match> scan(final Database db, final String input) throws Throwable { Pointer dbPointer = db.getPointer(); scratch = scratchReference.getValue(); final LinkedList<Match> matches = new LinkedList<Match>(); final byte[] utf8bytes =input.getBytes(StandardCharsets.UTF_8); int bytesLength = utf8bytes.length; final int[] byteToIndex = Util.utf8ByteIndexesMapping(input, bytesLength); matchedIds.clear(); int hsError = HyperscanLibrary.INSTANCE.hs_scan(dbPointer, input, bytesLength, 0, scratch, matchHandler, Pointer.NULL); if(hsError != 0) throw Util.hsErrorIntToException(hsError); matchedIds.forEach( tuple -> { int id = (int)tuple[0]; long from = tuple[1]; long to = tuple[2]; String match = ""; Expression matchingExpression = db.getExpression(id); if(matchingExpression.getFlags().contains(ExpressionFlag.SOM_LEFTMOST)) { int startIndex = byteToIndex[(int)from]; int endIndex = byteToIndex[(int)to - 1]; match = input.substring(startIndex, endIndex + 1); } matches.add(new Match(byteToIndex[(int)from], byteToIndex[(int)to - 1], match, matchingExpression)); }); return matches; } @Override protected void finalize() { HyperscanLibrary.INSTANCE.hs_free_scratch(scratch); } }
package com.kodcu.component; import com.kodcu.controller.ApplicationController; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Worker; import javafx.event.EventHandler; import javafx.scene.input.DragEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.scene.web.WebEngine; import javafx.scene.web.WebEvent; import javafx.scene.web.WebView; import javafx.util.Callback; import netscape.javascript.JSObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.nio.file.Path; import java.util.Objects; @Component @Scope("prototype") public class EditorPane extends AnchorPane { private final WebView webView; private EventHandler<WebEvent<String>> readyHandler; private final Logger logger = LoggerFactory.getLogger(EditorPane.class); private final ApplicationController controller; private String mode; @Autowired public EditorPane(ApplicationController controller) { this.controller = controller; this.webView = new WebView(); this.webView.setContextMenuEnabled(false); this.getChildren().add(webView); webEngine().setOnAlert(event -> { if (Objects.nonNull(readyHandler)) readyHandler.handle(event); }); initializeMargins(); } private void initializeMargins() { AnchorPane.setBottomAnchor(this, 0D); AnchorPane.setTopAnchor(this, 0D); AnchorPane.setLeftAnchor(this, 0D); AnchorPane.setRightAnchor(this, 0D); VBox.setVgrow(this, Priority.ALWAYS); AnchorPane.setBottomAnchor(webView, 0D); AnchorPane.setTopAnchor(webView, 0D); AnchorPane.setLeftAnchor(webView, 0D); AnchorPane.setRightAnchor(webView, 0D); VBox.setVgrow(webView, Priority.ALWAYS); } public void load(String url) { if (Objects.nonNull(url)) Platform.runLater(() -> { webEngine().load(url); }); else logger.error("Url is not loaded. Reason: null reference"); } public void hide() { super.setVisible(false); } public void show() { super.setVisible(true); } public void setOnReady(EventHandler<WebEvent<String>> readyHandler) { this.readyHandler = readyHandler; } public String getLocation() { return webEngine().getLocation(); } public void setMember(String name, Object value) { getWindow().setMember(name, value); } public Object call(String methodName, Object... args) { return getWindow().call(methodName, args); } public void whenStateSucceed(ChangeListener<Worker.State> stateChangeListener) { webEngine().getLoadWorker().stateProperty().addListener(stateChangeListener); } public Object getMember(String name) { return getWindow().getMember(name); } public WebEngine webEngine() { return webView.getEngine(); } public WebView getWebView() { return webView; } public void onClicked(EventHandler<MouseEvent> eventHandler) { webView.setOnMouseClicked(eventHandler); } public void dragDropped(EventHandler<DragEvent> eventHandler) { webView.setOnDragDropped(eventHandler); } public void confirmHandler(Callback<String, Boolean> confirmHandler) { webEngine().setConfirmHandler(confirmHandler); } public JSObject getWindow() { return (JSObject) webEngine().executeScript("window"); } public String getEditorValue() { return (String) webEngine().executeScript("editor.getValue()"); } public void switchMode(Object... args) { this.call("switchMode", args); } public void rerender(Object... args) { this.call("rerender", args); } public void focus() { webView.requestFocus(); } public void moveCursorTo(Integer lineno) { if (Objects.nonNull(lineno)) { webEngine().executeScript(String.format("editor.gotoLine(%d,-1,false)", (lineno))); webEngine().executeScript(String.format("editor.scrollToLine(%d,false,false,function(){})", (lineno - 3))); } } public void changeEditorMode(Path path) { if (Objects.nonNull(path)) { String mode = (String) webEngine().executeScript(String.format("changeEditorMode('%s')", path.toUri().toString())); setMode(mode); } } public String editorMode() { return (String) this.call("editorMode", new Object[]{}); } public void fillModeList(ObservableList modeList) { Platform.runLater(() -> { this.call("fillModeList", modeList); }); } public boolean is(String mode) { return ("ace/mode/" + mode).equalsIgnoreCase(this.mode); } public void setMode(String mode) { this.mode = mode; } public String getMode() { return mode; } }
package com.google.sps.servlets; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.gson.Gson; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.sps.data.Book; import java.net.URL; import java.net.HttpURLConnection; import java.util.Scanner; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonElement; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.net.URLEncoder; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * Servlet for generating a map of each term to a * list of the corresponding related books. */ @WebServlet("/books") public class BooksServlet extends HttpServlet { private final int NUM_BOOKS_PER_TERM = 5; /* * Writes a mapping of terms to lists of book objects in the servlet response. */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { List<String> terms = Arrays.asList(request.getParameterValues("key")); LinkedHashMap<String, List<Book>> booksMap = new LinkedHashMap<>(); terms.forEach((term) -> { String jsonString = getJsonStringForTerm(term); List<Book> books = makeBooksList(jsonString); booksMap.put(term, books); }); String json = encodeBookMapAsJson(booksMap); response.getWriter().println(json); } /** * Encodes the given term so that it can fit in a url. * @return An encoded string */ private String encodeTerm(String term) { try { return URLEncoder.encode(term, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex.getCause()); } } /** * Encodes a hashmap to a string format which can be easily processed by Mustache. * @return An encoded hashmap in string format. */ private String encodeBookMapAsJson(LinkedHashMap<String, List<Book>> booksMap) { Gson gson = new Gson(); Map<String, Object> books = new HashMap<>(); books.put("books", booksMap); String json = gson.toJson(books); return json; } /** * Creates list of Book objects from JSON results of Google Books query. * @return list of book objects. */ private List<Book> makeBooksList(String jsonString) { JsonObject responseObject = new JsonParser().parse(jsonString).getAsJsonObject(); JsonArray booksJsonArray = responseObject.getAsJsonArray("items"); // Reduce number of books displayed if there less books in the json array than as default. int numResults = booksJsonArray.size(); numResults = Math.min(numResults, NUM_BOOKS_PER_TERM); List<Book> books = new ArrayList<>(); for (int i = 0; i < numResults; i++) { JsonObject bookJson = booksJsonArray.get(i).getAsJsonObject().getAsJsonObject("volumeInfo"); String title = bookJson.get("title").getAsString(); String link = bookJson.get("infoLink").getAsString(); String image = bookJson.getAsJsonObject("imageLinks").get("thumbnail").getAsString(); String description = bookJson.get("description").getAsString(); String author = formatAuthors(bookJson.getAsJsonArray("authors")); books.add(new Book.Builder(title, link).withImage(image).withDescription(description).withAuthor(author).build()); } return books; } /** * Reads in JSON from an open URL. * @return JSON in String format. */ private String readJsonFile(URL url) throws IOException { Scanner jsonReader = new Scanner(url.openStream()); String data = ""; while(jsonReader.hasNext()) { data += jsonReader.nextLine(); } jsonReader.close(); return data; } /** * Formats authors into string from JSON array. * @return authors in String fomat. */ private String formatAuthors(JsonArray authorsArray) { Gson gson = new Gson(); ArrayList jsonObjList = gson.fromJson(authorsArray, ArrayList.class); return String.join(",", jsonObjList); } /** * Makes request to Google Books API's for books relating to a term and gets JSON response. * @return String of Google Books API JSON response. */ private String getJsonStringForTerm(String term) { String path = "https: String queryParam = "q=" + encodeTerm(term); String queryPath = path + queryParam; try { URL url = new URL(queryPath); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode != 200) { System.err.println("Error: connection response code is: " + responseCode); } return readJsonFile(url); } catch(Exception e) { e.printStackTrace(); } return ""; } }
package com.ociweb.iot.grove; import com.ociweb.iot.hardware.I2CConnection; import com.ociweb.iot.hardware.IODevice; import com.ociweb.iot.maker.Hardware; /** * Holds information for all standard Analog and Digital I/O twigs in the Grove starter kit. * * Methods are necessary for interpreting new connections declared in * IoTSetup declareConnections in the maker app. * * @see com.ociweb.iot.hardware.IODevice */ public enum GroveTwig implements IODevice { UVSensor() { @Override public boolean isInput() { return true; } @Override public int response() { return 30; } }, LightSensor() { @Override public boolean isInput() { return true; } @Override public int response() { return 100; } }, SoundSensor() { @Override public boolean isInput() { return true; } @Override public int response() { return 2; } }, AngleSensor() { @Override public boolean isInput() { return true; } @Override public int response() { return 40; } @Override public int range() { return 1024; } }, MoistureSensor() { @Override public boolean isInput() { return true; } }, Button() { @Override public boolean isInput() { return true; } public int response() { return 40; } @Override public int range() { return 1; } }, MotionSensor() { @Override public boolean isInput() { return true; } @Override public int range() { return 1; } }, LineFinder() { @Override public boolean isInput() { return true; } @Override public int range() { return 1; } }, RotaryEncoder() { @Override public boolean isInput() { return true; } @Override public int pinsUsed() { return 2; } }, Buzzer() { @Override public boolean isOutput() { return true; } }, LED() { @Override public boolean isOutput() { return true; } @Override public boolean isPWM() { return true; } }, Relay() { @Override public boolean isOutput() { return true; } }, Servo() { @Override public boolean isOutput() { return true; } }, I2C() { @Override public boolean isInput() { return true; } @Override public boolean isOutput() { return true; } }, UltrasonicRanger() { @Override public boolean isInput() { return true; } @Override public int range() { return 1024; } @Override public int response() { return 200; } @Override public int scanDelay() { return 1_420_000; } }, ThumbJoystick(){ @Override public boolean isInput(){ return true; } @Override public int range(){ return 1024; } @Override public int pinsUsed(){ return 2; } public boolean isPressed(int val){ return val == 1023; } }, FourDigitDisplay(){ @Override public boolean isOutput(){ return true; } @Override public int pinsUsed(){ return 2; } }, VibrationSensor(){ @Override public boolean isInput(){ return true; } @Override public int range(){ return 1024; } }, WaterSensor(){ @Override public boolean isInput(){ return true; } @Override public int range(){ return 1024; } }, TouchSensor() { @Override() public boolean isInput(){ return true; } @Override public int range(){ return 1; } @Override public int response(){ return 60; } }; /** * @return True if this twig is an input device, and false otherwise. */ public boolean isInput() { return false; } /** * @return True if this twig is an output device, and false otherwise. */ public boolean isOutput() { return false; } /** * @return Response time, in milliseconds, for this twig. */ public int response() { return 20; } /** * @return Delay, in milliseconds, for scan. TODO: What's scan? */ public int scanDelay() { return 0; } /** * @return True if this twig is Pulse Width Modulated (PWM) device, and * false otherwise. */ public boolean isPWM() { return false; } /** * @return True if this twig is an I2C device, and false otherwise. */ public boolean isI2C() { return false; } /** * @return The {@link I2CConnection} for this twig if it is an I2C * device, as indicated by {@link #isI2C()}. */ public I2CConnection getI2CConnection() { return null; } /** * @return The possible value range for reads from this device (from zero). */ public int range() { return 256; } /** * @return the setup bytes needed to initialized the connected I2C device */ public byte[] I2COutSetup() { return null; } /** * Validates if the I2C data from from the device is a valid response for this twig * * @param backing * @param position * @param length * @param mask * * @return fals if the bytes returned from the device were not some valid response */ public boolean isValid(byte[] backing, int position, int length, int mask) { return true; } /** * @return The number of hardware pins that this twig uses. */ public int pinsUsed() { return 1; } }
package com.ociweb.iot.grove; import com.ociweb.iot.hardware.I2CConnection; import com.ociweb.iot.hardware.IODevice; import com.ociweb.iot.maker.Hardware; /** * Holds information for all standard Analog and Digital I/O twigs in the Grove starter kit. * * Methods are necessary for interpreting new connections declared in * IoTSetup declareConnections in the maker app. * * @see com.ociweb.iot.hardware.IODevice */ public enum GroveTwig implements IODevice { UVSensor() { @Override public boolean isInput() { return true; } @Override public int response() { return 30; } }, LightSensor() { @Override public boolean isInput() { return true; } @Override public int response() { return 100; } }, SoundSensor() { @Override public boolean isInput() { return true; } @Override public int response() { return 2; } }, AngleSensor() { @Override public boolean isInput() { return true; } @Override public int response() { return 40; } @Override public int range() { return 1024; } }, MoistureSensor() { @Override public boolean isInput() { return true; } }, Button() { @Override public boolean isInput() { return true; } public int response() { return 40; } @Override public int range() { return 1; } }, MotionSensor() { @Override public boolean isInput() { return true; } @Override public int range() { return 1; } }, LineFinder() { @Override public boolean isInput() { return true; } @Override public int range() { return 1; } }, RotaryEncoder() { @Override public boolean isInput() { return true; } @Override public int pinsUsed() { return 2; } }, Buzzer() { @Override public boolean isOutput() { return true; } }, LED() { @Override public boolean isOutput() { return true; } @Override public boolean isPWM() { return true; } }, Relay() { @Override public boolean isOutput() { return true; } }, Servo() { @Override public boolean isOutput() { return true; } }, I2C() { @Override public boolean isInput() { return true; } @Override public boolean isOutput() { return true; } }, UltrasonicRanger() { @Override public boolean isInput() { return true; } @Override public int range() { return 1024; } @Override public int response() { return 200; } @Override public int scanDelay() { return 1_420_000; } }, ThumbJoystick(){ @Override public boolean isInput(){ return true; } @Override public int range(){ return 1024; } @Override public int pinsUsed(){ return 2; } }, WaterSensor(){ @Override public boolean isInput(){ return true; } @Override public boolean isOutput(){ return true; } @Override public int range(){ return 1024; } }; /** * @return True if this twig is an input device, and false otherwise. */ public boolean isInput() { return false; } /** * @return True if this twig is an output device, and false otherwise. */ public boolean isOutput() { return false; } /** * @return Response time, in milliseconds, for this twig. */ public int response() { return 20; } /** * @return Delay, in milliseconds, for scan. TODO: What's scan? */ public int scanDelay() { return 0; } /** * @return True if this twig is Pulse Width Modulated (PWM) device, and * false otherwise. */ public boolean isPWM() { return false; } /** * @return True if this twig is an I2C device, and false otherwise. */ public boolean isI2C() { return false; } /** * @return The {@link I2CConnection} for this twig if it is an I2C * device, as indicated by {@link #isI2C()}. */ public I2CConnection getI2CConnection() { return null; } /** * @return The possible value range for reads from this device (from zero). */ public int range() { return 256; } /** * @return the setup bytes needed to initialized the connected I2C device */ public byte[] I2COutSetup() { return null; } /** * Validates if the I2C data from from the device is a valid response for this twig * * @param backing * @param position * @param length * @param mask * * @return fals if the bytes returned from the device were not some valid response */ public boolean isValid(byte[] backing, int position, int length, int mask) { return true; } /** * @return The number of hardware pins that this twig uses. */ public int pinsUsed() { return 1; } }
package com.googlecode.yqltwitter; import java.io.UnsupportedEncodingException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URLEncoder; import java.util.List; import twitter4j.RateLimitStatus; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.http.Response; /** * Twitter that use YQL to access the twitter API. * * @author Sutra Zhou */ public class YqlTwitter extends Twitter { private static final long serialVersionUID = -4545368679112332540L; private static final boolean DEBUG = System.getProperty("YqlTwitter.debug") != null; /* private static final String API_KEY = "dj0yJmk9VXZBSzNjc0Vwcm1MJmQ9WVdrOVlVczBSVkJNTkdzbWNHbzlNVEV4TWpjNE5EZ3lNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD01Mg--"; private static final String SHARED_SECRET = "ef9287704ac426cb3e1ea0ce3d47fba7a2d82eaf"; private static final String APPLICATION_ID = "aK4EPL4k"; */ private static final String YQL = "https://query.yahooapis.com/v1/public/yql?q="; private static final String enc = "UTF-8"; private static final String TABLE_BASE_URL = "http://yqltwitter.googlecode.com/svn/trunk/src/main/table/"; private final YqlResponseResultsExtractor extractor = new YqlResponseResultsExtractor(); public YqlTwitter() { super(); } /** * @param id * @param password * @param baseURL */ public YqlTwitter(String id, String password, String baseURL) { super(id, password, baseURL); } /** * @param id * @param password */ public YqlTwitter(String id, String password) { super(id, password); } protected Response get(String q, boolean authenticate) throws TwitterException { String url = createYqlUrl(q); debug("Get: " + url); Response response = http.get(url, authenticate); return extractor.extract(response); } protected Response post(String q, boolean authenticate) throws TwitterException { String url = createYqlUrl(q); debug("Post: " + url); Response response = http.post(url, authenticate); return extractor.extract(response); } /** * {@inheritDoc} */ @Override public List<Status> getFriendsTimeline() throws TwitterException { String format = "use '%1$stwitter.friends_timeline.xml' as ft;" + " select * from ft where username='%2$s' and password='%3$s'"; String q = String.format(format, TABLE_BASE_URL, getUserId(), getPassword()); Response response = get(q, true); return invokeStaticMethod(Status.class, "constructStatuses", new Class<?>[] { Response.class, Twitter.class }, new Object[] { response, this }); } /** * {@inheritDoc} */ @Override public List<Status> getPublicTimeline() throws TwitterException { String format = "use '%1$stwitter.public_timeline.xml' as pt;" + " select * from pt"; String q = String.format(format, TABLE_BASE_URL); Response response = get(q, false); return invokeStaticMethod(Status.class, "constructStatuses", new Class<?>[] { Response.class, Twitter.class }, new Object[] { response, this }); } /** * {@inheritDoc} */ @Override public RateLimitStatus rateLimitStatus() throws TwitterException { String format = "use '%1$srate_limit_status.xml' as rls;" + "select * from rls"; String q = String.format(format, TABLE_BASE_URL); Response response = get(q, null != getUserId() && null != getPassword()); return newInstance(RateLimitStatus.class, new Class<?>[] { Response.class }, new Object[] { response }); } /** * {@inheritDoc} */ @Override public Status updateStatus(String status, long inReplyToStatusId) throws TwitterException { // TODO Auto-generated method stub return super.updateStatus(status, inReplyToStatusId); } /** * {@inheritDoc} */ @Override public Status updateStatus(String status) throws TwitterException { String format = "use '%1$stwitter.status.xml' as s;" + " insert into s(status,username,password,source) values ('%2$s','%3$s','%4$s','%5$s')"; String q = String.format(format, TABLE_BASE_URL, status, getUserId(), getPassword(), source); Response response = post(q, true); return newInstance(Status.class, new Class<?>[] { Response.class, Twitter.class }, new Object[] { response, this }); } /** * Create the YQL query URL. * * @param q * the query string * @return URL strng */ private String createYqlUrl(final String q) { try { final String url = YQL + URLEncoder.encode(q, enc); return url; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /* package */static <T> T newInstance(Class<T> clazz, Class<?>[] parameterTypes, Object[] initargs) { try { Constructor<T> c = clazz.getDeclaredConstructor(parameterTypes); c.setAccessible(true); return c.newInstance(initargs); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") /* package */static <T, R> R invokeStaticMethod(Class<T> clazz, String name, Class<?>[] parameterTypes, Object[] args) { Method m; try { m = Status.class.getDeclaredMethod(name, parameterTypes); m.setAccessible(true); Object o = m.invoke(clazz, args); return (R) o; } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } /* package */static void debug(String message) { if (DEBUG) { System.out.println(message); } } }
package com.perimeterx.utils; public final class Constants { // This token is replaced by maven on validation stage to the pom version public final static String SDK_VERSION = "@moduleVersion@"; public final static String ACTIVITY_BLOCKED = "block"; public final static String ACTIVITY_PAGE_REQUESTED = "page_requested"; public static final String SERVER_URL = "https://sapi.perimeterx.net"; public final static String COOKIE_CAPTCHA_KEY = "_pxCaptcha"; public final static String COOKIE_KEY = "_px"; public static final String API_RISK = "/api/v1/risk"; public static final String API_ACTIVITIES = "/api/v1/collector/s2s"; public static final String API_CAPTCHA = "/api/v1/risk/captcha"; public static final int CAPTCHA_SUCCESS_CODE = 0; public static final int CAPTCHA_FAILED_CODE = -1; }
package com.grunka.random.fortuna.tests; import com.grunka.random.fortuna.Fortuna; import java.io.BufferedOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Dump { //TODO decide which dump method to use, maybe combine private static final int MEGABYTE = 1024 * 1024; // Compression test: xz -e9zvkf random.data public static void main(String[] args) throws Exception { if (args.length < 1 || args.length > 2) { usage(); System.exit(args.length == 0 ? 0 : 1); } long megabytes = 0; try { megabytes = Long.parseLong(args[0]); } catch (NumberFormatException e) { usage(); System.err.println("Megabytes was not a number: " + args[0]); System.exit(1); } if (megabytes < 1) { usage(); System.err.println("Needs to be at least one megabyte, was " + megabytes); System.exit(1); } long dataSize = megabytes * MEGABYTE; System.err.println("Initializing RNG..."); Fortuna fortuna = Fortuna.createInstance(); long start = System.currentTimeMillis(); System.err.println("Generating data..."); try (OutputStream output = getOutputStream(args)) { try (OutputStream outputStream = new BufferedOutputStream(output)) { byte[] buffer = new byte[1024]; long remainingBytes = dataSize; while (remainingBytes > 0) { fortuna.nextBytes(buffer); outputStream.write(buffer); remainingBytes -= buffer.length; System.err.print((100 * (dataSize - remainingBytes) / dataSize) + "%\r"); } } } System.err.println("Done in " + ((System.currentTimeMillis() - start) / 1000) + " seconds"); fortuna.shutdown(); } private static OutputStream getOutputStream(String[] args) throws FileNotFoundException { if (args.length == 2) { return new FileOutputStream(args[1], false); } else { return System.out; } } private static void usage() { System.err.println("Usage: " + Dump.class.getName() + " <megabytes> [<file>]"); System.err.println("Will generate <megabytes> of data and output them either to <file> or stdout if <file> is not specified"); } public static void otherMain(String[] args) throws IOException, InterruptedException { boolean hasLimit = false; BigInteger limit = BigInteger.ZERO; if (args.length == 1) { String amount = args[0]; Matcher matcher = Pattern.compile("^([1-9][0-9]*)([KMG])?$").matcher(amount); if (matcher.matches()) { String number = matcher.group(1); String suffix = matcher.group(2); limit = new BigInteger(number); if (suffix != null) { switch (suffix) { case "K": limit = limit.multiply(BigInteger.valueOf(1024)); break; case "M": limit = limit.multiply(BigInteger.valueOf(1024 * 1024)); break; case "G": limit = limit.multiply(BigInteger.valueOf(1024 * 1024 * 1024)); break; default: System.err.println("Unrecognized suffix"); System.exit(1); } } hasLimit = true; } else { System.err.println("Unrecognized amount " + amount); System.exit(1); } } else if (args.length > 1) { System.err.println("Unrecognized parameters " + Arrays.toString(args)); System.exit(1); } Fortuna fortuna = Fortuna.createInstance(); final BigInteger chunk = BigInteger.valueOf(4 * 1024); while (!hasLimit || limit.compareTo(BigInteger.ZERO) > 0) { final byte[] buffer; if (hasLimit) { if (chunk.compareTo(limit) < 0) { buffer = new byte[chunk.intValue()]; limit = limit.subtract(chunk); } else { buffer = new byte[limit.intValue()]; limit = BigInteger.ZERO; } } else { buffer = new byte[chunk.intValue()]; } fortuna.nextBytes(buffer); System.out.write(buffer); } fortuna.shutdown(); } }
package com.sematext.in; import com.sun.mail.imap.IMAPMessage; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.configuration.SystemConfiguration; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.mail.Address; import javax.mail.internet.InternetAddress; public class EmailExtractor { private static final Logger LOG = LoggerFactory.getLogger(EmailExtractor.class); public static void main(String[] args) throws ConfigurationException { Options options = buildOptions(); CommandLineParser parser = new DefaultParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption("help") || (!line.hasOption("include") && !line.hasOption("enclude")) ) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("EmailExtractor", options); return; } EmailExtractor extractor = new EmailExtractor(); extractor.extract(line.getOptionValue("include"), line.getOptionValue("exclude")); } catch (ParseException exp) { LOG.error("Parsing failed. Reason: " + exp.getMessage()); } } private static Options buildOptions() { Options options = new Options(); Option help = Option.builder("h").longOpt("help").desc("Help").required(false).build(); Option includeFolders = Option.builder("i").longOpt("include").desc("regular expression to include folders") .hasArg().required(false).build(); Option excludeFolders = Option.builder("e").longOpt("exclude").desc("regular expression to exclude folders") .hasArg().required(false).build(); options.addOption(includeFolders).addOption(excludeFolders).addOption(help); return options; } private void extract(String include, String exclude) throws ConfigurationException { String[] includes = include == null ? new String[0] : include.split(","); String[] excludes = exclude == null ? new String[0] : exclude.split(","); CompositeConfiguration config = new CompositeConfiguration(); config.addConfiguration(new SystemConfiguration()); config.addConfiguration(new PropertiesConfiguration("config.properties")); String[] solrKeywords = config.getStringArray("solr.keywords"); String[] esKeywords = config.getStringArray("es.keywords"); IMapFetcher fetcher = new IMapFetcher(config, includes, excludes); if (!fetcher.connectToMailBox()) { LOG.error("Can't connect to mailbox"); return; } StringBuilder sb = new StringBuilder(); while (fetcher.hasNext()) { IMAPMessage mail = fetcher.next(); try { sb.setLength(0); sb.append(mail.getSubject()); sb.append(" "); fetcher.getPartContent(mail, sb); String content = sb.toString().toLowerCase(); int solrCount = 0; int esCount = 0; for (String keyword : solrKeywords) { solrCount += StringUtils.countMatches(content, keyword.toLowerCase()); } for (String keyword : esKeywords) { esCount += StringUtils.countMatches(content, keyword.toLowerCase()); } if (esCount == 0 && solrCount == 0) { continue; } if (esCount > solrCount) { for (Address address : mail.getFrom()) { InternetAddress from = (InternetAddress)address; System.out.println("from " + from.getAddress() + " ES " + fetcher.getFolder()); } /*for (Address address : mail.getAllRecipients()) { InternetAddress to = (InternetAddress)address; System.out.println("to " + ((InternetAddress)to).getAddress() + " ES " + fetcher.getFolder()); }*/ } else { for (Address address : mail.getFrom()) { InternetAddress from = (InternetAddress)address; System.out.println("from " + from.getAddress() + " Solr " + fetcher.getFolder()); } /*for (Address address : mail.getAllRecipients()) { InternetAddress to = (InternetAddress)address; System.out.println("to " + ((InternetAddress)to).getAddress() + " Solr " + fetcher.getFolder()); }*/ } } catch (Exception e) { LOG.error("Can't read content from email", e); } } fetcher.disconnectFromMailBox(); } }
package com.herocc.bukkit.core.api; import com.herocc.bukkit.core.Core; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class FreezeAPI { private final Core plugin; public FreezeAPI(Core plugin) { this.plugin = plugin; } PotionEffect noJump = PotionEffectType.JUMP.createEffect(999999, 128); // 128 = -1, prevents jumping public static List<UUID> frozen = new ArrayList<>(); public void unfreezePlayer(Player player){ player.setWalkSpeed(0.2F); player.removePotionEffect(PotionEffectType.JUMP); frozen.remove(player.getUniqueId()); } public void freezePlayer(Player player){ player.setWalkSpeed(0); player.addPotionEffect(noJump); frozen.add(player.getUniqueId()); } public void unfreezeAll(Boolean alert) { if (frozen.size() != 0) { int unfrozenPlayers = 0; plugin.getLogger().info("Unfreezing all players..."); for (UUID uuid : frozen) { unfrozenPlayers++; Player player = plugin.getServer().getPlayer(uuid); unfreezePlayer(player); plugin.getLogger().fine("Unfroze " + player.getDisplayName()); if (alert) { player.sendMessage(ChatColor.GREEN + "All players are now unfrozen!"); } } plugin.getLogger().info(unfrozenPlayers + " players unfrozen!"); } } }
package com.wacai.sdk.jtr; import com.google.common.io.Files; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.HandlerWrapper; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class UrlRemapping extends HandlerWrapper { private final File file; private final List<Substitute> substitutes; public UrlRemapping(File file) { this.file = file; this.substitutes = new ArrayList<>(); } @Override protected void doStart() throws Exception { load(); super.doStart(); } @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { for (Substitute sub : substitutes) { try { String replaced = sub.apply(target); baseRequest.setPathInfo(replaced); super.handle(replaced, baseRequest, request, response); return; } catch (NotMatchingException ignore) { } } super.handle(target, baseRequest, request, response); } void load() throws IOException { final List<String> lines = Files.readLines(file, Charset.forName("UTF-8")); for (String line : lines) { final String[] split = line.split("\\s+", 2); substitutes.add(new Substitute(Pattern.compile(split[0]), split[1])); } } static class Substitute { private final Pattern regex; private final String replacement; public Substitute(Pattern regex, String replacement) { this.regex = regex; this.replacement = replacement; } String apply(String input) { final Matcher matcher = regex.matcher(input); if (matcher.matches()) return matcher.replaceAll(replacement); throw new NotMatchingException(); } } private static class NotMatchingException extends RuntimeException { @Override public synchronized Throwable fillInStackTrace() { return this; } } }
package crazypants.enderio; import java.io.IOException; import java.util.List; import javax.annotation.Nonnull; import javax.xml.stream.XMLStreamException; import com.enderio.core.common.vecmath.Vector4f; import crazypants.enderio.config.Config; import crazypants.enderio.config.recipes.InvalidRecipeConfigException; import crazypants.enderio.config.recipes.RecipeFactory; import crazypants.enderio.config.recipes.xml.Recipes; import crazypants.enderio.diagnostics.DebugCommand; import crazypants.enderio.item.darksteel.DarkSteelRecipeManager; import crazypants.enderio.sound.SoundRegistry; import net.minecraft.command.CommandHandler; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.MobEffects; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.potion.PotionEffect; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.event.FMLInterModComms; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; import net.minecraftforge.fml.common.gameevent.TickEvent.ServerTickEvent; public class CommonProxy { protected long serverTickCount = 0; protected long clientTickCount = 0; protected final TickTimer tickTimer = new TickTimer(); public CommonProxy() { } public World getClientWorld() { return null; } public EntityPlayer getClientPlayer() { return null; } public double getReachDistanceForPlayer(EntityPlayer entityPlayer) { return 5; } public void loadIcons() { } public void preInit() { if (Loader.isModLoaded("theoneprobe")) { FMLInterModComms.sendFunctionMessage("theoneprobe", "getTheOneProbe", "crazypants.enderio.integration.top.TOPCompatibility"); } } private static final String[] RECIPE_FILES = { "aliases", "materials", "items", "machines" }; public void init() { MinecraftForge.EVENT_BUS.register(tickTimer); SoundRegistry.init(); MinecraftForge.EVENT_BUS.register(DarkSteelRecipeManager.instance); if (Config.registerRecipes) { for (String filename : RECIPE_FILES) { try { Recipes recipes = RecipeFactory.readFile(new Recipes(), "recipes", "recipe_" + filename); if (recipes.isValid()) { recipes.enforceValidity(); recipes.register(); } else { throw new InvalidRecipeConfigException("Recipes config file recipe_" + filename + ".xml is empty or invalid!"); } } catch (InvalidRecipeConfigException e) { Log.error("Failed to read recipe config file " + filename + "_core.xml or " + filename + "_user.xml\n\n\n\n" + "\n=======================================================================" + "\n== FATAL ERROR ========================================================" + "\n=======================================================================" + "\n== Cannot register recipes as configured. This means that either ==" + "\n== your custom config file has an error or another mod does bad ==" + "\n== things to vanilla items or the Ore Dictionary. ==" + "\n=======================================================================" + "\n== Bad file: " + filename + "_core.xml or " + filename + "_user.xml" + "\n=======================================================================" + "\n== Error: " + e.getMessage() + "\n=======================================================================" + "\n=======================================================================" + "\n== Note: To start the game anyway, you can disable recipe loading in ==" + "\n======== the Ender IO config file. However, then all of Ender IO's ==" + "\n======== crafting recipes will be missing. ==" + "\n=======================================================================" + "\n\n\n"); throw new RuntimeException("Recipes config file recipe_" + filename + ".xml is invalid: " + e.getMessage()); } catch (IOException e) { throw new RuntimeException("Error while reading recipes config file recipe_" + filename + ".xml: " + e.getMessage()); } catch (XMLStreamException e) { throw new RuntimeException("Recipes config file recipe_" + filename + ".xml is invalid: " + e.getMessage()); } } } registerCommands(); } protected void registerCommands() { ((CommandHandler) FMLCommonHandler.instance().getMinecraftServerInstance().getCommandManager()).registerCommand(DebugCommand.SERVER); } public long getTickCount() { return serverTickCount; } public boolean isAnEiInstalled() { return false; } public void setInstantConfusionOnPlayer(EntityPlayer ent, int duration) { ent.addPotionEffect(new PotionEffect(MobEffects.NAUSEA, duration, 1, true, true)); } protected void onServerTick() { ++serverTickCount; } protected void onClientTick() { } public final class TickTimer { @SubscribeEvent public void onTick(ServerTickEvent evt) { if(evt.phase == Phase.END) { onServerTick(); } } @SubscribeEvent public void onTick(ClientTickEvent evt) { if(evt.phase == Phase.END) { onClientTick(); } } } private static final String TEXTURE_PATH = ":textures/gui/23/"; private static final String TEXTURE_EXT = ".png"; public @Nonnull ResourceLocation getGuiTexture(String name) { return new ResourceLocation(EnderIO.DOMAIN + TEXTURE_PATH + name + TEXTURE_EXT); } public void markBlock(World worldObj, BlockPos pos, Vector4f color) { } public boolean isDedicatedServer() { return true; } public CreativeTabs getCreativeTab(ItemStack stack) { return null; } public void getSubItems(Item itemIn, CreativeTabs tab, List<ItemStack> subItems) { subItems.add(new ItemStack(itemIn)); } }
package de.ddb.pdc.metadata; import org.springframework.xml.xpath.XPathOperations; import org.w3c.dom.Node; import javax.xml.transform.dom.DOMSource; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; /** * Class to operate with xpath the DDB XML AIP request. */ public class ItemAipXml { private DOMSource domSource; private XPathOperations xpath; /** * Create new ItemAipXml Object for every DomSource. * The class is need to operate with xpath on the dom. * * @param domSource xml source in a dom * @param xpath use for xpath operations */ public ItemAipXml(DOMSource domSource, XPathOperations xpath) { this.domSource = domSource; this.xpath = xpath; } /** * Returns the title of the item. */ public String getTitle() { String title = xpath.evaluateAsString("//ctx:preview/ctx:title", domSource); if (title.equals("")) { return null; } return title; } /** * Returns the subtitle of the item. */ public String getSubtitle() { String subtitle = xpath.evaluateAsString("//ctx:preview/ctx:subtitle" , domSource); if (subtitle.equals("")) { return null; } return subtitle; } /** * Returns url to thumbnail of the item. */ public String getThumbnail() { String thumbnail = xpath.evaluateAsString("//ctx:preview/ctx:thumbnail/@href" , domSource); if (thumbnail.equals("")) { return null; } return thumbnail; } /** * Returns the published year. */ public int getPublishedYear() { String date = xpath.evaluateAsString("//dcterms:issued", domSource); try { return Integer.parseInt(MetadataUtils.useRegex(date,"\\d{4}" )); } catch (NumberFormatException e) { return -1; } } /** * Returns name of the institution. */ public String getInstitution() { String institution = xpath.evaluateAsString("//edm:dataProvider[1]" , domSource); if (institution.equals("")) { return null; } return institution; } public String getCCLicense() { String license = xpath.evaluateAsString( "//ore:Aggregation/edm:rights/@ns3:resource", domSource); if (isCCUri(license)) { String[] temp = license.split("/"); if ( temp.length > 4) { if (temp[3].equals("publicdomain")) { return "true"; } return temp[4]; } } return null; } private boolean isCCUri(String uri) { if (uri.isEmpty()) { return false; } try { URI ccUri = new URI(uri); return ccUri.getHost().equals("creativecommons.org"); } catch (URISyntaxException e) { return false; } } /** * Returns a list with the authors dnb urls. */ public List<String> getAuthorUrls() { List<String> authorUrls = new ArrayList<String>(); String xpathFacetRole = "//ctx:facet[@name='affiliate_fct_role_normdata']/ctx:value"; List<Node> nodes = xpath.evaluateAsNodeList(xpathFacetRole, domSource); for (Node node : nodes) { String value = node.getFirstChild().getTextContent(); if (value.endsWith("_1_affiliate_fct_involved")) { authorUrls.add(value.split("_")[0]); } } return authorUrls; } }
package de.sjanusch.date; import java.time.LocalDate; import java.time.ZoneId; import java.util.Calendar; import java.util.TimeZone; import javax.inject.Inject; public class DateFormatter { @Inject public DateFormatter() { } public String formatDate(final String input) { final Calendar calendar = getCalendar(input); LocalDate date = calendar.getTime().toInstant().atZone(ZoneId.of("Europe/Paris")).toLocalDate(); return date.toString(); } private Calendar getCalendar(final String time) { final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(Long.parseLong(time)); return cal; } }
package main.java.engine.objects.monster; import java.awt.geom.Point2D; import java.util.HashSet; import java.util.List; import jgame.JGPoint; import main.java.engine.objects.Exit; import main.java.engine.objects.TDObject; import main.java.engine.objects.monster.jgpathfinder.*; public abstract class Monster extends TDObject { public static final int MONSTER_CID = 1; /*public static final String HEALTH = "health"; public static final String SPEED = "speed"; public static final String MONEY_VALUE = "moneyValue"; public static final String ENTRANCE_LOCATION = "entrance"; public static final String EXIT_LOCATION = "exit";*/ protected double myHealth; protected double myMoveSpeed; protected double myMoneyValue; protected JGPathfinderInterface myPathFinder; protected Point2D myEntrance; protected Exit myExit; protected JGPath myPath; /* TODO: Clean up/move instance variables to appropriate concrete classes */ /** * * @param name * @param unique_id * @param x * @param y * @param collisionid * @param gfxname */ public Monster (//double x, //double y, Point2D entrance, Exit exit, List<Integer> blocked, double health, double moveSpeed, double rewardAmount, String graphic) { //TODO make factory add the spread between monsters in the same wave, and remove random from initial x,y super("monster", entrance.getX() + Math.random() * 100, entrance.getY() + Math.random() * 100, MONSTER_CID, graphic); myHealth = health; myMoveSpeed = moveSpeed; myMoneyValue = rewardAmount; myEntrance = entrance; myExit = exit; myPathFinder = new JGPathfinder(new JGTileMap(eng, null, new HashSet<Integer>(blocked)), new JGPathfinderHeuristic(), eng); // TODO: clean up JGPoint pathEntrance = new JGPoint(eng.getTileIndex(x, y)); // TODO: move into diff method JGPoint pathExit = new JGPoint(myExit.getCenterTile()); try { myPath = myPathFinder.getPath(pathEntrance, pathExit); } catch (NoPossiblePathException e) { e.printStackTrace(); } } @Override public void move () { if (myPath.peek() != null) { JGPoint waypoint = eng.getTileCoord(myPath.peek()); // TODO: refactor, quick implementation to test - jordan if (((int) (x + 10) >= waypoint.x && (int) (x - 10) <= waypoint.x) && ((int) (y + 10) >= waypoint.y && (int) (y - 10) <= waypoint.y)) { waypoint = myPath.getNext(); } xdir = Double.compare(waypoint.x, x); ydir = Double.compare(waypoint.y, y); setDirSpeed(xdir, ydir, myMoveSpeed); } else { setSpeed(0); } } /** * Check if this object has died and should be removed */ public boolean isDead () { return myHealth <= 0; } /** * Reduce the health of this object by a damage amount. * @param damage afflicting object's damage */ public void takeDamage (double damage) { myHealth -= damage; } public void reduceSpeed (double speed) { myMoveSpeed *= speed; } /** * Set the monster to be dead immediately, * effectively removing it from the game */ public void setDead() { myHealth = 0; myMoneyValue = 0; } /** * Get money value received upon death of this monster * @return */ public double getMoneyValue() { return myMoneyValue; } }
package com.matthewhatcher.vpnguard; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerPreLoginEvent; import org.bukkit.plugin.java.JavaPlugin; import com.matthewhatcher.vpnguard.Listeners.LoginListener; public class VPNGuard extends JavaPlugin { private VPNGuard instance; public LoginListener loginListener; @Override public void onEnable() { this.instance = this; loginListener = new LoginListener(this.instance); this.getServer().getPluginManager().registerEvents(loginListener, this.instance); super.onEnable(); } @Override public void onDisable() { super.onDisable(); } }
package es.tid.graphlib.sgd; import org.apache.giraph.Algorithm; import org.apache.giraph.aggregators.DoubleSumAggregator; import org.apache.giraph.graph.DefaultEdge; import org.apache.giraph.graph.Edge; import org.apache.giraph.master.DefaultMasterCompute; import org.apache.giraph.vertex.EdgeListVertex; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.IntWritable; import es.tid.graphlib.examples.MessageWrapper; import es.tid.graphlib.examples.SimpleMasterComputeVertex; import java.lang.Math; /** * Demonstrates the Pregel Stochastic Gradient Descent (SGD) implementation. */ @Algorithm( name = "Stochastic Gradient Descent (SGD)", description = "Minimizes the error in users preferences predictions" ) public class SgdGeneral extends EdgeListVertex<IntWritable, DoubleArrayListWritable, IntWritable, MessageWrapper>{ /** The convergence tolerance */ static double INIT=0.5; /** SGD vector size **/ static int SGD_VECTOR_SIZE=2; /** Regularization parameter */ static double LAMBDA= 0.005; /** Learning rate */ static double GAMMA=0.01; /** Number of supersteps */ static double ITERATIONS=10; /** Tolerance */ static double TOLERANCE = 0.3; /** Max rating */ static double MAX=5; /** Min rating */ static double MIN=0; /** Error */ public double err; /** Observed Value - Rating */ private double observed; /** Type of vertex * 0 for user, 1 for item */ private boolean item=false; /** RMSD Error */ private double rmsdErr=0d; /** Factor Error: it may be RMSD or L2NORM on initial&final vector */ public double err_factor=0d; /** Initial vector value to be used for the L2Norm case */ DoubleArrayListWritable initialValue = new DoubleArrayListWritable(); /** Aggregators to get values from the workers to the master */ public static final String RMSD_AGG = "rmsd.aggregator"; public void compute(Iterable<MessageWrapper> messages) { /** Counter of messages received - different from getNumEdges() * because a neighbor may not send a message */ int msgCounter = 0; /** Flag for checking if parameter for RMSD aggregator received */ boolean rmsdFlag = getContext().getConfiguration().getBoolean("sgd.aggregate", false); /** Flag for checking which termination factor to use: basic, rmsd, l2norm */ String factorFlag = getContext().getConfiguration().get("sgd.factor", "basic"); /** If it's the first round for users (superstep: 0) or * If it's the first round for items (superstep: 1) */ if (getSuperstep() < 2){ initLatentVector(); } /** First Superstep for items */ if (getSuperstep() == 1) { item=true; } System.out.println("******* Vertex: "+getId()+", superstep:"+getSuperstep()+", item:" + item + ", [" + getValue().get(0).get() + "," + getValue().get(1).get() + "]"); rmsdErr=0d; /*** For each message */ for (MessageWrapper message : messages) { msgCounter++; System.out.println(" [RECEIVE] from " + message.getSourceId().get() + " [" + message.getMessage().get(0) + "," + message.getMessage().get(1) + "]"); DefaultEdge<IntWritable, IntWritable> edge = new DefaultEdge<IntWritable, IntWritable>(); /** If first superstep for items --> store the rating given from user */ if (getSuperstep()==1) { observed = message.getMessage().get(message.getMessage().size()-1).get(); System.out.println("observed: " + observed); IntWritable sourceId = message.getSourceId(); edge.setTargetVertexId(sourceId); edge.setValue(new IntWritable((int) observed)); System.out.println(" Adding edge:" + edge); addEdge(edge); // Remove the last value from message - it's there for the 1st round message.getMessage().remove(message.getMessage().size()-1); } /*** Calculate error */ observed = (double)getEdgeValue(message.getSourceId()).get(); err = getError(getValue(), message.getMessage(), observed); /** user_vector = vertex_vector + * 2*GAMMA*(real_value - * dot_product(vertex_vector,other_vertex_vector))*other_vertex_vector + * LAMBDA * vertex_vector */ System.out.println("BEFORE: error = " + err + " vertex_vector= " + getValue()); runSgdAlgorithm(message.getMessage()); /*setValue(dotAddition(getValue(), numMatrixProduct((double) -GAMMA, (dotAddition(numMatrixProduct((double) err,message.getMessage()), numMatrixProduct((double) LAMBDA, getValue())))))); */ err = getError(getValue(), message.getMessage(),observed); System.out.println("AFTER: error = " + err + " vertex_vector = " + getValue()); /* If termination flag is set to RMSD or RMSD aggregator is true */ if (factorFlag.equals("rmsd") || rmsdFlag){ rmsdErr+= Math.pow(err, 2); System.out.println("rmsdErr: " + rmsdErr); } } // End of for each message // If basic factor specified if (factorFlag.equals("basic")){ err_factor=TOLERANCE+1; } // If RMSD aggregator flag is true if (rmsdFlag){ this.aggregate(RMSD_AGG, new DoubleWritable(rmsdErr)); } if (factorFlag.equals("rmsd")){ err_factor = getRMSD(msgCounter); System.out.println("myRMSD: " + err_factor + ", numEdges: " + msgCounter); } // If termination factor is set to L2NOrm if (factorFlag.equals("l2norm")){ err_factor = getL2Norm(initialValue, getValue()); System.out.println("NormVector: sqrt((initial[0]-final[0])^2 + (initial[1]-final[1])^2): " + err_factor); } if (getSuperstep()==0 || (err_factor > TOLERANCE && getSuperstep()<ITERATIONS)){ sendMsgs(); } // err_factor is used in the OutputFormat file. --> To print the error if (factorFlag.equals("basic")){ err_factor=err; } voteToHalt(); }//EofCompute /*** Initialize Vertex Latent Vector */ public void initLatentVector(){ for (int i=0; i<SGD_VECTOR_SIZE; i++) { getValue().add(new DoubleWritable((double)((int)(0.9/((double)(getId().get()+i+1))*100)))); } /** For L2Norm */ initialValue = getValue(); } /*** Modify Vertex Latent Vector based on SGD equation */ public void runSgdAlgorithm(DoubleArrayListWritable vvertex){ /** user_vector = vertex_vector + * 2*GAMMA*(real_value - * dot_product(vertex_vector,other_vertex_vector))*other_vertex_vector + * LAMBDA * vertex_vector */ DoubleArrayListWritable la, ra, ga = new DoubleArrayListWritable(); la = numMatrixProduct((double) LAMBDA, getValue()); ra = numMatrixProduct((double) err,vvertex); ga = numMatrixProduct((double) -GAMMA, (dotAddition(ra, la))); setValue(dotAddition(getValue(), ga)); } /*** Send messages to neighbours */ public void sendMsgs(){ /** Send to all neighbors a message*/ for (Edge<IntWritable, IntWritable> edge : getEdges()) { /** Create a message and wrap together the source id and the message */ MessageWrapper message = new MessageWrapper(); message.setSourceId(getId()); message.setMessage(getValue()); if (getSuperstep()==0) { message.getMessage().add(new DoubleWritable(edge.getValue().get())); } sendMessage(edge.getTargetVertexId(), message); System.out.println(" [SEND] to " + edge.getTargetVertexId() + " (rating: " + edge.getValue() + ")" + " [" + getValue().get(0) + "," + getValue().get(1) + "]"); // End of for each edge } } /*** Calculate the RMSD on the errors calculated by the current vertex */ public double getRMSD(int msgCounter){ return Math.sqrt(rmsdErr/msgCounter); } /*** Calculate the RMSD on the errors calculated by the current vertex */ public double getL2Norm(DoubleArrayListWritable valOld, DoubleArrayListWritable valNew){ double result=0; for (int i=0; i<valOld.size(); i++){ result += Math.pow((valOld.get(i).get() - valNew.get(i).get()),2); } System.out.println("L2norm: " + result); return Math.sqrt(result); } /*** Calculate the error: e=observed-predicted */ public double getError(DoubleArrayListWritable ma, DoubleArrayListWritable mb, double observed){ /*** Predicted value */ double predicted = dotProduct(ma,mb); predicted = Math.min(predicted, MAX); predicted = Math.max(predicted, MIN); return predicted-observed; } /*** Calculate the dot product of 2 vectors: vector1*vector2 */ public double dotProduct(DoubleArrayListWritable ma, DoubleArrayListWritable mb){ double result = 0d; for (int i=0; i<SGD_VECTOR_SIZE; i++){ result += (ma.get(i).get() * mb.get(i).get()); } return result; } /*** Calculate the dot addition of 2 vectors: vector1+vector2 */ public DoubleArrayListWritable dotAddition( DoubleArrayListWritable ma, DoubleArrayListWritable mb){ DoubleArrayListWritable result = new DoubleArrayListWritable(); for (int i=0; i<SGD_VECTOR_SIZE; i++){ result.add(new DoubleWritable(ma.get(i).get() + mb.get(i).get())); } return result; } /*** Calculate the product num*matirx */ public DoubleArrayListWritable numMatrixProduct(double num, DoubleArrayListWritable matrix){ DoubleArrayListWritable result = new DoubleArrayListWritable(); for (int i=0; i<SGD_VECTOR_SIZE; i++){ result.add(new DoubleWritable(num * matrix.get(i).get())); } return result; } /** * MasterCompute used with {@link SimpleMasterComputeVertex}. */ public static class MasterCompute extends DefaultMasterCompute { @Override public void compute() { double numRatings=0; double totalRMSD=0; if (getSuperstep()>1){ // In superstep=1 only half edges are created (users to items) if (getSuperstep()==2) numRatings = getTotalNumEdges(); else numRatings = getTotalNumEdges()/2; totalRMSD = Math.sqrt(((DoubleWritable)getAggregatedValue(RMSD_AGG)).get()/numRatings); System.out.println("Superstep: " + getSuperstep() + ", [Aggregator] Added Values: " + getAggregatedValue(RMSD_AGG) + " / " + numRatings + " = " + ((DoubleWritable)getAggregatedValue(RMSD_AGG)).get()/numRatings + " --> sqrt(): " + totalRMSD); getAggregatedValue(RMSD_AGG); if (totalRMSD < TOLERANCE){ System.out.println("HALT!"); haltComputation(); } } } // Eof Compute() @Override public void initialize() throws InstantiationException, IllegalAccessException { registerAggregator(RMSD_AGG, DoubleSumAggregator.class); } } }
package com.msgilligan.bitcoin.rpc; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.PasswordAuthentication; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; /** * JSON-RPC Client */ public class RPCClient { private URL serverURL; private HttpURLConnection connection; private ObjectMapper mapper; private long requestId; public RPCClient(RPCConfig config) { this(config.getUrl(), config.getUsername(), config.getPassword()); } public RPCClient(URL server, final String rpcuser, final String rpcpassword) { Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(rpcuser, rpcpassword.toCharArray()); } }); serverURL = server; requestId = 0; mapper = new ObjectMapper(); } public URL getServerURL() { return serverURL; } public Map<String, Object> send(Map<String, Object> request) throws IOException, JsonRPCException { openConnection(); OutputStream output = connection.getOutputStream(); String reqString = mapper.writeValueAsString(request); // System.out.println("Req json = " + reqString); try { mapper.writeValue(output, request); output.close(); } catch (IOException logOrIgnore) { System.out.println("Exception: " + logOrIgnore); } InputStream responseStream = null; int code = connection.getResponseCode(); String message = connection.getResponseMessage(); // System.out.println("Response code: " + code); if (code == 200) { try { responseStream = connection.getInputStream(); } catch (IOException e) { e.printStackTrace(); throw new JsonRPCException("IOException reading response stream", e); } } else { responseStream = connection.getErrorStream(); } String responseString = new Scanner(responseStream,"UTF-8").useDelimiter("\\A").next(); @SuppressWarnings("unchecked") Map<String, Object> responseMap = mapper.readValue(responseString, Map.class); if (code != 200) { String exceptionMessage = message; // Default to HTTP result message if (responseMap != null) { Map <String, Object> error = (Map <String, Object>) responseMap.get("error"); if (error != null) { // If there's a more specific message in the JSON use it instead. exceptionMessage = (String) error.get("message"); } } throw new JsonRPCStatusException(exceptionMessage, code, message, responseString, responseMap); } closeConnection(); return responseMap; } public Map<String, Object> send(String method, List<Object> params) throws IOException, JsonRPCException { Map<String, Object> request = new HashMap<String, Object>(); request.put("jsonrpc", "1.0"); request.put("method", method); request.put("id", Long.toString(requestId)); if (params != null) { params.removeAll(Collections.singleton(null)); // Remove null entries (should only be at end) } request.put("params", params); Map<String, Object> response = send(request); // assert response != null; // assert response.get("jsonrpc") != null; // assert response.get("jsonrpc").equals("2.0"); // assert response.get("id") != null; // assert response.get("id").equals(Long.toString(requestId++)); requestId++; return response; } public Object cliSend(String method, List<Object> params) throws IOException, JsonRPCException { Map<String, Object> response = send(method, params); return response.get("result"); } public Object cliSend(String method, Object... params) throws IOException, JsonRPCException { Map<String, Object> response = send(method, Arrays.asList(params)); return response.get("result"); } private void openConnection() throws IOException { connection = (HttpURLConnection) serverURL.openConnection(); connection.setDoOutput(true); // For writes connection.setRequestMethod("POST"); // connection.setRequestProperty("Accept-Charset", StandardCharsets.UTF_8.toString()); // connection.setRequestProperty("Content-Type", " application/json;charset=" + StandardCharsets.UTF_8.toString()); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setRequestProperty("Content-Type", "application/json;charset=" + "UTF-8"); connection.setRequestProperty("Connection", "close"); } private void closeConnection() { connection.disconnect(); } }
package io.jbrodriguez.react; import javax.annotation.Nullable; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.GuardedAsyncTask; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.WritableArray; import com.facebook.react.common.ReactConstants; // import com.facebook.react.modules.common.ModuleDataCleaner; import io.jbrodriguez.react.SQLiteManager; // public final class DBManager extends ReactContextBaseJavaModule implements ModuleDataCleaner.Cleanable { public final class DBManager extends ReactContextBaseJavaModule { private @Nullable SQLiteManager mDb; private boolean mShuttingDown = false; public DBManager(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "DBManager"; } @Override public void initialize() { super.initialize(); mShuttingDown = false; } @Override public void onCatalystInstanceDestroy() { mShuttingDown = true; if (mDb != null && mDb.isOpen()) { mDb.close(); mDb = null; } } @ReactMethod public void init(final String name, final Callback callback) { new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) { @Override protected void doInBackgroundGuarded(Void ...params) { // FLog.w(ReactConstants.TAG, "dbmanager.init.name=%s", name); mDb = new SQLiteManager(getReactApplicationContext(), name); mDb.init(); callback.invoke(); } }.execute(); } @ReactMethod public void query(final String sql, final ReadableArray values, final Callback callback) { new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) { @Override protected void doInBackgroundGuarded(Void ...params) { WritableArray data = Arguments.createArray(); // FLog.w(ReactConstants.TAG, "dbmanager.query.sql=%s", sql); // FLog.w(ReactConstants.TAG, "dbmanager.query.values.size()=%d", values.size()); try { data = mDb.query(sql, values); } catch(Exception e) { FLog.w(ReactConstants.TAG, "Exception in database query: ", e); callback.invoke(ErrorUtil.getError(null, e.getMessage()), null); } callback.invoke(null, data); } }.execute(); } @ReactMethod public void exec(final String sql, final ReadableArray values, final Callback callback) { new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) { @Override protected void doInBackgroundGuarded(Void ...params) { try { mDb.exec(sql, values); } catch(Exception e) { FLog.w(ReactConstants.TAG, "Exception in database exec: ", e); callback.invoke(ErrorUtil.getError(null, e.getMessage()), null); } callback.invoke(); } }.execute(); } @ReactMethod public void close(final Callback callback) { new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) { @Override protected void doInBackgroundGuarded(Void ...params) { try { mDb.close(); } catch(Exception e) { FLog.w(ReactConstants.TAG, "Exception in database close: ", e); callback.invoke(ErrorUtil.getError(null, e.getMessage()), null); } callback.invoke(); } }.execute(); } }
package com.ociweb.iot.hardware; import static com.ociweb.pronghorn.pipe.PipeWriter.publishWrites; import static com.ociweb.pronghorn.pipe.PipeWriter.tryWriteFragment; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ociweb.iot.hardware.HardConnection.ConnectionType; import com.ociweb.iot.hardware.Hardware; import com.ociweb.pronghorn.iot.i2c.impl.I2CNativeLinuxBacking; import com.ociweb.pronghorn.iot.schema.AcknowledgeSchema; import com.ociweb.pronghorn.iot.schema.GoSchema; import com.ociweb.pronghorn.iot.schema.I2CCommandSchema; import com.ociweb.pronghorn.pipe.DataInputBlobReader; import com.ociweb.pronghorn.pipe.DataOutputBlobWriter; import com.ociweb.pronghorn.pipe.Pipe; import com.ociweb.pronghorn.pipe.PipeReader; import com.ociweb.pronghorn.pipe.PipeWriter; import com.ociweb.pronghorn.pipe.RawDataSchema; import com.ociweb.pronghorn.stage.PronghornStage; import com.ociweb.pronghorn.stage.scheduling.GraphManager; import com.ociweb.pronghorn.iot.i2c.impl.I2CNativeLinuxBacking; public class I2CJFFIStage extends PronghornStage { private final Pipe<I2CCommandSchema>[] fromCommandChannels; //private final Pipe<RawDataSchema> toListener; private final Pipe<GoSchema> goPipe; //TODO: Change the Schema private final Pipe<AcknowledgeSchema> ackPipe; //private DataOutputBlobWriter<RawDataSchema> writeListener; private DataOutputBlobWriter<AcknowledgeSchema> writeAck; private DataInputBlobReader<I2CCommandSchema>[] readCommandChannels; private DataInputBlobReader<GoSchema> readGo; private Hardware hardware; private int goCount; private int ackCount; private int pipeIdx; private byte addr; private byte[] data; private static final Logger logger = LoggerFactory.getLogger(JFFIStage.class); private static I2CNativeLinuxBacking i2c; public I2CJFFIStage(GraphManager graphManager, Pipe<GoSchema> goPipe, Pipe<I2CCommandSchema>[] i2cPayloadPipes, Pipe<AcknowledgeSchema> ackPipe, Hardware hardware) { //add an I2CListenerPipe super(graphManager, join(join(goPipe), i2cPayloadPipes), join(ackPipe)); //TODO: does double join work? feels weird. //STORE OTHER FIELDS THAT WILL BE REQUIRED IN STARTUP //this.toListener = toListener; this.ackPipe = ackPipe; this.fromCommandChannels = i2cPayloadPipes; this.goPipe = goPipe; this.hardware = hardware; //this.writeListener = new DataOutputBlobWriter<RawDataSchema>(toListener); } @Override public void startup() { try{ this.readCommandChannels = new DataInputBlobReader[fromCommandChannels.length]; for (int i = 0; i < readCommandChannels.length; i++) { this.readCommandChannels[i] = new DataInputBlobReader<I2CCommandSchema>(this.fromCommandChannels[i]); } I2CJFFIStage.i2c = new I2CNativeLinuxBacking(hardware.getI2CConnector()); this.goCount = 0; this.ackCount = 0; this.pipeIdx = 0; this.data = new byte[0]; this.addr = 0; } catch (Throwable t) { throw new RuntimeException(t); } //call the super.startup() last to keep schedulers from getting too eager and starting early super.startup(); } @Override public void run() { while (PipeReader.tryReadFragment(goPipe)) { assert(PipeReader.isNewMessage(goPipe)) : "This test should only have one simple message made up of one fragment"; int msgIdx = PipeReader.getMsgIdx(goPipe); if(GoSchema.MSG_RELEASE_20== msgIdx){ assert(goCount>=0); goCount += PipeReader.readInt(goPipe, GoSchema.MSG_RELEASE_20_FIELD_COUNT_22); pipeIdx = PipeReader.readInt(goPipe, GoSchema.MSG_GO_10_FIELD_PIPEIDX_11); ackCount = goCount; System.out.println("Received Go Command "+goCount); assert(goCount>0); }else{ assert(msgIdx == -1); requestShutdown(); } PipeReader.releaseReadLock(goPipe); } while (goCount>0 && PipeReader.tryReadFragment(fromCommandChannels[pipeIdx])) { goCount assert(PipeReader.isNewMessage(fromCommandChannels[pipeIdx])) : "This test should only have one simple message made up of one fragment"; int msgIdx = PipeReader.getMsgIdx(fromCommandChannels[pipeIdx]); System.out.println("Inside the while"); if(I2CCommandSchema.MSG_COMMAND_1 == msgIdx){ readCommandChannels[pipeIdx].openHighLevelAPIField(I2CCommandSchema.MSG_COMMAND_1_FIELD_BYTEARRAY_2); try { addr = readCommandChannels[pipeIdx].readByte(); data = new byte[readCommandChannels[pipeIdx].readByte()]; //TODO: Nathan take out the trash ReadByteArray method? for (int i = 0; i < data.length; i++) { data[i]=readCommandChannels[pipeIdx].readByte(); } I2CJFFIStage.i2c.write(addr, data); System.out.println("writing to I2C bus"); } catch (IOException e) { logger.error(e.getMessage(), e); System.out.println("I failed"); } try { readCommandChannels[pipeIdx].close(); } catch (IOException e) { logger.error(e.getMessage(), e); System.out.println("I failed to close"); } }else{ System.out.println("Wrong Message index "+msgIdx); assert(msgIdx == -1); requestShutdown(); } PipeReader.releaseReadLock(fromCommandChannels[pipeIdx]); if(goCount==0 && ackCount!=0){ if (tryWriteFragment(ackPipe, AcknowledgeSchema.MSG_DONE_10)) { PipeWriter.writeInt(ackPipe, AcknowledgeSchema.MSG_DONE_10, 0); publishWrites(ackPipe); ackCount = goCount; System.out.println("Send Acknowledgement"); }else{ System.out.println("unable to write fragment"); } } } // for (int i = 0; i < this.hardware.digitalInputs.length; i++) { //TODO: This polls every attached input, are there intermittent inputs? // if(this.hardware.digitalInputs[i].type.equals(ConnectionType.GrovePi)){ // if (tryWriteFragment(toListener, RawDataSchema.MSG_CHUNKEDSTREAM_1)) { //TODO: Do we want to open and close pipe writer for every poll? // DataOutputBlobWriter.openField(writeListener); // try { // byte[] tempData = {}; // byte[] message = {0x01, 0x01, hardware.digitalInputs[i].connection, 0x00, 0x00};//TODO: This is GrovePi specific. Should it be in hardware? // i2c.write((byte) 0x04, message); // while(tempData.length == 0){ //TODO: Blocking call // i2c.read(hardware.digitalInputs[i].connection, 1); // writeListener.write(tempData); //TODO: Use some other Schema // } catch (IOException e) { // logger.error(e.getMessage(), e); // DataOutputBlobWriter.closeHighLevelField(writeListener, RawDataSchema.MSG_CHUNKEDSTREAM_1_FIELD_BYTEARRAY_2); // publishWrites(toListener); // }else{ // System.out.println("unable to write fragment"); // for (int i = 0; i < this.hardware.analogInputs.length; i++) { // if(this.hardware.analogInputs[i].type.equals(ConnectionType.GrovePi)){ // if (tryWriteFragment(toListener, RawDataSchema.MSG_CHUNKEDSTREAM_1)) { //TODO: Do we want to open and close pipe writer for every poll? // DataOutputBlobWriter.openField(writeListener); // try { // byte[] tempData = {}; // byte[] message = {0x01, 0x03, hardware.analogInputs[i].connection, 0x00, 0x00};//TODO: This is GrovePi specific. Should it be in hardware? // i2c.write((byte) 0x04, message); // while(tempData.length == 0){ //TODO: Blocking call // i2c.read(hardware.digitalInputs[i].connection, 1); // writeListener.write(tempData); //TODO: Use some other Schema // } catch (IOException e) { // logger.error(e.getMessage(), e); // DataOutputBlobWriter.closeHighLevelField(writeListener, RawDataSchema.MSG_CHUNKEDSTREAM_1_FIELD_BYTEARRAY_2); // publishWrites(toListener); // }else{ // System.out.println("unable to write fragment"); } @Override public void shutdown() { //if batching was used this will publish any waiting fragments //RingBuffer.publishAllWrites(output); try{ //PUT YOUR LOGIC HERE TO CLOSE CONNECTIONS FROM THE DATABASE OR OTHER SOURCE OF INFORMATION } catch (Throwable t) { throw new RuntimeException(t); } } }
package io.praesid.livestats; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.AtomicDouble; import javax.annotation.concurrent.ThreadSafe; import java.util.Arrays; import java.util.Collections; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.DoubleConsumer; import java.util.function.DoublePredicate; import java.util.function.Function; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.IntStream; @ThreadSafe public class LiveStats implements DoublePredicate, DoubleConsumer { private static final double[] DEFAULT_TILES = {0.5}; private final AtomicDouble minVal = new AtomicDouble(Double.MAX_VALUE); private final AtomicDouble maxVal = new AtomicDouble(Double.MIN_VALUE); private final AtomicDouble varM2 = new AtomicDouble(0); private final AtomicDouble kurtM4 = new AtomicDouble(0); private final AtomicDouble skewM3 = new AtomicDouble(0); private final AtomicInteger fullStatsCount = new AtomicInteger(0); private final AtomicDouble average = new AtomicDouble(0); private final AtomicInteger count = new AtomicInteger(0); private final double fullStatsProbability; private final ImmutableList<Quantile> tiles; /** * Constructs a LiveStats object * * @param fullStatsProbability the probability that any given item is considered for all available statistics * other items are only counted and considered for maximum and minimum. * values &lt; 0 disable full stats and values &gt; 1 always calculate full stats * @param p A list of quantiles to track (default {0.5}) */ public LiveStats(final double fullStatsProbability, final double... p) { this.fullStatsProbability = fullStatsProbability; tiles = Arrays.stream(p.length == 0 ? DEFAULT_TILES : p) .mapToObj(Quantile::new) .collect(Collector.of(ImmutableList::<Quantile>builder, Builder::add, (a, b) -> a.addAll(b.build()), Builder::build)); } /** * Adds another datum * * @param item the value to add */ @Override public void accept(final double item) { add(item); } /** * Adds another datum * * @param item the value to add * @return true if full stats were collected, false otherwise */ @Override public boolean test(final double item) { return add(item); } /** * Adds another datum * * @param item the value to add * @return true if full stats were collected, false otherwise */ public boolean add(double item) { double oldMin = minVal.get(); while (item < oldMin) { if (minVal.compareAndSet(oldMin, item)) { break; } oldMin = minVal.get(); } double oldMax = maxVal.get(); while (item > oldMax) { if (maxVal.compareAndSet(oldMax, item)) { break; } oldMax = maxVal.get(); } count.incrementAndGet(); if (ThreadLocalRandom.current().nextDouble() < fullStatsProbability) { tiles.forEach(tile -> tile.add(item)); final int myCount = fullStatsCount.incrementAndGet(); final double preDelta = item - average.get(); // This is wrong if it matters that post delta is relative to a different point in "time" than the pre delta final double postDelta = item - average.addAndGet(preDelta / myCount); final double d2 = postDelta * postDelta; //Variance(except for the scale) varM2.addAndGet(d2); final double d3 = d2 * postDelta; //Skewness skewM3.addAndGet(d3); final double d4 = d3 * postDelta; //Kurtosis kurtM4.addAndGet(d4); return true; } return false; } /** * @return a Map of quantile to approximate value */ public Map<Double, Double> quantiles() { final ImmutableMap.Builder<Double, Double> builder = ImmutableMap.builder(); for (final Quantile tile : tiles) { builder.put(tile.p, tile.quantile()); } return builder.build(); } public double maximum() { return maxVal.get(); } public double mean() { return average.get(); } public double minimum() { return minVal.get(); } public int num() { return count.get(); } public double variance() { return varM2.get() / fullStatsCount.get(); } public double kurtosis() { // k / (c * (v/c)^2) - 3 // k / (c * (v/c) * (v/c)) - 3 // k / (v * v / c) - 3 // k * c / (v * v) - 3 final double myVarM2 = varM2.get(); return kurtM4.get() * fullStatsCount.get() / (myVarM2 * myVarM2) - 3; } public double skewness() { // s / (c * (v/c)^(3/2)) // s / (c * (v/c) * (v/c)^(1/2)) // s / (v * sqrt(v/c)) // s * sqrt(c/v) / v final double myVarM2 = varM2.get(); return skewM3.get() * Math.sqrt(fullStatsCount.get() / myVarM2) / myVarM2; } @ThreadSafe private static class Quantile { private static final int LEN = 5; // dn and npos must be updated if this is changed private final double[] dn; // Immutable private final double[] npos; private final int[] pos; private final double[] heights; private int initialized = LEN; public final double p; /** * Constructs a single quantile object */ public Quantile(double p) { this.p = p; dn = new double[]{0, p / 2, p, (1 + p) / 2, 1}; npos = new double[]{1, 1 + 2 * p, 1 + 4 * p, 3 + 2 * p, 5}; pos = IntStream.range(1, LEN + 1).toArray(); heights = new double[LEN]; } /** * Adds another datum */ public synchronized void add(double item) { if (initialized < LEN) { heights[initialized] = item; initialized++; if (initialized == LEN) { Arrays.sort(heights); } return; } // find cell k final int k; if (item < heights[0]) { heights[0] = item; k = 1; } else if (item >= heights[LEN - 1]) { heights[LEN - 1] = item; k = 4; } else { int i = 1; // Linear search is fastest for small LEN while (item >= heights[i]) { i++; } k = i; } IntStream.range(k, pos.length).forEach(i -> pos[i]++); // increment all positions greater than k IntStream.range(0, npos.length).forEach(i -> npos[i] += dn[i]); adjust(); } private void adjust() { for (int i = 1; i < LEN - 1; i++) { final int n = pos[i]; final double q = heights[i]; final double d0 = npos[i] - n; if ((d0 >= 1 && pos[i + 1] - n > 1) || (d0 <= -1 && pos[i - 1] - n < -1)) { final int d = (int)Math.signum(d0); final double qp1 = heights[i + 1]; final double qm1 = heights[i - 1]; final int np1 = pos[i + 1]; final int nm1 = pos[i - 1]; final double qn = calcP2(qp1, q, qm1, d, np1, n, nm1); if (qm1 < qn && qn < qp1) { heights[i] = qn; } else { // use linear form heights[i] = q + d * (heights[i + d] - q) / (pos[i + d] - n); } pos[i] = n + d; } } } public synchronized double quantile() { if (initialized == LEN) { return heights[2]; } else { Arrays.sort(heights); // Not fully initialized, probably not in order // make sure we don't overflow on p == 1 or underflow on p == 0 return heights[Math.min(Math.max(initialized - 1, 0), (int)(initialized * p))]; } } } private static double calcP2(double qp1, double q, double qm1, double d, double np1, double n, double nm1) { final double outer = d / (np1 - nm1); final double innerLeft = (n - nm1 + d) * (qp1 - q) / (np1 - n); final double innerRight = (np1 - n - d) * (q - qm1) / (n - nm1); return q + outer * (innerLeft + innerRight); } private static double triangular(double low, double high, double mode) { final double base = ThreadLocalRandom.current().nextDouble(); final double pivot = (mode - low) / (high - low); if (base <= pivot) { return low + Math.sqrt(base * (high - low) * (mode - low)); } else { return high - Math.sqrt((1 - base) * (high - low) * (high - mode)); } } private static double bimodal(double low1, double high1, double mode1, double low2, double high2, double mode2) { final boolean toss = ThreadLocalRandom.current().nextBoolean(); return toss ? triangular(low1, high1, mode1) : triangular(low2, high2, mode2); } private static double exponential(double lambda) { return Math.log(1 - ThreadLocalRandom.current().nextDouble()) / -lambda; } private static void output(final double[] data, final LiveStats stats, final String name) { Arrays.sort(data); final Map<Double, Double> tiles = stats.quantiles(); final Map<Double, Double> expected = tiles .keySet().stream().collect(Collectors.toMap(Function.identity(), x -> data[(int)(data.length * x)])); final double et = expected .entrySet().stream() .mapToDouble(e -> Math.abs(tiles.get(e.getKey()) - e.getValue()) / Math.abs(e.getValue())) .sum(); final double pe = 100 * et / data.length; final double avg = Arrays.stream(data).sum() / data.length; final double s2 = Arrays.stream(data).map(x -> Math.pow(x - avg, 2)).sum(); final double var = s2 / data.length; final double v_pe = 100.0 * Math.abs(stats.variance() - var) / Math.abs(var); final double avg_pe = 100.0 * Math.abs(stats.mean() - avg) / Math.abs(avg); System.out.println(String.format("%s: Avg%%E %e Var%%E %e Quant%%E %e, Kurtosis %e, Skewness %e", name, avg_pe, v_pe, pe, stats.kurtosis(), stats.skewness())); } public static void main(String... args) { final int count = Integer.parseInt(args[0]); final double[] tiles = {0.25,0.5,0.75}; final LiveStats median = new LiveStats(1, tiles); final double[] test = {0.02,0.15,0.74,3.39,0.83,22.37,10.15,15.43,38.62,15.92,34.60, 10.28,1.47,0.40,0.05,11.39,0.27,0.42,0.09,11.37}; Arrays.stream(test).forEach(median); output(test, median, "Test"); final LiveStats uniform = new LiveStats(1, tiles); final LiveStats uniform50 = new LiveStats(.5, tiles); final double[] ux = IntStream.range(0, count).asDoubleStream().toArray(); Collections.shuffle(Arrays.asList(ux), ThreadLocalRandom.current()); // Shuffles the underlying array Arrays.stream(ux).peek(uniform).forEach(uniform50); output(ux, uniform, "Uniform"); output(ux, uniform50, "Uniform50"); final LiveStats expovar = new LiveStats(1, tiles); final double[] ex = IntStream.range(0, count) .mapToDouble(i -> exponential(1.0 / 435)) .peek(expovar).toArray(); output(ex, expovar, "Expovar"); final LiveStats triangular = new LiveStats(1, tiles); final double[] tx = IntStream.range(0, count) .mapToDouble(i -> triangular(-1000 * count / 10, 1000 * count / 10, 100)) .peek(triangular).toArray(); output(tx, triangular, "Triangular"); final LiveStats bimodal = new LiveStats(1, tiles); final LiveStats bimodal50 = new LiveStats(.5, tiles); final double[] bx = IntStream.range(0, count) .mapToDouble(i -> bimodal(0, 1000, 500, 500, 1500, 1400)) .peek(bimodal).peek(bimodal50).toArray(); output(bx, bimodal, "Bimodal"); output(bx, bimodal50, "Bimodal50"); } }
package com.plivo.api.models.call; import com.plivo.api.models.base.ListResponse; import com.plivo.api.models.base.Lister; import com.plivo.api.util.PropertyFilter; public class CallLister extends Lister<Call> { private String subaccount; private CallDirection callDirection; private String fromNumber; private String toNumber; private String parentCallUuid; private String hangupSource; private Integer hangupCauseCode; // TODO XXX PropertyFilter private PropertyFilter<Long> billDuration; private PropertyFilter<Long> endTime; public String subaccount() { return this.subaccount; } public CallDirection callDirection() { return this.callDirection; } public String fromNumber() { return this.fromNumber; } public String toNumber() { return this.toNumber; } public String parentCallUuid(){ return this.parentCallUuid; } public String hangupSource() { return hangupSource; } public Integer hangupCauseCode() { return hangupCauseCode; } public PropertyFilter<Long> billDuration() { return this.billDuration; } public PropertyFilter<Long> endTime() { return this.endTime; } /** * @param subaccount The id of the subaccount, if call details of the subaccount are needed. */ public CallLister subaccount(final String subaccount) { this.subaccount = subaccount; return this; } /** * @param callDirection Filter the results by call direction. The valid inputs are inbound and * outbound. */ public CallLister callDirection(final CallDirection callDirection) { this.callDirection = callDirection; return this; } /** * @param fromNumber Filter the results by the number from where the call originated. */ public CallLister fromNumber(final String fromNumber) { this.fromNumber = fromNumber; return this; } /** * @param toNumber Filter the results by the number to which the call was made. */ public CallLister toNumber(final String toNumber) { this.toNumber = toNumber; return this; } /** * @param parentCallUuid Filter the results by the number to which the call was made. */ public CallLister parentCallUuid(final String parentCallUuid) { this.parentCallUuid = parentCallUuid; return this; } /** * @param hangupSource Filter the results by hangup source. */ public CallLister hangupSource(String hangupSource) { this.hangupSource = hangupSource; return this; } /** * @param hangupCauseCode Filter the results by hangup cause code. */ public CallLister hangupCauseCode(Integer hangupCauseCode) { this.hangupCauseCode = hangupCauseCode; return this; } /** * @param billDuration Filter the results according to billed duration. */ public CallLister billDuration( final PropertyFilter<Long> billDuration) { this.billDuration = billDuration; return this; } /** * @param endTime Filter out calls according to the time of completion. */ public CallLister endTime(final PropertyFilter<Long> endTime) { this.endTime = endTime; return this; } @Override protected retrofit2.Call<ListResponse<Call>> obtainCall() { return client().getApiService().callList(client().getAuthId(), toMap()); } }
package io.sigpipe.sing.stat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class Reservoir<T> { private int count; private int size; private List<Entry> reservoir; private Random random = new Random(); private class Entry implements Comparable<Entry> { public double key; public T value; public int id; public Entry(double key, T value) { this.key = key; this.value = value; } @Override public int compareTo(Entry that) { return Double.compare(this.key, that.key); } @Override public String toString() { return id + " [" + key + "] -> " + value; } } public Reservoir(int size) { this.size = size; reservoir = new ArrayList<>(size); } public void put(Iterable<T> items) { for (T item : items) { put(item); } } public void put(T item) { double key = random.nextDouble(); Entry e = new Entry(key, item); e.id = count; if (count < this.size()) { reservoir.add(count, e); } else { if (key < ((double) this.size() / (count + 1))) { int position = random.nextInt(this.size()); reservoir.set(position, e); } } count++; } public void merge(Reservoir<T> that, int size) { List<Entry> combinedEntries = new ArrayList<>(size); combinedEntries.addAll(this.reservoir); combinedEntries.addAll(that.reservoir); Collections.sort(combinedEntries); this.reservoir = new ArrayList<>(size); for (int i = 0; i < size; ++i) { this.reservoir.add(combinedEntries.get(i)); } } public void merge(Reservoir<T> that) { merge(that, this.size()); } public int size() { return this.size; } public List<Entry> entries() { return new ArrayList<>(this.reservoir); } public List<T> samples() { List<T> l = new ArrayList<>(this.size()); for (Entry e : this.reservoir) { l.add(e.value); } return l; } public double[] keys() { double[] k = new double[this.size()]; for (int i = 0; i < this.size(); ++i) { k[i] = this.reservoir.get(i).key; } return k; } public static void main(String[] args) { Reservoir<Double> rs = new Reservoir<>(20); Random r = new Random(); r.doubles(1000).filter(val -> val < 0.5).forEach(rs::put); RunningStatistics stats = new RunningStatistics(); for (double d : rs.samples()) { System.out.println(d); stats.put(d); } System.out.println(stats); for (double d : rs.keys()) { System.out.println(d); } } }
package com.rapportive.storm.spout; import java.io.IOException; import java.util.Map; import org.apache.log4j.Logger; import com.rabbitmq.client.AMQP.Queue; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.QueueingConsumer; import com.rapportive.storm.amqp.QueueDeclaration; import backtype.storm.spout.Scheme; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.IRichSpout; import backtype.storm.topology.OutputFieldsDeclarer; /** * Spout to feed messages into Storm from an AMQP queue. Each message routed * to the queue will be emitted as a Storm tuple. The message will be acked or * rejected once the topology has respectively fully processed or failed the * corresponding tuple. * * <p><strong>N.B.</strong> if you need to guarantee all messages are reliably * processed, you should have AMQPSpout consume from a queue that is * <em>not</em> set as 'exclusive' or 'auto-delete': otherwise if the spout * task crashes or is restarted, the queue will be deleted and any messages in * it lost, as will any messages published while the task remains down. See * {@link com.rapportive.storm.amqp.SharedQueueWithBinding} to declare a shared * queue that allows for guaranteed processing. (For prototyping, an * {@link com.rapportive.storm.amqp.ExclusiveQueueWithBinding} may be * simpler to manage.)</p> * * <p>This consumes messages from AMQP asynchronously, so it may receive * messages before Storm requests them as tuples; therefore it buffers messages * in an internal queue. To avoid this buffer growing large and consuming too * much RAM, set {@link #CONFIG_PREFETCH_COUNT}.</p> * * <p>This spout can be distributed among multiple workers, depending on the * queue declaration: see {@link QueueDeclaration#isParallelConsumable}.</p> * * @see QueueDeclaration * @see com.rapportive.storm.amqp.SharedQueueWithBinding * @see com.rapportive.storm.amqp.ExclusiveQueueWithBinding * * @author Sam Stokes (sam@rapportive.com) */ public class AMQPSpout implements IRichSpout { private static final long serialVersionUID = 11258942292629263L; private static final Logger log = Logger.getLogger(AMQPSpout.class); /** * Storm config key to set the AMQP basic.qos prefetch-count parameter. * Defaults to 100. * * <p>This caps the number of messages outstanding (i.e. unacked) at a time * that will be sent to each spout worker. Increasing this will improve * throughput if the network roundtrip time to the AMQP broker is * significant compared to the time for the topology to process each * message; this will also increase the RAM requirements as the internal * message buffer grows.</p> * * <p>AMQP allows a prefetch-count of zero, indicating unlimited delivery, * but that is not allowed here to avoid unbounded buffer growth.</p> */ public static final String CONFIG_PREFETCH_COUNT = "amqp.prefetch.count"; private static final long DEFAULT_PREFETCH_COUNT = 100; /** * Time in milliseconds to wait for a message from the queue if there is * no message ready when the topology requests a tuple (via * {@link #nextTuple()}). */ public static final long WAIT_FOR_NEXT_MESSAGE = 1L; private final String amqpHost; private final int amqpPort; private final String amqpUsername; private final String amqpPassword; private final String amqpVhost; private final QueueDeclaration queueDeclaration; private final Scheme serialisationScheme; private transient Connection amqpConnection; private transient Channel amqpChannel; private transient QueueingConsumer amqpConsumer; private transient String amqpConsumerTag; private SpoutOutputCollector collector; /** * Create a new AMQP spout. When * {@link #open(Map, TopologyContext, SpoutOutputCollector)} is called, it * will declare a queue according to the specified * <tt>queueDeclaration</tt>, subscribe to the queue, and start consuming * messages. It will use the provided <tt>scheme</tt> to deserialise each * AMQP message into a Storm tuple. * * @param host hostname of the AMQP broker node * @param port port number of the AMQP broker node * @param username username to log into to the broker * @param password password to authenticate to the broker * @param vhost vhost on the broker * @param queueDeclaration declaration of the queue / exchange bindings * @param scheme {@link backtype.storm.spout.Scheme} used to deserialise * each AMQP message into a Storm tuple */ public AMQPSpout(String host, int port, String username, String password, String vhost, QueueDeclaration queueDeclaration, Scheme scheme) { this.amqpHost = host; this.amqpPort = port; this.amqpUsername = username; this.amqpPassword = password; this.amqpVhost = vhost; this.queueDeclaration = queueDeclaration; this.serialisationScheme = scheme; } /** * Acks the message with the AMQP broker. */ @Override public void ack(Object msgId) { if (msgId instanceof Long) { final long deliveryTag = (Long) msgId; if (amqpChannel != null) { try { amqpChannel.basicAck(deliveryTag, false /* not multiple */); } catch (IOException e) { log.warn("Failed to ack delivery-tag " + deliveryTag, e); } } } else { log.warn(String.format("don't know how to ack(%s: %s)", msgId.getClass().getName(), msgId)); } } /** * Cancels the queue subscription, and disconnects from the AMQP broker. */ @Override public void close() { try { if (amqpChannel != null) { if (amqpConsumerTag != null) { amqpChannel.basicCancel(amqpConsumerTag); } amqpChannel.close(); } } catch (IOException e) { log.warn("Error closing AMQP channel", e); } try { if (amqpConnection != null) { amqpConnection.close(); } } catch (IOException e) { log.warn("Error closing AMQP connection", e); } } /** * Tells the AMQP broker to drop (Basic.Reject) the message. * * <p><strong>N.B.</strong> this does <em>not</em> requeue the message: * failed messages will simply be dropped. This is to prevent infinite * redelivery in the event of non-transient failures (e.g. malformed * messages). However it means that messages will <em>not</em> be retried * in the event of transient failures.</p> */ @Override public void fail(Object msgId) { if (msgId instanceof Long) { final long deliveryTag = (Long) msgId; if (amqpChannel != null) { try { amqpChannel.basicReject(deliveryTag, false /* don't requeue */); } catch (IOException e) { log.warn("Failed to reject delivery-tag " + deliveryTag, e); } } } else { log.warn(String.format("don't know how to reject(%s: %s)", msgId.getClass().getName(), msgId)); } } /** * Emits the next message from the queue as a tuple. * * <p>If no message is ready to emit, this will wait a short time * ({@link #WAIT_FOR_NEXT_MESSAGE}) for one to arrive on the queue, * to avoid a tight loop in the spout worker.</p> */ @Override public void nextTuple() { if (amqpConsumer != null) { try { final QueueingConsumer.Delivery delivery = amqpConsumer.nextDelivery(WAIT_FOR_NEXT_MESSAGE); if (delivery == null) return; final long deliveryTag = delivery.getEnvelope().getDeliveryTag(); final byte[] message = delivery.getBody(); collector.emit(serialisationScheme.deserialize(message), deliveryTag); /* * TODO what to do about malformed messages? Skip? * Avoid infinite retry! * Maybe we should output them on a separate stream. */ } catch (InterruptedException e) { // interrupted while waiting for message, big deal } } } /** * Connects to the AMQP broker, declares the queue and subscribes to * incoming messages. */ @Override public void open(@SuppressWarnings("rawtypes") Map config, TopologyContext context, SpoutOutputCollector collector) { Long prefetchCount = (Long) config.get(CONFIG_PREFETCH_COUNT); if (prefetchCount == null) { log.info("Using default prefetch-count"); prefetchCount = DEFAULT_PREFETCH_COUNT; } else if (prefetchCount < 1) { throw new IllegalArgumentException(CONFIG_PREFETCH_COUNT + " must be at least 1"); } try { this.collector = collector; setupAMQP(prefetchCount.intValue()); } catch (IOException e) { log.error("AMQP setup failed", e); } } private void setupAMQP(int prefetchCount) throws IOException { final ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost(amqpHost); connectionFactory.setPort(amqpPort); connectionFactory.setUsername(amqpUsername); connectionFactory.setPassword(amqpPassword); connectionFactory.setVirtualHost(amqpVhost); this.amqpConnection = connectionFactory.newConnection(); this.amqpChannel = amqpConnection.createChannel(); log.info("Setting basic.qos prefetch-count to " + prefetchCount); amqpChannel.basicQos(prefetchCount); final Queue.DeclareOk queue = queueDeclaration.declare(amqpChannel); final String queueName = queue.getQueue(); log.info("Consuming queue " + queueName); this.amqpConsumer = new QueueingConsumer(amqpChannel); this.amqpConsumerTag = amqpChannel.basicConsume(queueName, false /* no auto-ack */, amqpConsumer); } /** * Declares the output fields of this spout according to the provided * {@link backtype.storm.spout.Scheme}. */ @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(serialisationScheme.getOutputFields()); } /** * This spout can be distributed among multiple workers if the * {@link QueueDeclaration} supports it. * * @see QueueDeclaration#isParallelConsumable() */ @Override public boolean isDistributed() { return queueDeclaration.isParallelConsumable(); } }
package io.tus.java.client; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; /** * This class is used for doing the actual upload of the files. Instances are returned by * {@link TusClient#createUpload(TusUpload)}, {@link TusClient#createUpload(TusUpload)} and * {@link TusClient#resumeOrCreateUpload(TusUpload)}. * <br> * After obtaining an instance you can upload a file by following these steps: * <ol> * <li>Upload a chunk using {@link #uploadChunk()}</li> * <li>Optionally get the new offset ({@link #getOffset()} to calculate the progress</li> * <li>Repeat step 1 until the {@link #uploadChunk()} returns -1</li> * <li>Close HTTP connection and InputStream using {@link #finish()} to free resources</li> * </ol> */ public class TusUploader { private URL uploadURL; private TusInputStream input; private long offset; private TusClient client; private TusUpload upload; private byte[] buffer; private int requestPayloadSize = 10 * 1024 * 1024; private int bytesRemainingForRequest; private HttpURLConnection connection; private OutputStream output; /** * Begin a new upload request by opening a PATCH request to specified upload URL. After this * method returns a connection will be ready and you can upload chunks of the file. * * @param client Used for preparing a request ({@link TusClient#prepareConnection(HttpURLConnection)} * @param uploadURL URL to send the request to * @param input Stream to read (and seek) from and upload to the remote server * @param offset Offset to read from * @throws IOException Thrown if an exception occurs while issuing the HTTP request. */ public TusUploader(TusClient client, TusUpload upload, URL uploadURL, TusInputStream input, long offset) throws IOException { this.uploadURL = uploadURL; this.input = input; this.offset = offset; this.client = client; this.upload = upload; input.seekTo(offset); setChunkSize(2 * 1024 * 1024); } private void openConnection() throws IOException, ProtocolException { // Only open a connection, if we have none open. if(connection != null) { return; } bytesRemainingForRequest = requestPayloadSize; input.mark(requestPayloadSize); connection = (HttpURLConnection) uploadURL.openConnection(); client.prepareConnection(connection); connection.setRequestProperty("Upload-Offset", Long.toString(offset)); connection.setRequestProperty("Content-Type", "application/offset+octet-stream"); connection.setRequestProperty("Expect", "100-continue"); try { connection.setRequestMethod("PATCH"); // Check whether we are running on a buggy JRE } catch (java.net.ProtocolException pe) { connection.setRequestMethod("POST"); connection.setRequestProperty("X-HTTP-Method-Override", "PATCH"); } connection.setDoOutput(true); connection.setChunkedStreamingMode(0); try { output = connection.getOutputStream(); } catch(java.net.ProtocolException pe) { // If we already have a response code available, our expectation using the "Expect: 100- // continue" header failed and we should handle this response. if(connection.getResponseCode() != -1) { finish(); } throw pe; } } /** * Sets the used chunk size. This number is used by {@link #uploadChunk()} to indicate how * much data is uploaded in a single take. When choosing a value for this parameter you need to * consider that uploadChunk() will only return once the specified number of bytes has been * sent. For slow internet connections this may take a long time. In addition, a buffer with * the chunk size is allocated and kept in memory. * * @param size The new chunk size */ public void setChunkSize(int size) { buffer = new byte[size]; } /** * Returns the current chunk size set using {@link #setChunkSize(int)}. * * @return Current chunk size */ public int getChunkSize() { return buffer.length; } public void setRequestPayloadSize(int size) throws IllegalStateException { if(connection != null) { throw new IllegalStateException("payload size for a single request must not be " + "modified as long as a request is in progress"); } requestPayloadSize = size; } /** * Get the current maximum payload size for a single request. * * @see #setChunkSize(int) * * @return Number of bytes for a single payload */ public int getRequestPayloadSize() { return requestPayloadSize; } /** * Upload a part of the file by reading a chunk from the InputStream and writing * it to the HTTP request's body. If the number of available bytes is lower than the chunk's * size, all available bytes will be uploaded and nothing more. * No new connection will be established when calling this method, instead the connection opened * in the previous calls will be used. * The size of the read chunk can be obtained using {@link #getChunkSize()} and changed * using {@link #setChunkSize(int)}. * In order to obtain the new offset, use {@link #getOffset()} after this method returns. * * @return Number of bytes read and written. * @throws IOException Thrown if an exception occurs while reading from the source or writing * to the HTTP request. */ public int uploadChunk() throws IOException, ProtocolException { openConnection(); int bytesToRead = Math.min(getChunkSize(), bytesRemainingForRequest); int bytesRead = input.read(buffer, bytesToRead); if(bytesRead == -1) { // No bytes were read since the input stream is empty return -1; } // Do not write the entire buffer to the stream since the array will // be filled up with 0x00s if the number of read bytes is lower then // the chunk's size. output.write(buffer, 0, bytesRead); output.flush(); offset += bytesRead; bytesRemainingForRequest -= bytesRead; if(bytesRemainingForRequest <= 0) { finishConnection(); } return bytesRead; } /** * Upload a part of the file by read a chunks specified size from the InputStream and writing * it to the HTTP request's body. If the number of available bytes is lower than the chunk's * size, all available bytes will be uploaded and nothing more. * No new connection will be established when calling this method, instead the connection opened * in the previous calls will be used. * In order to obtain the new offset, use {@link #getOffset()} after this method returns. * * This method ignored the payload size per request, which may be set using * {@link #setRequestPayloadSize(int)}. Please, use {@link #uploadChunk()} instead. * * @deprecated This method is inefficient and has been replaced by {@link #setChunkSize(int)} * and {@link #uploadChunk()} and should not be used anymore. The reason is, that * this method allocates a new buffer with the supplied chunk size for each time * it's called without reusing it. This results in a high number of memory * allocations and should be avoided. The new methods do not have this issue. * * @param chunkSize Maximum number of bytes which will be uploaded. When choosing a value * for this parameter you need to consider that the method call will only * return once the specified number of bytes have been sent. For slow * internet connections this may take a long time. * @return Number of bytes read and written. * @throws IOException Thrown if an exception occurs while reading from the source or writing * to the HTTP request. */ @Deprecated public int uploadChunk(int chunkSize) throws IOException, ProtocolException { openConnection(); byte[] buf = new byte[chunkSize]; int bytesRead = input.read(buf, chunkSize); if(bytesRead == -1) { // No bytes were read since the input stream is empty return -1; } // Do not write the entire buffer to the stream since the array will // be filled up with 0x00s if the number of read bytes is lower then // the chunk's size. output.write(buf, 0, bytesRead); output.flush(); offset += bytesRead; return bytesRead; } /** * Get the current offset for the upload. This is the number of all bytes uploaded in total and * in all requests (not only this one). You can use it in conjunction with * {@link TusUpload#getSize()} to calculate the progress. * * @return The upload's current offset. */ public long getOffset() { return offset; } public URL getUploadURL() { return uploadURL; } /** * Finish the request by closing the HTTP connection and the InputStream. * You can call this method even before the entire file has been uploaded. Use this behavior to * enable pausing uploads. * This method is equivalent to calling {@code finish(false)}. * * @throws ProtocolException Thrown if the server sends an unexpected status * code * @throws IOException Thrown if an exception occurs while cleaning up. */ public void finish() throws ProtocolException, IOException { finish(true); } /** * Finish the request by closing the HTTP connection. You can choose whether to close the InputStream or not. * You can call this method even before the entire file has been uploaded. Use this behavior to * enable pausing uploads. * * Be aware that it doesn't automatically release local resources if {@code closeStream == false} and you do * not close the InputStream on your own. To be safe use {@link TusUploader#finish()}. * * @param closeInputStream Determines whether the InputStream is closed with the HTTP connection. Not closing the * Input Stream may be useful for future upload a future continuation of the upload. * @throws ProtocolException Thrown if the server sends an unexpected status code * @throws IOException Thrown if an exception occurs while cleaning up. */ public void finish(boolean closeInputStream) throws ProtocolException, IOException { finishConnection(); if (upload.getSize() == offset) { client.uploadFinished(upload); } // Close the TusInputStream after checking the response and closing the connection to ensure // that we will not need to read from it again in the future. if (closeInputStream) { input.close(); } } private void finishConnection() throws ProtocolException, IOException { if(output != null) output.close(); if(connection != null) { int responseCode = connection.getResponseCode(); connection.disconnect(); if (!(responseCode >= 200 && responseCode < 300)) { throw new ProtocolException("unexpected status code (" + responseCode + ") while uploading chunk", connection); } // TODO detect changes and seek accordingly long serverOffset = getHeaderFieldLong(connection, "Upload-Offset"); if(serverOffset == -1) { throw new ProtocolException("response to PATCH request contains no or invalid Upload-Offset header", connection); } if(offset != serverOffset) { throw new ProtocolException( String.format("response contains different Upload-Offset value (%d) than expected (%d)", serverOffset, offset), connection); } connection = null; } } private long getHeaderFieldLong(URLConnection connection, String field) { String value = connection.getHeaderField(field); if(value == null) { return -1; } try { return Long.parseLong(value); } catch(NumberFormatException e) { return -1; } } }
package com.rollbar.http; /** * Represents expected response codes from POSTing an item to Rollbar * */ public enum RollbarResponseCode { /** * A successful POST to the API */ Success(200), /** * Invalid, or missing, JSON POST body. */ BadRequest(400), /** * Missing Access Token. (Check your JSON serialization). */ Unauthorized(401), /** * Invalid access token. Bad format, invalid scope, for type of request (Client -> Server, or vice versa). * See the {@link RollbarResponse} message. */ AccessDenied(403), /** * Max Payload size exceeded. Try removing or truncating particularly large portions of your payload * (e.g. whole binary files, or large strings). */ RequestTooLarge(413), /** * JSON was valid, but semantically incorrect. See {@link RollbarResponse} message. */ UnprocessablePayload(422), /** * Rate limit for your account or access token was reached. */ TooManyRequests(429), /** * An error occurred on Rollbar's end. */ InternalServerError(500); private final int value; RollbarResponseCode(int value) { this.value = value; } /** * Create a {@link RollbarResponse} from a response code, with a message. * @param message The explanatory message. * @return RollbarResponse with explanatory message. */ public RollbarResponse response(String message) { return RollbarResponse.failure(this, message); } /** * Get a Response Code from the integer value returned by the HTTP request. * @param i the integer value of the response code. * @return the RollbarResponseCode * @throws InvalidResponseCodeException if not a valid ResponseCode */ public static RollbarResponseCode fromInt(int i) throws InvalidResponseCodeException { for(RollbarResponseCode rrc : RollbarResponseCode.values()) { if (rrc.value == i) return rrc; } throw new InvalidResponseCodeException(i); } }
package istc.bigdawg.query; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import jline.internal.Log; import org.apache.accumulo.core.client.AccumuloException; import org.apache.accumulo.core.client.AccumuloSecurityException; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import istc.bigdawg.accumulo.AccumuloHandler; import istc.bigdawg.exceptions.AccumuloShellScriptException; import istc.bigdawg.executor.QueryResult; import istc.bigdawg.planner.Planner; import istc.bigdawg.postgresql.PostgreSQLHandler; import istc.bigdawg.scidb.SciDBHandler; import istc.bigdawg.sstore.SStoreSQLConnectionInfo; import istc.bigdawg.utils.LogUtils; import istc.bigdawg.utils.StackTrace; @Path("/") public class QueryClient { private static Logger log = Logger .getLogger(QueryClient.class.getName()); private static List<DBHandler> registeredDbHandlers; static { registeredDbHandlers = new ArrayList<DBHandler>(); int postgreSQL1Engine=0; try { registeredDbHandlers.add(new PostgreSQLHandler(postgreSQL1Engine)); } catch (Exception e) { e.printStackTrace(); String msg = "Could not register PostgreSQL handler!"; System.err.println(msg); log.error(msg); System.exit(1); } registeredDbHandlers.add(new AccumuloHandler()); try { registeredDbHandlers.add(new SciDBHandler()); } catch (SQLException e) { e.printStackTrace(); log.error(e.getMessage() + " " + StackTrace.getFullStackTrace(e)); } } /** * Answer a query from a client. * * @param istream * @return * @throws AccumuloSecurityException * @throws AccumuloException * @throws TableNotFoundException * @throws AccumuloShellScriptException * @throws InterruptedException */ @Path("query") @POST // @Consumes(MediaType.APPLICATION_JSON) // @Produces(MediaType.APPLICATION_JSON) public Response query(String istream) { log.info("istream: " + istream.replaceAll("[\"']", "*")); try { return Planner.processQuery(istream, false); } catch (Exception e) { e.printStackTrace(); return Response.status(412).entity(e.getMessage()).build(); } } /** * Answer a query from a client. * * @param istream * @return * @throws AccumuloSecurityException * @throws AccumuloException * @throws TableNotFoundException * @throws AccumuloShellScriptException * @throws InterruptedException */ @Path("jsonquery") @POST // @Consumes(MediaType.APPLICATION_JSON) public Response jsonQuery(String istream) { log.info("istream: " + istream.replaceAll("[\"']", "*")); try { Response r = Planner.processQuery(istream, false); String results = (String)r.getEntity(); return Response.ok(formatToJson(results)).build(); } catch (Exception e) { e.printStackTrace(); return Response.status(412).entity(e.getMessage()).build(); } } private String formatToJson(String s) throws JSONException{ StringBuilder sb = new StringBuilder(); sb.append('['); Scanner scanner = new Scanner(s); String[] fields = scanner.nextLine().split("\t"); while(scanner.hasNextLine()){ sb.append('{'); sb.append(processLine(scanner.nextLine(),fields)); sb.append('}').append(','); } if (sb.length() > 1) sb.deleteCharAt(sb.length()-1); sb.append(']'); return sb.toString(); } private String processLine(String nextLine, String[] fields) { StringBuilder sb = new StringBuilder(); String[] values = nextLine.split("\t"); String pattern = "^[+-]?([0-9]*[.])?[0-9]+$"; Pattern p = Pattern.compile(pattern); for(int i =0; i<values.length; i++){ sb.append(fields[i]).append(':'); Matcher m = p.matcher(values[i]); if(m.matches() || "null".equals(values[i])){ //its a number or null value sb.append(values[i]); } else { //its a string sb.append('"'); sb.append(values[i]); sb.append('"'); } sb.append(','); } if (sb.length() > 1) sb.deleteCharAt(sb.length()-1); return sb.toString(); } public static void main(String[] args) { /* QueryClient qClient = new QueryClient(); qClient.executeQueryPostgres("Select * from books"); Response response1 = qClient.query("{\"query\":\"RELATION(select * from mimic2v26.d_patients limit 5)\",\"authorization\":{},\"tuplesPerPage\":1,\"pageNumber\":1,\"timestamp\":\"2012-04-23T18:25:43.511Z\"}"); System.out.println(response1.getEntity()); int max_limit = 10000; for (int limit = 1; limit <= max_limit; limit = limit * 2) { System.out.print("limit: " + limit + ","); long lStartTime = System.nanoTime(); Response response = qClient .query("{\"query\":\"RELATION(SELECT * FROM pg_catalog.pg_tables)\",\"authorization\":{},\"tuplesPerPage\":1,\"pageNumber\":1,\"timestamp\":\"2012-04-23T18:25:43.511Z\"}"); Response response = qClient .query("{\"query\":\"RELATION(select * from mimic2v26.d_patients limit " + limit + ")\",\"authorization\":{},\"tuplesPerPage\":1,\"pageNumber\":1,\"timestamp\":\"2012-04-23T18:25:43.511Z\"}"); Response response = qClient .query("{\"query\":\"RELATION(select * from mimic2v26.chartevents limit " + limit + ")\",\"authorization\":{},\"tuplesPerPage\":1,\"pageNumber\":1,\"timestamp\":\"2012-04-23T18:25:43.511Z\"}"); System.out.println("Postgresql response: " + response.getEntity()); System.out.println("Elapsed total time milliseconds: " + (System.nanoTime() - lStartTime) / 1000000); } qClient.query("{\"query\":\"RELATION(SELECT * FROM test2)\",\"authorization\":{},\"tuplesPerPage\":1,\"pageNumber\":1,\"timestamp\":\"2012-04-23T18:25:43.511Z\"}"); System.out.println(response.getEntity()); String accumuloData = qClient .executeQueryAccumuloPure("note_events_TedgeDeg"); System.out.println(accumuloData); */ } }
package com.rultor.agents.daemons; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.jcabi.aspects.Immutable; import com.jcabi.log.Logger; import com.jcabi.ssh.SSH; import com.jcabi.ssh.Shell; import com.jcabi.xml.XML; import com.rultor.Time; import com.rultor.agents.AbstractAgent; import com.rultor.agents.shells.TalkShells; import java.io.IOException; import lombok.EqualsAndHashCode; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import org.xembly.Directive; import org.xembly.Directives; /** * Marks the daemon as done. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 1.0 * @checkstyle ClassDataAbstractionCoupling (500 lines) * @todo @567 Refactor this class to use less objects and remove checkstyle * exception above. */ @Immutable @ToString @EqualsAndHashCode(callSuper = false) public final class EndsDaemon extends AbstractAgent { /** * Prefix for log highlights. */ public static final String HIGHLIGHTS_PREFIX = "RULTOR: "; /** * Join shell commands with this string. */ private static final String SHELL_JOINER = " && "; /** * Ctor. */ public EndsDaemon() { super("/talk/daemon[started and not(code) and not(ended)]"); } @Override public Iterable<Directive> process(final XML xml) throws IOException { final Shell shell = new TalkShells(xml).get(); final String dir = xml.xpath("/talk/daemon/dir/text()").get(0); final int exit = new Shell.Empty(shell).exec( Joiner.on(EndsDaemon.SHELL_JOINER).join( String.format("dir=%s ", SSH.escape(dir)), "if [ ! -e \"${dir}/pid\" ]; then exit 1; fi", "pid=$(cat \"${dir}/pid\")", "ps -p \"${pid}\" >/dev/null" ) ); final Directives dirs = new Directives(); if (exit == 0) { Logger.info( this, "the daemon is still running in %s (%s)", dir, xml.xpath("/talk/@name").get(0) ); } else { dirs.append(this.end(shell, dir)); } return dirs; } /** * End this daemon. * @param shell Shell * @param dir The dir * @return Directives * @throws IOException If fails */ private Iterable<Directive> end(final Shell shell, final String dir) throws IOException { final int exit = this.exit(shell, dir); final String stdout = Joiner.on("\n").join( Iterables.transform( Iterables.filter( Splitter.on(System.lineSeparator()).split( new Shell.Plain(new Shell.Safe(shell)).exec( Joiner.on(EndsDaemon.SHELL_JOINER).join( String.format("dir=%s", SSH.escape(dir)), "cat \"${dir}/stdout\"" ) ) ), new Predicate<String>() { @Override public boolean apply(final String input) { return input.startsWith( EndsDaemon.HIGHLIGHTS_PREFIX ); } } ), new Function<String, String>() { @Override public String apply(final String str) { return StringUtils.removeStart( str, EndsDaemon.HIGHLIGHTS_PREFIX ); } } ) ); Logger.info(this, "daemon finished at %s, exit: %d", dir, exit); return new Directives() .xpath("/talk/daemon") .strict(1) .add("ended").set(new Time().iso()).up() .add("code").set(Integer.toString(exit)).up() .add("highlights").set(stdout); } /** * Get exit code. * @param shell Shell * @param dir The dir * @return Exit code * @throws IOException If fails */ private int exit(final Shell shell, final String dir) throws IOException { final String status = new Shell.Plain(new Shell.Safe(shell)).exec( Joiner.on(EndsDaemon.SHELL_JOINER).join( String.format("cd %s", SSH.escape(dir)), "if [ ! -e status ]; then echo 127; exit; fi", "cat status" ) ).trim().replaceAll("[^0-9]", ""); final int exit; if (status.isEmpty()) { exit = 1; } else { exit = Integer.parseInt(status); } return exit; } }
package me.pagar.util; import com.google.common.base.Strings; import com.google.gson.*; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.ISODateTimeFormat; import java.lang.reflect.Type; public class LocalDateAdapter implements JsonDeserializer<LocalDate>, JsonSerializer<LocalDate> { private final DateTimeFormatter formatter; public LocalDateAdapter() { this.formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ"); } @Override public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final String dateTime = json.getAsString(); return Strings.isNullOrEmpty(dateTime) ? null : formatter.parseLocalDate(dateTime); } @Override public JsonElement serialize(LocalDate src, Type typeOfSrc, JsonSerializationContext context) { return src == null ? null : new JsonPrimitive(formatter.print(src)); } }
package com.stratio.tests.utils; import java.net.UnknownHostException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; import cucumber.api.DataTable; public class MongoDBUtils { private static final Logger LOGGER = LoggerFactory .getLogger(MongoDBUtils.class); private final String host; private final int port; private static MongoClient mongoClient; private DB dataBase; public MongoDBUtils() { this.host = System.getProperty("MONGO_HOST", "127.0.0.1"); this.port = Integer.parseInt(System.getProperty("MONGO_PORT", "27017")); LOGGER.debug("Initializing MongoDB client"); } public void connectToMongoDB() { try { mongoClient = new MongoClient(this.host, this.port); } catch (UnknownHostException e) { LOGGER.error("Unable to connect to MongoDB", e); } } public void disconnect() { mongoClient.close(); } public void connectToMongoDBDataBase(String db) { dataBase = mongoClient.getDB(db); } public boolean exitsMongoDbDataBase(String dataBaseName) { List<String> dataBaseList = mongoClient.getDatabaseNames(); return dataBaseList.contains(dataBaseName); } public boolean exitsCollections(String colName) { return dataBase.collectionExists(colName); } public Set<String> getMongoDBCollections() { return dataBase.getCollectionNames(); } public DBCollection getMongoDBCollection(String collectionName) { return dataBase.getCollection(collectionName); } public void createMongoDBCollection(String colectionName, DataTable options) { BasicDBObject aux = new BasicDBObject(); List<List<String>> rowsOp = options.raw(); for (int i = 0; i < rowsOp.size(); i++) { List<String> rowOp = rowsOp.get(i); if (rowOp.get(0).equals("size") || rowOp.get(0).equals("max")) { int intproperty = Integer.parseInt(rowOp.get(1)); aux.append(rowOp.get(0), intproperty); } else { Boolean boolProperty = Boolean.parseBoolean(rowOp.get(1)); aux.append(rowOp.get(0), boolProperty); } } dataBase.createCollection(colectionName, aux); } public void dropMongoDBDataBase(String dataBaseName) { mongoClient.dropDatabase(dataBaseName); } public void dropMongoDBCollection(String collectionName) { getMongoDBCollection(collectionName).drop(); } public void dropAllDataMongoDBCollection(String collectionName) { DBCollection db = getMongoDBCollection(collectionName); DBCursor objectsList = db.find(); try { while (objectsList.hasNext()) { db.remove(objectsList.next()); } } finally { objectsList.close(); } } public void insertIntoMongoDBCollection(String collection, DataTable table) { // Primero pasamos la fila del datatable a un hashmap de ColumnName-Type List<String[]> colRel = coltoArrayList(table); // Vamos insertando fila a fila for (int i = 1; i < table.raw().size(); i++) { // Obtenemos la fila correspondiente BasicDBObject doc = new BasicDBObject(); List<String> row = table.raw().get(i); for (int x = 0; x < row.size(); x++) { String[] colNameType = colRel.get(x); Object data = castSTringTo(colNameType[1], row.get(x)); doc.put(colNameType[0], data); } this.dataBase.getCollection(collection).insert(doc); } } public List<DBObject> readFromMongoDBCollection(String collection, DataTable table) { List<DBObject> res = new ArrayList<DBObject>(); List<String[]> colRel = coltoArrayList(table); DBCollection aux = this.dataBase.getCollection(collection); for (int i = 1; i < table.raw().size(); i++) { // Obtenemos la fila correspondiente BasicDBObject doc = new BasicDBObject(); List<String> row = table.raw().get(i); for (int x = 0; x < row.size(); x++) { String[] colNameType = colRel.get(x); Object data = castSTringTo(colNameType[1], row.get(x)); doc.put(colNameType[0], data); } DBCursor cursor = aux.find(doc); try { while (cursor.hasNext()) { res.add(cursor.next()); } } finally { cursor.close(); } } return res; } private List<String[]> coltoArrayList(DataTable table) { List<String[]> res = new ArrayList<String[]>(); // Primero se obiente la primera fila del datatable List<String> firstRow = table.raw().get(0); for (int i = 0; i < firstRow.size(); i++) { String[] colTypeArray = firstRow.get(i).split("-"); res.add(colTypeArray); } return res; } private Object castSTringTo(String dataType, String data) { switch (dataType) { case "String": return data; case "Integer": return Integer.parseInt(data); case "Double": return Double.parseDouble(dataType); case "Boolean": return Boolean.parseBoolean(dataType); case "Timestamp": return Timestamp.valueOf(dataType); default: return null; } } }
package com.twu.biblioteca.model; import com.twu.biblioteca.exceptions.BookNotBorrowable; import com.twu.biblioteca.exceptions.BookNotReturnable; import com.twu.biblioteca.exceptions.MovieNotBorrowable; import java.util.*; /** * Library implementation. * Library is responsible for holding the available and borrowed books. * * @author Desiree Kelly * @version 1.0 */ public class LibraryImpl implements Library { private List<Book> books = new ArrayList<Book>(); private Set<Book> borrowedBooks = new HashSet<Book>(); private List<Movie> movies = new ArrayList<Movie>(); private Set<Movie> borrowedMovies = new HashSet<Movie>(); private Map<String, User> users = new HashMap<String, User>(); private Map<String, String> bookCheckedOutByCustomer = new HashMap<String, String>(); public LibraryImpl() { this.createBookList(); this.createMovieList(); this.createUsers(); this.createBooksCheckedOutByCustomer(); } private void createBookList() { books.add(new Book("Java 101", "Joe Bloggs", 1990)); books.add(new Book("PHP 101", "Mary Jane", 2005)); books.add(new Book("C# 101", "John Smith", 2010)); books.add(new Book("C++ 101", "Joyce Merry", 2001)); } private void createMovieList() { movies.add(new Movie("The Matrix", 1999, "The Wachowski Brothers", "10")); movies.add(new Movie("Inception", 2010, "Christopher Nolan", "8")); movies.add(new Movie("Divergent", 2014, "Neil Burger", "Unrated")); movies.add(new Movie("The Bourne Identity", 2002, "Doug Liman", "10")); } private void createUsers() { User customer1 = new User("Joe Bloggs", "joebloggs@joebloggs.com", "0400 000 000", "123-4566", "f8kf93jd"); User customer2 = new User("Jane Smith", "janesmith@janesmith.com", "0400 123 888", "123-4567", "5jgfdkl5"); User customer3 = new User("Bob Smith", "bobsmith@bobsmith.com", "0412 454 565", "123-4568", "4jg84jf8"); User librarian = new User("Jenny Bloggs", "jennybloggs@jennybloggs.com", "0435 567 040", "123-4569", "kb94kfm3"); users.put(customer1.getLibraryNumber(), customer1); users.put(customer2.getLibraryNumber(), customer2); users.put(customer3.getLibraryNumber(), customer3); users.put(librarian.getLibraryNumber(), librarian); librarian.setLibrarian(true); } private void createBooksCheckedOutByCustomer() { Book book = new Book("Ruby 101", "Jenny Moore", 2013); User customer = new User("Bob Kent", "bobkent@bobkent.com", "0400 575 838", "123-4570", "4jv03m20"); users.put(customer.getLibraryNumber(), customer); borrowedBooks.add(book); bookCheckedOutByCustomer.put(book.getTitle(), customer.getLibraryNumber()); } @Override public List<Book> getAvailableBooks() { List<Book> results = new ArrayList<Book>(books.size()); for (Book book : books) { if (!borrowedBooks.contains(book)) { results.add(book); } } return results; } @Override public List<Book> getBorrowedBooks() { List<Book> results = new ArrayList<Book>(books.size()); for (Book book : books) { if (borrowedBooks.contains(book)) { results.add(book); } } return results; } @Override public List<Book> getBookList() { return Collections.unmodifiableList(books); } @Override public void checkoutBook(Book book, User user) throws BookNotBorrowable { if (borrowedBooks.contains(book)) throw new BookNotBorrowable("book is not available"); borrowedBooks.add(book); bookCheckedOutByCustomer.put(book.getTitle(), user.getLibraryNumber()); } @Override public void returnBook(Book book, User user) throws BookNotReturnable { if (!borrowedBooks.contains(book)) throw new BookNotReturnable("book is already returned"); borrowedBooks.remove(book); bookCheckedOutByCustomer.remove(book.getTitle()); } @Override public List<Movie> getAvailableMovies() { List<Movie> results = new ArrayList<Movie>(movies.size()); for (Movie movie : movies) { if (!borrowedMovies.contains(movie)) { results.add(movie); } } return results; } @Override public List<Movie> getBorrowedMovies() { List<Movie> results = new ArrayList<Movie>(movies.size()); for (Movie movie : movies) { if (borrowedMovies.contains(movie)) { results.add(movie); } } return results; } @Override public List<Movie> getMovieList() { return Collections.unmodifiableList(movies); } @Override public void checkoutMovie(Movie movie) throws MovieNotBorrowable { if (borrowedMovies.contains(movie)) throw new MovieNotBorrowable("movie is not available"); borrowedMovies.add(movie); } @Override public String getBooksCheckedOutByCustomer(String bookTitle) { String checkedOutByCustomer; for (Map.Entry<String, String> entry : bookCheckedOutByCustomer.entrySet()) { if (bookCheckedOutByCustomer.containsKey(bookTitle)) { checkedOutByCustomer = entry.getKey() + " is checked out by user: " + entry.getValue(); return checkedOutByCustomer; } } return null; } @Override public Map<String, User> getUsers() { return Collections.unmodifiableMap(users); } @Override public User login(String libraryNumber, String password) { if (users.containsKey(libraryNumber)) { if (users.get(libraryNumber).checkPassword(password)) { return users.get(libraryNumber); } } return null; } }
package nablarch.etl; import java.io.File; import java.io.IOException; import java.io.InputStream; import javax.batch.api.AbstractBatchlet; import javax.batch.runtime.context.JobContext; import javax.batch.runtime.context.StepContext; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import nablarch.core.log.basic.LogLevel; import nablarch.core.log.operation.OperationLogger; import nablarch.core.message.MessageLevel; import nablarch.core.message.MessageUtil; import nablarch.core.repository.SystemRepository; import nablarch.core.util.FileUtil; import nablarch.etl.config.EtlConfig; import nablarch.etl.config.FileToDbStepConfig; import nablarch.etl.config.PathConfig; import nablarch.etl.config.StepConfig; /** * SQL*LoaderCSV{@link javax.batch.api.Batchlet} * * @author Naoki Yamamoto */ @Named @Dependent public class SqlLoaderBatchlet extends AbstractBatchlet { /** {@link SystemRepository}DB */ private static final String USER_KEY = "db.user"; /** {@link SystemRepository}DB */ private static final String PASSWORD_KEY = "db.password"; /** {@link SystemRepository} */ private static final String DATABASE_NAME_KEY = "db.databaseName"; /** {@link JobContext} */ private final JobContext jobContext; /** {@link StepContext} */ private final StepContext stepContext; /** ETL */ private final FileToDbStepConfig stepConfig; private final File inputFileBasePath; /** SQLLoader */ private final File sqlLoaderControlFileBasePath; /** SQLLoader */ private final File sqlLoaderOutputFileBasePath; /** * * @param jobContext JobContext * @param stepContext StepContext * @param stepConfig * @param inputFileBasePath * @param sqlLoaderControlFileBasePath SQL*Loader * @param sqlLoaderOutputFileBasePath SQL*Loader */ @Inject public SqlLoaderBatchlet( final JobContext jobContext, final StepContext stepContext, @EtlConfig final StepConfig stepConfig, @PathConfig(BasePath.INPUT) final File inputFileBasePath, @PathConfig(BasePath.SQLLOADER_CONTROL) final File sqlLoaderControlFileBasePath, @PathConfig(BasePath.SQLLOADER_OUTPUT) final File sqlLoaderOutputFileBasePath) { this.jobContext = jobContext; this.stepContext = stepContext; this.stepConfig = (FileToDbStepConfig) stepConfig; this.inputFileBasePath = inputFileBasePath; this.sqlLoaderControlFileBasePath = sqlLoaderControlFileBasePath; this.sqlLoaderOutputFileBasePath = sqlLoaderOutputFileBasePath; } /** * SQL*LoaderCSV * * @return * @throws Exception */ @Override public String process() throws Exception { final String user = getUser(); final String password = getPassword(); final String databaseName = getDatabaseName(); final String jobId = jobContext.getJobName(); final String stepId = stepContext.getStepName(); EtlUtil.verifyRequired(jobId, stepId, "fileName", stepConfig.getFileName()); EtlUtil.verifyRequired(jobId, stepId, "bean", stepConfig.getBean()); final String ctlFileName = stepConfig.getBean().getSimpleName(); final String ctlFile = new File(sqlLoaderControlFileBasePath, ctlFileName + ".ctl").getPath(); final File dataFile = new File(inputFileBasePath, stepConfig.getFileName()); final String badFile = new File(sqlLoaderOutputFileBasePath, ctlFileName + ".bad").getPath(); final String logFile = new File(sqlLoaderOutputFileBasePath, ctlFileName + ".log").getPath(); if (!dataFile.isFile()) { OperationLogger.write(LogLevel.ERROR, MessageUtil.createMessage(MessageLevel.ERROR, "nablarch.etl.input-file-not-found", dataFile.getAbsoluteFile()).formatMessage()); return "FAILED"; } SqlLoaderRunner runner = new SqlLoaderRunner(user, password, databaseName, ctlFile, dataFile.getPath(), badFile, logFile); runner.execute(); if (!runner.isSuccess()) { throw new SqlLoaderFailedException( "failed to execute SQL*Loader. controlFile = [" + ctlFile + ']'); } return "SUCCESS"; } /** * SQL*LoaderDB{@link SystemRepository} * <ul> * <li>db.user</li> * </ul> * * * @return */ protected String getUser() { return SystemRepository.getString(USER_KEY); } /** * SQL*LoaderDB{@link SystemRepository} * <ul> * <li>db.password</li> * </ul> * * * @return */ protected String getPassword() { return SystemRepository.getString(PASSWORD_KEY); } /** * SQL*Loader{@link SystemRepository} * <ul> * <li>db.databaseName</li> * </ul> * * * @return */ protected String getDatabaseName() { return SystemRepository.getString(DATABASE_NAME_KEY); } /** * SQL*Loader * * @author Naoki Yamamoto */ public static class SqlLoaderRunner { private final String userName; private final String password; private final String databaseName; private final String ctrlFile; private final String dataFile; /** BAD */ private final String badFile; private final String logFile; /** SQL*Loader{@link Process} */ private Process process; /** * * * @param userName DB * @param password DB * @param databaseName * @param ctrlFile * @param dataFile * @param badFile BAD * @param logFile */ public SqlLoaderRunner(String userName, String password, String databaseName, String ctrlFile, String dataFile, String badFile, String logFile) { this.userName = userName; this.password = password; this.databaseName = databaseName; this.ctrlFile = ctrlFile; this.dataFile = dataFile; this.badFile = badFile; this.logFile = logFile; } /** * SQL*Loader * * @throws IOException * @throws InterruptedException SQL*Loader */ public void execute() throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder( "sqlldr", "USERID=" + userName + "/" + password + "@" + databaseName, "CONTROL=" + ctrlFile, "DATA=" + dataFile, "BAD=" + badFile, "LOG=" + logFile, "SILENT=(HEADER,FEEDBACK)"); pb.redirectErrorStream(true); process = pb.start(); InputStream is = process.getInputStream(); try { while (is.read() >= 0) { } } finally { FileUtil.closeQuietly(is); } process.waitFor(); } /** * SQL*Loader * * @return {@code true} */ public boolean isSuccess() { return process.exitValue() == 0; } } }
package net.amigocraft.mglib.api; import com.google.common.collect.Lists; import net.amigocraft.mglib.MGUtil; import net.amigocraft.mglib.Main; import net.amigocraft.mglib.RollbackManager; import net.amigocraft.mglib.UUIDFetcher; import net.amigocraft.mglib.event.player.PlayerHitArenaBorderEvent; import net.amigocraft.mglib.event.player.PlayerJoinMinigameRoundEvent; import net.amigocraft.mglib.event.player.PlayerLeaveMinigameRoundEvent; import net.amigocraft.mglib.event.round.*; import net.amigocraft.mglib.exception.*; import net.amigocraft.mglib.misc.JoinResult; import net.amigocraft.mglib.misc.Metadatable; import org.bukkit.*; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.potion.PotionEffect; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import static net.amigocraft.mglib.MGUtil.loadArenaYaml; import static net.amigocraft.mglib.Main.locale; public class Round implements Metadatable { HashMap<String, Object> metadata = new HashMap<String, Object>(); private int minPlayers; private int maxPlayers; private int prepareTime; private int roundTime; private Location exitLocation; private String plugin; private int time = 0; private Stage stage; private String world; private String arena; private String displayName; private List<Location> spawns = new ArrayList<Location>(); private Location minBound; private Location maxBound; private HashMap<String, MGPlayer> players = new HashMap<String, MGPlayer>(); private int timerHandle = -1; private boolean damage; private boolean pvp; private boolean rollback; /** * Creates a new {@link Round} with the given parameters. * <br><br> * <strong>Please use {@link Minigame#createRound(String)} * unless you understand the implications of using this constructor.</strong> * @param plugin the plugin which this round should be associated with * @param arena the name of the arena in which this round takes place in * @throws NoSuchArenaException if the specified arena does not exist */ public Round(String plugin, String arena) throws NoSuchArenaException{ MGYamlConfiguration y = loadArenaYaml(plugin); if (!y.contains(arena)){ throw new NoSuchArenaException(); } ConfigurationSection cs = y.getConfigurationSection(arena); // make the code easier to read world = cs.getString("world"); // get the name of the world of the arena World w = Bukkit.getWorld(world); // convert it to a Bukkit world if (w == null){ w = Bukkit.createWorld(new WorldCreator(world).environment(MGUtil.getEnvironment(cs.getString("world")))); } if (w == null) // but what if world is kill? { throw new IllegalArgumentException("World " + world + " cannot be loaded!"); // then round is kill } for (String k : cs.getConfigurationSection("spawns").getKeys(false)){ // load spawns into round object Location l = new Location(w, cs.getDouble("spawns." + k + ".x"), cs.getDouble("spawns." + k + ".y"), cs.getDouble("spawns." + k + ".z")); if (cs.isSet(k + ".pitch")){ l.setPitch((float)cs.getDouble(cs.getCurrentPath() + ".spawns." + k + ".pitch")); } if (cs.isSet(k + ".yaw")){ l.setYaw((float)cs.getDouble(cs.getCurrentPath() + ".spawns." + k + ".yaw")); } spawns.add(l); // register spawn } if (cs.getBoolean("boundaries")){ // check if arena has boundaries defined minBound = new Location(w, cs.getDouble("minX"), cs.getDouble("minY"), cs.getDouble("minZ")); maxBound = new Location(w, cs.getDouble("maxX"), cs.getDouble("maxY"), cs.getDouble("maxZ")); } else { minBound = null; maxBound = null; } this.plugin = plugin; // set globals this.arena = arena.toLowerCase(); this.displayName = cs.contains("displayname") ? cs.getString("displayname") : arena.toLowerCase(); ConfigManager cm = getConfigManager(); this.prepareTime = cm.getDefaultPreparationTime(); this.roundTime = cm.getDefaultPlayingTime(); this.minPlayers = cm.getMinPlayers(); this.maxPlayers = cm.getMaxPlayers(); this.exitLocation = cm.getDefaultExitLocation(); this.damage = cm.isDamageAllowed(); this.pvp = cm.isPvPAllowed(); this.rollback = cm.isRollbackEnabled(); stage = Stage.WAITING; // default to waiting stage String[] defaultKeysA = new String[]{"world", "spawns", "minX", "minY", "minZ", "maxX", "maxY", "maxZ"}; List<String> defaultKeys = Arrays.asList(defaultKeysA); for (String k : cs.getKeys(true)){ if (!defaultKeys.contains(k.split("\\.")[0])){ setMetadata(k, cs.get(k)); } } Minigame.getMinigameInstance(plugin).getRounds().put(arena, this); // register round with minigame instance } /** * Gets the name of the minigame plugin associated with this {@link Round}. * @return the name of the minigame plugin associated with this {@link Round} * @since 0.1.0 */ public String getPlugin(){ return plugin; } /** * Gets the instance of the MGLib API registered by the plugin associated with this {@link Round}. * @return the instance of the MGLib API registered by the plugin associated with this {@link Round} * @since 0.1.0 */ public Minigame getMinigame(){ return Minigame.getMinigameInstance(plugin); } /** * Gets the name of the arena associated with this {@link Round}. * @return the name of the arena associated with this {@link Round} * @since 0.1.0 */ public String getArena(){ return arena; } /** * Gets the current {@link Stage} of this {@link Round}. * @return the current {@link Stage} of this {@link Round} * @since 0.1.0 */ public Stage getStage(){ return stage; } /** * Gets the current time in seconds of this {@link Round}, where 0 represents the first second of it. * @return the current time in seconds of this {@link Round}, where 0 represents the first second of it * @since 0.1.0 */ public int getTime(){ return time; } /** * Gets the time remaining in this round. * @return the time remaining in this round, or -1 if there is no time limit or if the {@link Stage stage} is not * {@link Stage#PLAYING PLAYING} or {@link Stage#PREPARING PREPARING} * @since 0.1.0 */ public int getRemainingTime(){ switch (this.getStage()){ case PREPARING: if (this.getPreparationTime() > 0){ return this.getPreparationTime() - this.getTime(); } else { return -1; } case PLAYING: if (this.getPlayingTime() > 0){ return this.getPlayingTime() - this.getTime(); } else { return -1; } default: return -1; } } /** * Gets the round's preparation time. * @return the round's preparation time * @since 0.1.0 */ public int getPreparationTime(){ return prepareTime; } /** * Gets the round's playing time. * @return the round's playing time * @since 0.1.0 */ public int getPlayingTime(){ return roundTime; } /** * Gets the round's timer's task's handle, or -1 if a timer is not started. * @return the round's timer's task's handle, or -1 if a timer is not started * @since 0.1.0 */ public int getTimerHandle(){ return timerHandle; } /** * Sets the associated arena of this {@link Round}. * @param arena the arena to associate with this {@link Round} * @since 0.1.0 */ public void setArena(String arena){ this.arena = arena; } /** * Sets the current stage of this {@link Round}. * @param stage the stage to set this {@link Round} to * @param resetTimer whether to reset the round timer (defaults to true if omitted) * @since 0.3.1 */ public void setStage(Stage stage, boolean resetTimer){ MinigameRoundStageChangeEvent event = new MinigameRoundStageChangeEvent(this, stage, s); MGUtil.callEvent(event); if (!event.isCancelled()){ this.stage = stage; if (resetTimer) setTime(0); } } /** * Sets the current stage of this {@link Round}. * @param stage the stage to set this {@link Round} to * @since 0.1.0 */ public void setStage(Stage stage){ this.setStage(stage, true); } /** * Sets the remaining time of this {@link Round}. * @param t the time to set this {@link Round} to * @since 0.1.0 */ public void setTime(int t){ time = t; } /** * Sets the round's preparation time. * @param t the number of seconds to set the preparation time to. Use -1 for no limit, or 0 for no preparation * phase. * @since 0.1.0 */ public void setPreparationTime(int t){ prepareTime = t; } /** * Sets the round's playing time. * @param t the number of seconds to set the preparation time to. Use -1 for no limit * @since 0.1.0 */ public void setPlayingTime(int t){ roundTime = t; } /** * Decrements the time remaining in the round by 1. <br><br> Please do not call this method from your plugin unless * you understand the implications. Let MGLib handle the timer. * @since 0.1.0 */ public void tick(){ time += 1; } /** * Subtracts <b>t</b> seconds from the elapsed time in the round. * @param t the number of seconds to subtract * @since 0.1.0 */ public void subtractTime(int t){ time -= t; } /** * Adds <b>t</b> seconds to the elapsed time in the round. * @param t the number of seconds to add * @since 0.1.0 */ public void addTime(int t){ time += t; } /** * Destroys this {@link Round}. <br><br> <b>Please do not call this method from your plugin unless you understand * the implications.</b> * @since 0.1.0 */ public void destroy(){ Minigame.getMinigameInstance(plugin).getRounds().remove(this.getArena()); } /** * Retrieves a list of {@link MGPlayer MGPlayers} in this round. * @return a list of {@link MGPlayer MGPlayers} in this round * @since 0.1.0 */ public List<MGPlayer> getPlayerList(){ return Lists.newArrayList(players.values()); } /** * Retrieves a {@link HashMap} of players in this round. * @return a {@link HashMap} mapping the names of players in the round to their respective {@link MGPlayer} objects * @since 0.1.0 */ public HashMap<String, MGPlayer> getPlayers(){ return players; } /** * Retrieves a {@link HashMap} of all players on a given team. * @param team the team to retrieve players from * @return a {@link HashMap} mapping the names of players on a given team to their respective {@link MGPlayer} * objects. * @since 0.3.0 */ public HashMap<String, MGPlayer> getTeam(String team){ HashMap<String, MGPlayer> t = new HashMap<String, MGPlayer>(); for (MGPlayer p : getPlayerList()){ if (p.getTeam() != null && p.getTeam().equals(team)){ t.put(p.getName(), p); } } return t; } /** * Retrieves a list of non-spectating {@link MGPlayer MGPlayers} in this round. * @return a list of non-spectating {@link MGPlayer MGPlayers} in this round * @since 0.2.0 */ public List<MGPlayer> getAlivePlayerList(){ List<MGPlayer> list = new ArrayList<MGPlayer>(); for (MGPlayer p : players.values()){ if (!p.isSpectating()){ list.add(p); } } return list; } /** * Retrieves a list of spectating {@link MGPlayer MGPlayers} in this {@link Round}. * @return a list of spectating {@link MGPlayer MGPlayers} in this {@link Round} * @since 0.2.0 */ public List<MGPlayer> getSpectatingPlayerList(){ List<MGPlayer> list = new ArrayList<MGPlayer>(); for (MGPlayer p : players.values()){ if (p.isSpectating()){ list.add(p); } } return list; } /** * Retrieves the number of {@link MGPlayer MGPlayers} in this {@link Round}. * @return the number of {@link MGPlayer MGPlayers} in this {@link Round} * @since 0.2.0 */ public int getPlayerCount(){ return players.size(); } /** * Retrieves the number of in-game (non-spectating) {@link MGPlayer MGPlayers} in this {@link Round}. * @return the number of in-game (non-spectating) {@link MGPlayer MGPlayers} in this {@link Round} * @since 0.2.0 */ public int getAlivePlayerCount(){ int count = 0; for (MGPlayer p : players.values()){ if (!p.isSpectating()){ count += 1; } } return count; } /** * Retrieves the number of spectating {@link MGPlayer MGPlayers} in this {@link Round}. * @return the number of spectating {@link MGPlayer MGPlayers} in this {@link Round} * @since 0.2.0 */ public int getSpectatingPlayerCount(){ int count = 0; for (MGPlayer p : players.values()){ if (p.isSpectating()){ count += 1; } } return count; } public void start(){ if (stage == Stage.WAITING){ // make sure the round isn't already started final Round r = this; if (r.getPreparationTime() > 0){ MinigameRoundPrepareEvent event = new MinigameRoundPrepareEvent(r); MGUtil.callEvent(event); if (event.isCancelled()){ return; } r.setTime(0); // reset time r.setStage(Stage.PREPARING); // set stage to preparing } else { MinigameRoundStartEvent event = new MinigameRoundStartEvent(r); MGUtil.callEvent(event); if (event.isCancelled()){ return; } r.setTime(0); // reset timer r.setStage(Stage.PLAYING); } if (time != -1){ // I'm pretty sure this is wrong, but I'm also pretty tired timerHandle = Bukkit.getScheduler().runTaskTimer(Main.plugin, new Runnable() { public void run(){ int oldTime = r.getTime(); boolean stageChange = false; int limit = r.getStage() == Stage.PLAYING ? r.getPlayingTime() : r.getPreparationTime(); if (r.getTime() >= limit && limit > 0){ // timer reached its limit if (r.getStage() == Stage.PREPARING){ // if we're still preparing... MinigameRoundStartEvent event = new MinigameRoundStartEvent(r); MGUtil.callEvent(event); if (event.isCancelled()){ return; } r.setStage(Stage.PLAYING); // ...set stage to playing stageChange = true; r.setTime(0); // reset timer } else { // we're playing and the round just ended end(true); stageChange = true; } } if (!stageChange){ r.tick(); } //TODO: Allow for a grace period upon player disconnect if (r.getMinBound() != null){ // this whole bit handles keeping player inside the arena //TODO: Possibly make an event for when a player wanders out of an arena for (MGPlayer p : r.getPlayerList()){ Player pl = p.getBukkitPlayer(); Location l = pl.getLocation(); boolean event = true; boolean toggleFlip = false; if (!getMinigame().getConfigManager().isTeleportationAllowed()){ getMinigame().getConfigManager().setTeleportationAllowed(true); toggleFlip = true; } if (l.getX() < r.getMinBound().getX()){ pl.teleport(new Location(l.getWorld(), r.getMinBound().getX(), l.getY(), l.getZ()), TeleportCause.PLUGIN); } else if (l.getX() > r.getMaxBound().getX()){ pl.teleport(new Location(l.getWorld(), r.getMaxBound().getX(), l.getY(), l.getZ()), TeleportCause.PLUGIN); } else if (l.getY() < r.getMinBound().getY()){ pl.teleport(new Location(l.getWorld(), l.getX(), r.getMinBound().getY(), l.getZ()), TeleportCause.PLUGIN); } else if (l.getY() > r.getMaxBound().getY()){ pl.teleport(new Location(l.getWorld(), l.getX(), r.getMinBound().getY(), l.getZ()), TeleportCause.PLUGIN); } else if (l.getZ() < r.getMinBound().getZ()){ pl.teleport(new Location(l.getWorld(), l.getX(), l.getY(), r.getMinBound().getZ()), TeleportCause.PLUGIN); } else if (l.getZ() > r.getMaxBound().getZ()){ pl.teleport(new Location(l.getWorld(), l.getX(), l.getY(), r.getMinBound().getZ()), TeleportCause.PLUGIN); } else { event = false; } if (toggleFlip){ getMinigame().getConfigManager().setTeleportationAllowed(false); } if (event){ MGUtil.callEvent(new PlayerHitArenaBorderEvent(p)); } } } if (r.getStage() == Stage.PLAYING || r.getStage() == Stage.PREPARING){ MGUtil.callEvent(new MinigameRoundTickEvent(r, oldTime, stageChange)); } } }, 0L, 20L).getTaskId(); // iterates once per second } } else { throw new IllegalStateException(Bukkit.getPluginManager().getPlugin(plugin) + " attempted to start a round which had already been started."); } } public void end(boolean timeUp){ Stage prevStage = this.getStage(); this.setStage(Stage.RESETTING); MinigameRoundEndEvent event = new MinigameRoundEndEvent(this, timeUp); MGUtil.callEvent(event); if (event.isCancelled()){ this.setStage(prevStage); return; } this.setTime(-1); if (this.getTimerHandle() != -1){ Bukkit.getScheduler().cancelTask(this.getTimerHandle()); // cancel the round's timer task } this.timerHandle = -1; // reset timer handle since the task no longer exists for (MGPlayer mp : getPlayerList()){ // iterate and remove players try { removePlayer(mp.getName()); } catch (Exception ex){ // I don't care if this happens } } if (getConfigManager().isRollbackEnabled()) // check if rollbacks are enabled { getRollbackManager().rollback(getArena()); // roll back arena } setStage(Stage.WAITING); } public void end(){ end(false); } /** * Retrieves whether this round has been ended. * @return whether this round has been ended * @since 0.3.0 * @deprecated Returns true only when {@link Round#getStage()} is equal to {@link Stage#RESETTING}. * This comparison should be used instead. */ @Deprecated public boolean hasEnded(){ return this.getStage() == Stage.RESETTING; } /** * Retrieves the location representing the minimum boundary on all three axes of the arena this round takes place * in. * @return the location representing the minimum boundary on all three axes of the arena this round takes place in, * or null if the arena does not have boundaries. * @since 0.1.0 */ public Location getMinBound(){ return minBound; } /** * Retrieves the location representing the maximum boundary on all three axes of the arena this round takes place * in. * @return the location representing the maximum boundary on all three axes of the arena this round takes place in, * or null if the arena does not have boundaries. * @since 0.1.0 */ public Location getMaxBound(){ return maxBound; } /** * Sets the minimum boundary on all three axes of this round object. * @param x the minimum x-value * @param y the minimum y-value * @param z the minimum z-value * @since 0.1.0 */ public void setMinBound(double x, double y, double z){ this.minBound = new Location(this.minBound.getWorld(), x, y, z); } /** * Sets the maximum boundary on all three axes of this round object. * @param x the maximum x-value * @param y the maximum y-value * @param z the maximum z-value * @since 0.1.0 */ public void setMaxBound(double x, double y, double z){ this.minBound = new Location(this.minBound.getWorld(), x, y, z); } /** * Retrieves a list of possible spawns for this round's arena. * @return a list of possible spawns for this round's arena * @since 0.1.0 */ public List<Location> getSpawns(){ return spawns; } /** * Returns the {@link MGPlayer} in this round associated with the given username. * @param player the username to search for * @return the {@link MGPlayer} in this round associated with the given username, or <b>null</b> if none is found * @since 0.1.0 */ public MGPlayer getMGPlayer(String player){ return players.get(player); } /** * Retrieves the world of this arena. * @return the name of the world containing this arena * @since 0.1.0 */ public String getWorld(){ return world; } /** * Adds a player by the given name to this {@link Round round}. * @param name the player to add to this {@link Round round}. (will default to random/sequential (depending on * configuration) if out of bounds). * @return the {@link JoinResult result} of the player being added to the round * @throws PlayerOfflineException if the player is not online * @throws PlayerPresentException if the player is already in a round * @throws RoundFullException if the round is full * @since 0.1.0 */ public JoinResult addPlayer(String name) throws PlayerOfflineException, PlayerPresentException, RoundFullException{ return addPlayer(name, -1); } /** * Adds a player by the given name to this {@link Round round}. * @param name the player to add to this {@link Round round} * @param spawn the spawn number to teleport the player to (will default to random/sequential (depending on * configuration) if out of bounds). * @return the {@link JoinResult result} of the player being added to the round * @throws PlayerOfflineException if the player is not online * @throws PlayerPresentException if the player is already in a round * @throws RoundFullException if the round is full * @since 0.3.0 */ @SuppressWarnings("deprecation") public JoinResult addPlayer(String name, int spawn) throws PlayerOfflineException, PlayerPresentException, RoundFullException{ final Player p = Bukkit.getPlayer(name); MGPlayer mp = Minigame.getMinigameInstance(plugin).getMGPlayer(name); if (mp == null){ if (this.getMinigame().customPlayerClass){ try { Constructor con = getConfigManager().getPlayerClass().getDeclaredConstructor(String.class, String.class, String.class); mp = (MGPlayer) con.newInstance(plugin, name, arena.toLowerCase()); } catch (NoSuchMethodException ex){ // thrown when the required constructor does not exist Main.log.severe("The constructor overriding MGLib's default MGPlayer for plugin " + plugin + " is malformed!"); ex.printStackTrace(); return JoinResult.INTERNAL_ERROR; } catch (InvocationTargetException ex){ // any error thrown from the called constructor ex.getTargetException().printStackTrace(); return JoinResult.INTERNAL_ERROR; } catch (SecurityException ex){ // I have no idea why this would happen. ex.printStackTrace(); return JoinResult.INTERNAL_ERROR; } catch (InstantiationException ex){ // if this happens then the overriding plugin seriously screwed something up Main.log.severe("The constructor overriding MGLib's default MGPlayer for plugin " + plugin + " is malformed!"); ex.printStackTrace(); return JoinResult.INTERNAL_ERROR; } catch (IllegalAccessException ex){ // thrown if the called method from the overriding class is not public Main.log.severe("The constructor overriding MGLib's default MGPlayer for plugin " + plugin + " is not visible!"); ex.printStackTrace(); return JoinResult.INTERNAL_ERROR; } } else { mp = new MGPlayer(plugin, name, arena.toLowerCase()); } } else if (mp.getArena() == null){ mp.setArena(arena.toLowerCase()); } else { throw new PlayerPresentException(); } if (p == null){ // check that the specified player is online throw new PlayerOfflineException(); } if (getPlayerCount() >= getMaxPlayers() && getMaxPlayers() > 0){ throw new RoundFullException(); } if (getStage() == Stage.PREPARING){ if (!getConfigManager().getAllowJoinRoundWhilePreparing()){ p.sendMessage(ChatColor.RED + locale.getMessage("no-join-prepare")); return JoinResult.ROUND_PREPARING; } } else if (getStage() == Stage.PLAYING){ if (!getConfigManager().getAllowJoinRoundInProgress()){ p.sendMessage(ChatColor.RED + locale.getMessage("no-join-progress")); return JoinResult.ROUND_PLAYING; } } PlayerJoinMinigameRoundEvent event = new PlayerJoinMinigameRoundEvent(this, mp); MGUtil.callEvent(event); if (event.isCancelled()){ return JoinResult.CANCELLED; } ItemStack[] contents = p.getInventory().getContents(); PlayerInventory pInv = p.getInventory(); ItemStack helmet = pInv.getHelmet(), chestplate = pInv.getChestplate(), leggings = pInv.getLeggings(), boots = pInv.getBoots(); try { File invDir = new File(Main.plugin.getDataFolder(), "inventories"); File invF = new File(Main.plugin.getDataFolder() + File.separator + "inventories" + File.separator + UUIDFetcher.getUUIDOf(p.getName()) + ".dat"); if (!invF.exists()){ invDir.mkdirs(); invF.createNewFile(); } YamlConfiguration invY = new YamlConfiguration(); invY.load(invF); for (int i = 0; i < contents.length; i++){ invY.set(Integer.toString(i), contents[i]); } if (helmet != null){ invY.set("h", helmet); } if (chestplate != null){ invY.set("c", chestplate); } if (leggings != null){ invY.set("l", leggings); } if (boots != null){ invY.set("b", boots); } invY.save(invF); } catch (Exception ex){ ex.printStackTrace(); p.sendMessage(ChatColor.RED + locale.getMessage("inv-save-fail")); return JoinResult.INVENTORY_SAVE_ERROR; } p.getInventory().clear(); p.getInventory().setArmorContents(new ItemStack[]{null, null, null, null}); p.updateInventory(); for (PotionEffect pe : p.getActivePotionEffects()){ p.removePotionEffect(pe.getType()); // remove any potion effects before adding the player } if ((getStage() == Stage.PREPARING || getStage() == Stage.PLAYING) && getConfigManager().getSpectateOnJoin()){ mp.setSpectating(true); } else { mp.setSpectating(false); } mp.setPrevGameMode(p.getGameMode()); p.setGameMode(getConfigManager().getDefaultGameMode()); players.put(name, mp); // register player with round object mp.spawnIn(); if (getStage() == Stage.WAITING && getPlayerCount() >= getMinPlayers() && getPlayerCount() > 0){ start(); } return JoinResult.SUCCESS; } /** * Removes a given player from this {@link Round round} and teleports them to the given location. * @param name the player to remove from this {@link Round round} * @param location the location to teleport the player to * @throws PlayerOfflineException if the player is not online * @throws NoSuchPlayerException if the player are not in this round * @since 0.1.0 */ public void removePlayer(String name, Location location) throws PlayerOfflineException, NoSuchPlayerException{ @SuppressWarnings("deprecation") Player p = Bukkit.getPlayer(name); MGPlayer mp = players.get(name); if (mp == null){ throw new NoSuchPlayerException(); } if (p != null){ PlayerLeaveMinigameRoundEvent event = new PlayerLeaveMinigameRoundEvent(this, mp); MGUtil.callEvent(event); if (event.isCancelled()){ return; } mp.setSpectating(false); // make sure they're not spectating when they join a new round players.remove(name); // remove player from round p.setGameMode(mp.getPrevGameMode()); // restore the player's gamemode mp.reset(location); // reset the object and send the player to the exit point mp.setArena(null); // they're not in an arena anymore if (this.getPlayerCount() < this.getMinPlayers()){ this.setStage(Stage.WAITING); } } } /** * Removes a given player from this {@link Round round} and teleports them to the round or plugin's default exit * location (defaults to the main world's spawn point). * @param name the player to remove from this {@link Round round} * @throws NoSuchPlayerException if the given player is not in this round * @throws PlayerOfflineException if the given player is offline * @since 0.1.0 */ public void removePlayer(String name) throws PlayerOfflineException, NoSuchPlayerException{ removePlayer(name, getConfigManager().getDefaultExitLocation()); } /** * Retrieves the minimum number of players required to automatically start the round. * @return the minimum number of players required to automatically start the round * @since 0.2.0 */ public int getMinPlayers(){ return minPlayers; } /** * Sets the minimum number of players required to automatically start the round. * @param players the minimum number of players required to automatically start the round * @since 0.2.0 */ public void setMinPlayers(int players){ this.minPlayers = players; } /** * Retrieves the maximum number of players allowed in a round at once. * @return the maximum number of players allowed in a round at once * @since 0.1.0 */ public int getMaxPlayers(){ return maxPlayers; } /** * Sets the maximum number of players allowed in a round at once. * @param players the maximum number of players allowed in a round at once * @since 0.1.0 */ public void setMaxPlayers(int players){ this.maxPlayers = players; } /** * Creates a new LobbySign to be managed * @param location the location to create the sign at * @param type the type of the sign ("status" or "players") * @param index the number of the sign (applicable only for "players" signs) * @throws NoSuchArenaException if the specified arena does not exist * @throws InvalidLocationException if the specified location does not contain a sign * @throws IndexOutOfBoundsException if the specified index for a player sign is less than 1 * @since 0.1.0 */ public void addSign(Location location, LobbyType type, int index) throws NoSuchArenaException, InvalidLocationException, IndexOutOfBoundsException{ this.getMinigame().getLobbyManager().add(location, this.getArena(), type, index); } /** * Updates all lobby signs linked to this round's arena. * @since 0.1.0 */ public void updateSigns(){ this.getMinigame().getLobbyManager().update(arena); } /** * Retrieves this round's exit location. * @return this round's exit location * @since 0.1.0 */ public Location getExitLocation(){ return exitLocation; } /** * Sets this round's exit location. * @param location the new exit location for this round * @since 0.1.0 */ public void setExitLocation(Location location){ this.exitLocation = location; } /** * Retrieves whether PvP is allowed. * @return whether PvP is allowed * @since 0.1.0 */ public boolean isPvPAllowed(){ return pvp; } /** * Sets whether PvP is allowed. * @param allowed whether PvP is allowed * @since 0.1.0 */ public void setPvPAllowed(boolean allowed){ this.pvp = allowed; } /** * Retrieves whether players in rounds may receive damage. (default: true) * @return whether players in rounds may receive damage * @since 0.1.0 */ public boolean isDamageAllowed(){ return damage; } /** * Sets whether players in rounds may receive damage. (default: false) * @param allowed whether players in rounds may receive damage * @since 0.1.0 */ public void setDamageAllowed(boolean allowed){ this.damage = allowed; } /** * Retrieves whether rollback is enabled in this round. * @return whether rollback is enabled in this round * @since 0.2.0 */ public boolean isRollbackEnabled(){ return rollback; } /** * Sets whether rollback is enabled by default. * @param enabled whether rollback is enabled by default * @since 0.2.0 */ public void setRollbackEnabled(boolean enabled){ this.rollback = enabled; } /** * Retrieves the {@link ConfigManager} of the plugin owning this round. * @return the {@link ConfigManager} of the plugin owning this round * @since 0.2.0 */ public ConfigManager getConfigManager(){ return getMinigame().getConfigManager(); } /** * Retrieves the {@link RollbackManager} of the plugin owning this round * @return the {@link RollbackManager} of the plugin owning this round * @since 0.2.0 */ public RollbackManager getRollbackManager(){ return getMinigame().getRollbackManager(); } /** * Broadcasts a message to all players in this round. * @param message the message to broadcast * @param broadcastToSpectators whether the message should be broadcast to spectators * @since 0.2.0 */ public void broadcast(String message, boolean broadcastToSpectators){ for (MGPlayer p : players.values()){ if ((!p.isSpectating() || broadcastToSpectators) && p.getBukkitPlayer() != null){ p.getBukkitPlayer().sendMessage(message); } } } /** * Broadcasts a message to all players in this round. * @param message the message to broadcast * @since 0.2.0 */ public void broadcast(String message){ broadcast(message, true); } /** * Retrieves the display name of the round's arena. * @return the display name of the round's arena * @since 0.3.0 */ public String getDisplayName(){ return displayName; } public Object getMetadata(String key){ return metadata.get(key); } public void setMetadata(String key, Object value){ metadata.put(key, value); } public void removeMetadata(String key){ metadata.remove(key); } public boolean hasMetadata(String key){ return metadata.containsKey(key); } public HashMap<String, Object> getAllMetadata(){ return metadata; } public boolean equals(Object p){ return p instanceof Round && arena.equals(((Round)p).getArena()); } public int hashCode(){ return 41 * (plugin.hashCode() + arena.hashCode() + 41); } }
package net.amigocraft.mglib.api; import static net.amigocraft.mglib.MGUtil.*; import static net.amigocraft.mglib.Main.locale; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Random; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.potion.PotionEffect; import com.google.common.collect.Lists; import net.amigocraft.mglib.MGUtil; import net.amigocraft.mglib.Main; import net.amigocraft.mglib.RollbackManager; import net.amigocraft.mglib.UUIDFetcher; import net.amigocraft.mglib.event.player.PlayerHitArenaBorderEvent; import net.amigocraft.mglib.event.player.PlayerJoinMinigameRoundEvent; import net.amigocraft.mglib.event.player.PlayerLeaveMinigameRoundEvent; import net.amigocraft.mglib.event.round.MinigameRoundEndEvent; import net.amigocraft.mglib.event.round.MinigameRoundPrepareEvent; import net.amigocraft.mglib.event.round.MinigameRoundStartEvent; import net.amigocraft.mglib.event.round.MinigameRoundTickEvent; import net.amigocraft.mglib.exception.ArenaNotExistsException; import net.amigocraft.mglib.exception.InvalidLocationException; import net.amigocraft.mglib.exception.PlayerNotPresentException; import net.amigocraft.mglib.exception.PlayerOfflineException; import net.amigocraft.mglib.exception.PlayerPresentException; import net.amigocraft.mglib.exception.RoundFullException; import net.amigocraft.mglib.misc.JoinResult; import net.amigocraft.mglib.misc.Metadatable; public class Round implements Metadatable { private int minPlayers; private int maxPlayers; private int prepareTime; private int roundTime; private Location exitLocation; private String plugin; private int time = 0; private Stage stage; private String world; private String arena; private List<Location> spawns = new ArrayList<Location>(); private Location minBound; private Location maxBound; private HashMap<String, MGPlayer> players = new HashMap<String, MGPlayer>(); private int timerHandle = -1; private boolean damage; private boolean pvp; private boolean rollback; /** * Creates a new {@link Round} with the given parameters. * <br><br> * Please use {@link Minigame#createRound(String)} unless you * understand the implications of using this constructor. * @param plugin the plugin which this round should be associated with. * @param arena the name of the arena in which this round takes place in. * @throws ArenaNotExistsException if the specified arena does not exist. */ public Round(String plugin, String arena) throws ArenaNotExistsException { YamlConfiguration y = loadArenaYaml(plugin); if (!y.contains(arena)) throw new ArenaNotExistsException(); ConfigurationSection cs = y.getConfigurationSection(arena); // make the code easier to read world = cs.getString("world"); // get the name of the world of the arena World w = Bukkit.getWorld(world); // convert it to a Bukkit world if (w == null){ // but what if world is kill? throw new IllegalArgumentException("World " + world + " cannot be loaded!"); // then round is kill } for (String k : cs.getConfigurationSection("spawns").getKeys(false)){ // load spawns into round object Location l = new Location(w, cs.getDouble("spawns." + k + ".x"), cs.getDouble("spawns." + k + ".y"), cs.getDouble("spawns." + k + ".z")); if (cs.isSet(k + ".pitch")) l.setPitch((float)cs.getDouble(cs.getCurrentPath() + ".spawns." + k + ".pitch")); if (cs.isSet(k + ".yaw")) l.setYaw((float)cs.getDouble(cs.getCurrentPath() + ".spawns." + k + ".yaw")); spawns.add(l); // register spawn } if (cs.getBoolean("boundaries")){ // check if arena has boundaries defined minBound = new Location(w, cs.getDouble("minX"), cs.getDouble("minY"), cs.getDouble("minZ")); maxBound = new Location(w, cs.getDouble("maxX"), cs.getDouble("maxY"), cs.getDouble("maxZ")); } else { minBound = null; maxBound = null; } this.plugin = plugin; // set globals this.arena = arena; ConfigManager cm = getConfigManager(); this.prepareTime = cm.getDefaultPreparationTime(); this.roundTime = cm.getDefaultPlayingTime(); this.minPlayers = cm.getMinPlayers(); this.maxPlayers = cm.getMaxPlayers(); this.exitLocation = cm.getDefaultExitLocation(); this.damage = cm.isDamageAllowed(); this.pvp = cm.isPvPAllowed(); this.rollback = cm.isRollbackEnabled(); stage = Stage.WAITING; // default to waiting stage String[] defaultKeysA = new String[]{"world", "spawns", "minX", "minY", "minZ", "maxX", "maxY", "maxZ"}; List<String> defaultKeys = Arrays.asList(defaultKeysA); for (String k : cs.getKeys(true)) if (!defaultKeys.contains(k.contains(".") ? k.split(".")[0] : k)) setMetadata(k, cs.get(k)); Minigame.getMinigameInstance(plugin).getRounds().put(arena, this); // register round with minigame instance } /** * Gets the name of the minigame plugin associated with this {@link Round}. * @return The name of the minigame plugin associated with this {@link Round}. * @since 0.1.0 */ public String getPlugin(){ return plugin; } /** * Gets the instance of the MGLib API registered by the plugin associated with this {@link Round}. * @return The instance of the MGLib API registered by the plugin associated with this {@link Round}. * @since 0.1.0 */ public Minigame getMinigame(){ return Minigame.getMinigameInstance(plugin); } /** * Gets the name of the arena associated with this {@link Round}. * @return The name of the arena associated with this {@link Round}. * @since 0.1.0 */ public String getArena(){ return arena; } /** * Gets the current {@link Stage} of this {@link Round}. * @return The current {@link Stage} of this {@link Round}. * @since 0.1.0 */ public Stage getStage(){ return stage; } /** * Gets the current time in seconds of this {@link Round}, where 0 represents the first second of it. * @return the current time in seconds of this {@link Round}, where 0 represents the first second of it. * @since 0.1.0 */ public int getTime(){ return time; } /** * Gets the time remaining in this round. * @return the time remaining in this round, or -1 if there is no time limit or if the {@link Stage stage} is not * {@link Stage#PLAYING PLAYING} or {@link Stage#PREPARING PREPARING} * @since 0.1.0 */ public int getRemainingTime(){ switch (this.getStage()){ case PREPARING: if (this.getPreparationTime() > 0) return this.getPreparationTime() - this.getTime(); else return -1; case PLAYING: if (this.getPlayingTime() > 0) return this.getPlayingTime() - this.getTime(); else return -1; default: return -1; } } /** * Gets the round's preparation time. * @return The round's preparation time. * @since 0.1.0 */ public int getPreparationTime(){ return prepareTime; } /** * Gets the round's playing time. * @return The round's playing time. * @since 0.1.0 */ public int getPlayingTime(){ return roundTime; } /** * Gets the round's timer's task's handle, or -1 if a timer is not started. * @return The round's timer's task's handle, or -1 if a timer is not started. * @since 0.1.0 */ public int getTimerHandle(){ return timerHandle; } /** * Sets the associated arena of this {@link Round}. * @param arena The arena to associate with this {@link Round}. * @since 0.1.0 */ public void setArena(String arena){ this.arena = arena; } /** * Sets the current stage of this {@link Round}. * @param s The stage to set this {@link Round} to. * @since 0.1.0 */ public void setStage(Stage s){ stage = s; } /** * Sets the remaining time of this {@link Round}. * @param t The time to set this {@link Round} to. * @since 0.1.0 */ public void setTime(int t){ time = t; } /** * Sets the round's preparation time. * @param t The number of seconds to set the preparation time to. Use -1 for no limit, or 0 for * no preparation phase. * @since 0.1.0 */ public void setPreparationTime(int t){ prepareTime = t; } /** * Sets the round's playing time. * @param t The number of seconds to set the preparation time to. Use -1 for no limit. * @since 0.1.0 */ public void setPlayingTime(int t){ roundTime = t; } /** * Decrements the time remaining in the round by 1. * <br><br> * Please do not call this method from your plugin unless you understand the implications. Let MGLib handle * the timer. * @since 0.1.0 */ public void tick(){ time += 1; } /** * Subtracts <b>t</b> seconds from the elapsed time in the round. * @param t The number of seconds to subtract. * @since 0.1.0 */ public void subtractTime(int t){ time -= t; } /** * Adds <b>t</b> seconds to the elapsed time in the round. * @param t The number of seconds to add. * @since 0.1.0 */ public void addTime(int t){ time += t; } /** * Destroys this {@link Round}. * <br><br> * <b>Please do not call this method from your plugin unless you understand the implications.</b> * @since 0.1.0 */ public void destroy(){ Minigame.getMinigameInstance(plugin).getRounds().remove(this); } /** * Retrieves a list of {@link MGPlayer MGPlayers} in this round. * @return A list of {@link MGPlayer MGPlayers} in this round. * @since 0.1.0 */ public List<MGPlayer> getPlayerList(){ return Lists.newArrayList(players.values()); } /** * Retrieves a {@link HashMap} of players in this round. * @return a {@link HashMap} mapping the names of players in the round to their respective {@link MGPlayer} objects. * @since 0.1.0 */ public HashMap<String, MGPlayer> getPlayers(){ return players; } /** * Retrieves a {@link HashMap} of all players on a given team. * @param team the team to retrieve players from. * @return a {@link HashMap} mapping the names of players on a given team to their respective {@link MGPlayer} objects. * @since 0.3.0 */ public HashMap<String, MGPlayer> getTeam(String team){ HashMap<String, MGPlayer> t = new HashMap<String, MGPlayer>(); for (MGPlayer p : getPlayerList()){ if (p.getTeam() != null && p.getTeam().equals(team)) t.put(p.getName(), p); } return t; } /** * Retrieves a list of non-spectating {@link MGPlayer MGPlayers} in this round. * @return a list of non-spectating {@link MGPlayer MGPlayers} in this round. * @since 0.2.0 */ public List<MGPlayer> getAlivePlayerList(){ List<MGPlayer> list = new ArrayList<MGPlayer>(); for (MGPlayer p : players.values()) if (!p.isSpectating()) list.add(p); return list; } /** * Retrieves a list of spectating {@link MGPlayer MGPlayers} in this {@link Round}. * @return a list of spectating {@link MGPlayer MGPlayers} in this {@link Round}. * @since 0.2.0 */ public List<MGPlayer> getSpectatingPlayerList(){ List<MGPlayer> list = new ArrayList<MGPlayer>(); for (MGPlayer p : players.values()) if (p.isSpectating()) list.add(p); return list; } /** * Retrieves the number of {@link MGPlayer MGPlayers} in this {@link Round}. * @return the number of {@link MGPlayer MGPlayers} in this {@link Round}. * @since 0.2.0 */ public int getPlayerCount(){ return players.size(); } /** * Retrieves the number of in-game (non-spectating) {@link MGPlayer MGPlayers} in this {@link Round}. * @return the number of in-game (non-spectating) {@link MGPlayer MGPlayers} in this {@link Round}. * @since 0.2.0 */ public int getAlivePlayerCount(){ int count = 0; for (MGPlayer p : players.values()) if (!p.isSpectating()) count += 1; return count; } /** * Retrieves the number of spectating {@link MGPlayer MGPlayers} in this {@link Round}. * @return the number of spectating {@link MGPlayer MGPlayers} in this {@link Round}. * @since 0.2.0 */ public int getSpectatingPlayerCount(){ int count = 0; for (MGPlayer p : players.values()) if (p.isSpectating()) count += 1; return count; } public void start(){ if (stage == Stage.WAITING){ // make sure the round isn't already started final Round r = this; if (r.getPreparationTime() > 0){ r.setTime(0); // reset time r.setStage(Stage.PREPARING); // set stage to preparing MGUtil.callEvent(new MinigameRoundPrepareEvent(r)); // call an event for anyone who cares } else { r.setTime(0); // reset timer r.setStage(Stage.PLAYING); MGUtil.callEvent(new MinigameRoundStartEvent(r)); } if (time != -1){ // I'm pretty sure this is wrong, but I'm also pretty tired timerHandle = Bukkit.getScheduler().runTaskTimer(Main.plugin, new Runnable(){ public void run(){ int oldTime = r.getTime(); boolean stageChange = false; int limit = r.getStage() == Stage.PLAYING ? r.getPlayingTime() : r.getPreparationTime(); if (r.getTime() >= limit && limit > 0){ // timer reached its limit if (r.getStage() == Stage.PREPARING){ // if we're still preparing... r.setStage(Stage.PLAYING); // ...set stage to playing stageChange = true; r.setTime(0); // reset timer MGUtil.callEvent(new MinigameRoundStartEvent(r)); } else { // we're playing and the round just ended end(true); stageChange = true; } } if (!stageChange) r.tick(); //TODO: Allow for a grace period upon player disconnect if (r.getMinBound() != null){ // this whole bit handles keeping player inside the arena //TODO: Possibly make an event for when a player wanders out of an arena for (MGPlayer p : r.getPlayerList()){ Player pl = p.getBukkitPlayer(); Location l = pl.getLocation(); boolean event = true; if (l.getX() < r.getMinBound().getX()) pl.teleport(new Location(l.getWorld(), r.getMinBound().getX(), l.getY(), l.getZ()), TeleportCause.PLUGIN); else if (l.getX() > r.getMaxBound().getX()) pl.teleport(new Location(l.getWorld(), r.getMaxBound().getX(), l.getY(), l.getZ()), TeleportCause.PLUGIN); else if (l.getY() < r.getMinBound().getY()) pl.teleport(new Location(l.getWorld(), l.getX(), r.getMinBound().getY(), l.getZ()), TeleportCause.PLUGIN); else if (l.getY() > r.getMaxBound().getY()) pl.teleport(new Location(l.getWorld(), l.getX(), r.getMinBound().getY(), l.getZ()), TeleportCause.PLUGIN); else if (l.getZ() < r.getMinBound().getZ()) pl.teleport(new Location(l.getWorld(), l.getX(), l.getY(), r.getMinBound().getZ()), TeleportCause.PLUGIN); else if (l.getZ() > r.getMaxBound().getZ()) pl.teleport(new Location(l.getWorld(), l.getX(), l.getY(), r.getMinBound().getZ()), TeleportCause.PLUGIN); else event = false; if (event) MGUtil.callEvent(new PlayerHitArenaBorderEvent(p)); } } if (r.getStage() == Stage.PLAYING || r.getStage() == Stage.PREPARING) MGUtil.callEvent(new MinigameRoundTickEvent(r, oldTime, stageChange)); } }, 0L, 20L).getTaskId(); // iterates once per second } } else throw new IllegalStateException(Bukkit.getPluginManager().getPlugin(plugin) + " attempted to start a round which had already been started."); } public void end(boolean timeUp){ setTime(-1); if (timerHandle != -1) Bukkit.getScheduler().cancelTask(timerHandle); // cancel the round's timer task stage = Stage.WAITING; // set stage back to waiting timerHandle = -1; // reset timer handle since the task no longer exists for (MGPlayer mp : getPlayerList()){ // iterate and remove players try { removePlayer(mp.getName()); } catch (Exception ex){} // I don't care if this happens } MGUtil.callEvent(new MinigameRoundEndEvent(this, timeUp)); if (getConfigManager().isRollbackEnabled()) // check if rollbacks are enabled getRollbackManager().rollback(getArena()); // roll back arena } public void end(){ end(false); } /** * Retrieves the location representing the minimum boundary on all three axes of the arena this round takes place in. * @return the location representing the minimum boundary on all three axes of the arena this round takes place in, or * null if the arena does not have boundaries. * @since 0.1.0 */ public Location getMinBound(){ return minBound; } /** * Retrieves the location representing the maximum boundary on all three axes of the arena this round takes place in. * @return the location representing the maximum boundary on all three axes of the arena this round takes place in, or * null if the arena does not have boundaries. * @since 0.1.0 */ public Location getMaxBound(){ return maxBound; } /** * Sets the minimum boundary on all three axes of this round object. * @param x The minimum x-value. * @param y The minimum y-value. * @param z The minimum z-value. * @since 0.1.0 */ public void setMinBound(double x, double y, double z){ this.minBound = new Location(this.minBound.getWorld(), x, y, z); } /** * Sets the maximum boundary on all three axes of this round object. * @param x The maximum x-value. * @param y The maximum y-value. * @param z The maximum z-value. * @since 0.1.0 */ public void setMaxBound(double x, double y, double z){ this.minBound = new Location(this.minBound.getWorld(), x, y, z); } /** * Retrieves a list of possible spawns for this round's arena. * @return a list of possible spawns for this round's arena. * @since 0.1.0 */ public List<Location> getSpawns(){ return spawns; } /** * Returns the {@link MGPlayer} in this round associated with the given username. * @param player The username to search for. * @return The {@link MGPlayer} in this round associated with the given username, or <b>null</b> if none is found. * @since 0.1.0 */ public MGPlayer getMGPlayer(String player){ return players.get(player); } /** * Retrieves the world of this arena. * @return The name of the world containing this arena. * @since 0.1.0 */ public String getWorld(){ return world; } /** * Adds a player by the given name to this {@link Round round}. * @param name the player to add to this {@link Round round}. * (will default to random/sequential (depending on configuration) if out of bounds). * @return the {@link JoinResult result} of the player being added to the round. * @throws PlayerOfflineException if the player is not online. * @throws PlayerPresentException if the player is already in a round. * @throws RoundFullException if the round is full. * @since 0.1.0 */ public JoinResult addPlayer(String name) throws PlayerOfflineException, PlayerPresentException, RoundFullException { return addPlayer(name, -1); } /** * Adds a player by the given name to this {@link Round round}. * @param name the player to add to this {@link Round round}. * @param spawn the spawn number to teleport the player to * (will default to random/sequential (depending on configuration) if out of bounds). * @return the {@link JoinResult result} of the player being added to the round. * @throws PlayerOfflineException if the player is not online. * @throws PlayerPresentException if the player is already in a round. * @throws RoundFullException if the round is full. * @since 0.3.0 */ @SuppressWarnings("deprecation") public JoinResult addPlayer(String name, int spawn) throws PlayerOfflineException, PlayerPresentException, RoundFullException { final Player p = Bukkit.getPlayer(name); if (p == null) // check that the specified player is online throw new PlayerOfflineException(); if (getPlayerCount() >= getMaxPlayers() && getMaxPlayers() > 0) throw new RoundFullException(); if (getStage() == Stage.PREPARING){ if (!getConfigManager().getAllowJoinRoundWhilePreparing()){ p.sendMessage(ChatColor.RED + locale.getMessage("no-join-prepare")); return JoinResult.ROUND_PREPARING; } } else if (getStage() == Stage.PLAYING){ if (!getConfigManager().getAllowJoinRoundInProgress()){ p.sendMessage(ChatColor.RED + locale.getMessage("no-join-progress")); return JoinResult.ROUND_PLAYING; } } MGPlayer mp = Minigame.getMinigameInstance(plugin).getMGPlayer(name); if (mp == null){ try { mp = (MGPlayer)getConfigManager().getPlayerClass().getDeclaredConstructors()[0] .newInstance(plugin, name, arena); } catch (InvocationTargetException ex){ // any error thrown from the called constructor ex.getTargetException().printStackTrace(); } catch (IllegalArgumentException ex){ // thrown when the overriding constructor doesn't match what's expected Main.log.severe("The constructor overriding MGLib's default MGPlayer for plugin " + plugin + " is malformed"); ex.printStackTrace(); } catch (SecurityException ex){ // I have no idea why this would happen. ex.printStackTrace(); } catch (InstantiationException ex){ // if this happens then the overriding plugin seriously screwed something up Main.log.severe("The constructor overriding MGLib's default MGPlayer for plugin " + plugin + " is seriously wack. Fix it, developer."); ex.printStackTrace(); } catch (IllegalAccessException ex){ // thrown if the called method from the overriding class is not public Main.log.severe("The constructor overriding MGLib's default MGPlayer for plugin " + plugin + " is not visible"); ex.printStackTrace(); } } else if (mp.getArena() == null) mp.setArena(arena); else throw new PlayerPresentException(); ItemStack[] contents = p.getInventory().getContents(); PlayerInventory pInv = (PlayerInventory)p.getInventory(); ItemStack helmet = pInv.getHelmet(), chestplate = pInv.getChestplate(), leggings = pInv.getLeggings(), boots = pInv.getBoots(); try { File invDir = new File(Main.plugin.getDataFolder(), "inventories"); File invF = new File(Main.plugin.getDataFolder() + File.separator + "inventories" + File.separator + UUIDFetcher.getUUIDOf(p.getName()) + ".dat"); if (!invF.exists()){ invDir.mkdirs(); invF.createNewFile(); } YamlConfiguration invY = new YamlConfiguration(); invY.load(invF); for (int i = 0; i < contents.length; i++) invY.set(Integer.toString(i), contents[i]); if (helmet != null) invY.set("h", helmet); if (chestplate != null) invY.set("c", chestplate); if (leggings != null) invY.set("l", leggings); if (boots != null) invY.set("b", boots); invY.save(invF); } catch (Exception ex){ ex.printStackTrace(); p.sendMessage(ChatColor.RED + locale.getMessage("inv-save-fail")); return JoinResult.INVENTORY_SAVE_ERROR; } ((PlayerInventory)p.getInventory()).clear(); ((PlayerInventory)p.getInventory()).setArmorContents(new ItemStack[]{null, null, null, null}); p.updateInventory(); for (PotionEffect pe : p.getActivePotionEffects()) p.removePotionEffect(pe.getType()); // remove any potion effects before adding the player if ((getStage() == Stage.PREPARING || getStage() == Stage.PLAYING) && getConfigManager().getSpectateOnJoin()) mp.setSpectating(true); else mp.setSpectating(false); mp.setPrevGameMode(p.getGameMode()); p.setGameMode(getConfigManager().getDefaultGameMode()); players.put(name, mp); // register player with round object Location sp = (spawn >= 0 && spawns.size() > spawn) ? spawns.get(spawn) : getConfigManager().isRandomSpawning() ? spawns.get(new Random().nextInt(spawns.size())) : spawns.get(players.size() % spawns.size()); p.teleport(sp, TeleportCause.PLUGIN); // teleport the player to it MGUtil.callEvent(new PlayerJoinMinigameRoundEvent(this, mp)); if (getStage() == Stage.WAITING && getPlayerCount() >= getMinPlayers() && getPlayerCount() > 0) start(); return JoinResult.SUCCESS; } /** * Removes a given player from this {@link Round round} and teleports them to the given location. * @param name The player to remove from this {@link Round round}. * @param location The location to teleport the player to. * @throws PlayerOfflineException if the player is not online. * @throws PlayerNotPresentException if the player are not in this round. * @since 0.1.0 */ public void removePlayer(String name, Location location) throws PlayerOfflineException, PlayerNotPresentException { @SuppressWarnings("deprecation") Player p = Bukkit.getPlayer(name); MGPlayer mp = players.get(name); if (mp == null) throw new PlayerNotPresentException(); if (p != null){ mp.setArena(null); // they're not in an arena anymore mp.setSpectating(false); // make sure they're not dead when they join a new round players.remove(name); // remove player from round p.setGameMode(mp.getPrevGameMode()); // restore the player's gamemode mp.reset(location); // reset the object and send the player to the exit point } PlayerLeaveMinigameRoundEvent event = new PlayerLeaveMinigameRoundEvent(this, mp); MGUtil.callEvent(event); } /** * Removes a given player from this {@link Round round} and teleports them to the round or plugin's default exit location * (defaults to the main world's spawn point). * @param name The player to remove from this {@link Round round}. * @throws PlayerNotPresentException if the given player is not in this round. * @throws PlayerOfflineException if the given player is offline. * @since 0.1.0 */ public void removePlayer(String name) throws PlayerOfflineException, PlayerNotPresentException{ removePlayer(name, getConfigManager().getDefaultExitLocation()); } /** * Retrieves the minimum number of players required to automatically start the round. * @return the minimum number of players required to automatically start the round. * @since 0.2.0 */ public int getMinPlayers(){ return minPlayers; } /** * Sets the minimum number of players required to automatically start the round. * @param players the minimum number of players required to automatically start the round. * @since 0.2.0 */ public void setMinPlayers(int players){ this.minPlayers = players; } /** * Retrieves the maximum number of players allowed in a round at once. * @return the maximum number of players allowed in a round at once. * @since 0.1.0 */ public int getMaxPlayers(){ return maxPlayers; } /** * Sets the maximum number of players allowed in a round at once. * @param players the maximum number of players allowed in a round at once. * @since 0.1.0 */ public void setMaxPlayers(int players){ this.maxPlayers = players; } /** * Creates a new LobbySign to be managed * @param location The location to create the sign at. * @param type The type of the sign ("status" or "players") * @param index The number of the sign (applicable only for "players" signs) * @throws ArenaNotExistsException if the specified arena does not exist. * @throws InvalidLocationException if the specified location does not contain a sign. * @throws IndexOutOfBoundsException if the specified index for a player sign is less than 1. * @since 0.1.0 */ public void addSign(Location location, LobbyType type, int index) throws ArenaNotExistsException, InvalidLocationException, IndexOutOfBoundsException { this.getMinigame().getLobbyManager().add(location, this.getArena(), type, index); } /** * Updates all lobby signs linked to this round's arena. * @since 0.1.0 */ public void updateSigns(){ this.getMinigame().getLobbyManager().update(arena); } /** * Retrieves this round's exit location. * @return this round's exit location. * @since 0.1.0 */ public Location getExitLocation(){ return exitLocation; } /** * Sets this round's exit location. * @param location the new exit location for this round. * @since 0.1.0 */ public void setExitLocation(Location location){ this.exitLocation = location; } /** * Retrieves whether PvP is allowed. * @return whether PvP is allowed. * @since 0.1.0 */ public boolean isPvPAllowed(){ return pvp; } /** * Sets whether PvP is allowed. * @param allowed whether PvP is allowed. * @since 0.1.0 */ public void setPvPAllowed(boolean allowed){ this.pvp = allowed; } /** * Retrieves whether players in rounds may receive damage. (default: true) * @return whether players in rounds may receive damage. * @since 0.1.0 */ public boolean isDamageAllowed(){ return damage; } /** * Sets whether players in rounds may receive damage. (default: false) * @param allowed whether players in rounds may receive damage. * @since 0.1.0 */ public void setDamageAllowed(boolean allowed){ this.damage = allowed; } /** * Retrieves whether rollback is enabled in this round. * @return whether rollback is enabled in this round. * @since 0.2.0 */ public boolean isRollbackEnabled(){ return rollback; } /** * Sets whether rollback is enabled by default. * @param enabled whether rollback is enabled by default. * @since 0.2.0 */ public void setRollbackEnabled(boolean enabled){ this.rollback = enabled; } /** * Retrieves the {@link ConfigManager} of the plugin owning this round. * @return the {@link ConfigManager} of the plugin owning this round. * @since 0.2.0 */ public ConfigManager getConfigManager(){ return getMinigame().getConfigManager(); } /** * Retrieves the {@link RollbackManager} of the plugin owning this round. * @return the {@link RollbackManager} of the plugin owning this round. * @since 0.2.0 */ public RollbackManager getRollbackManager(){ return getMinigame().getRollbackManager(); } /** * Broadcasts a message to all players in this round. * @param message the message to broadcast. * @param broadcastToSpectators whether the message should be broadcast to spectators. * @since 0.2.0 */ public void broadcast(String message, boolean broadcastToSpectators){ for (MGPlayer p : players.values()) if (!p.isSpectating() || broadcastToSpectators) p.getBukkitPlayer().sendMessage(message); } /** * Broadcasts a message to all players in this round. * @param message the message to broadcast. * @since 0.2.0 */ public void broadcast(String message){ broadcast(message, true); } @Override public Object getMetadata(String key){ return metadata.get(key); } @Override public void setMetadata(String key, Object value){ metadata.put(key, value); } @Override public void removeMetadata(String key){ metadata.remove(key); } @Override public boolean hasMetadata(String key){ return metadata.containsKey(key); } @Override public HashMap<String, Object> getAllMetadata(){ return metadata; } public boolean equals(Object p){ Round r = (Round)p; return arena.equals(r.getArena()); } public int hashCode(){ return 41 * (plugin.hashCode() + arena.hashCode() + 41); } }
package net.databinder; import java.net.URL; import java.util.Locale; import javax.servlet.http.HttpServletResponse; import net.databinder.components.PageExpiredCookieless; import net.databinder.util.URLConverter; import org.hibernate.cfg.AnnotationConfiguration; import wicket.ISessionFactory; import wicket.Session; import wicket.markup.html.pages.PageExpiredErrorPage; import wicket.protocol.http.BufferedWebResponse; import wicket.protocol.http.WebApplication; import wicket.protocol.http.WebResponse; import wicket.util.convert.Converter; import wicket.util.convert.IConverterFactory; /** * Databinder Application subclass for request cycle hooks and a basic configuration. * @author Nathan Hamblen */ public abstract class DataApplication extends WebApplication { /** true if in development mode, false if deployment */ private boolean development; /** true if cookieless use is supported through URL rewriting(defaults to true). */ private boolean cookielessSupported = true; /** * Configures this application for development or production, turns off * default page versioning, and establishes a DataSession factory, and * initializes Hibernate. Development mode is the default; set a JVM property of * wicket.configuration=deployment for production. (The context and init params * in wicket.protocol.http.WebApplication are not supported here). Override * this method for further customization. */ @Override protected void init() { // this databinder-specific parameter will eventually be dropped in favor // of wicket.configuration String configuration = System.getProperty("net.databinder.configuration"); if (configuration != null) configure(configuration); else configuration = System.getProperty("wicket." + CONFIGURATION, DEVELOPMENT); // (if using wicket.configuration, calling configure() is unnecessary) development = configuration.equalsIgnoreCase(DEVELOPMENT); // versioning doesn't do so much for database driven pages getPageSettings().setVersionPagesByDefault(false); getApplicationSettings().setConverterFactory(new IConverterFactory() { /** Registers URLConverter in addition to the Wicket defaults. */ public wicket.util.convert.IConverter newConverter(Locale locale) { Converter conv = new Converter(locale); conv.set(URL.class, new URLConverter()); return conv; } }); setSessionFactory(new ISessionFactory() { public Session newSession() { return newDataSession(); } }); DataRequestCycle.initHibernate(); // don't wait for first request } /** * Returns a new instance of a DataSession. Override if your application uses * its own DataSession subclass. * @return new instance of DataSession */ protected DataSession newDataSession() { return new DataSession(DataApplication.this); } /** * Reports if the program is running in a development environment, as determined by the * "wicket.configuration" environment variable. If that variable is unset or set to * "development", the app is considered to be running in development. * @return true if running in a development environment */ protected boolean isDevelopment() { return development; } /** * Override to add annotated classes for persistent storage by Hibernate, but don't forget * to call this super-implementation. If running in a development environment, * the session factory is set for hbm2ddl auto updating to create and add columns to tables * as required. Otherwise, it is configured for C3P0 connection pooling. (At present the two * seem to be incompatible.) If you don't want this behaviour, don't call the * super-implementation. * @param config used to build Hibernate session factory */ protected void configureHibernate(AnnotationConfiguration config) { if (isDevelopment()) config.setProperty("hibernate.hbm2ddl.auto", "update"); else { config.setProperty("hibernate.c3p0.max_size", "20") .setProperty("hibernate.c3p0.timeout","3000") .setProperty("hibernate.c3p0.idle_test_period", "300"); } } /** * If <code>isCookielessSupported()</code> returns false, this method returns * a custom WebResponse that disables URL rewriting. */ @Override protected WebResponse newWebResponse(final HttpServletResponse servletResponse) { if (isCookielessSupported()) return super.newWebResponse(servletResponse); if (getRequestCycleSettings().getBufferResponse()) return new BufferedWebResponse(servletResponse) { @Override public CharSequence encodeURL(CharSequence url) { return url; } }; else return (new WebResponse(servletResponse) { @Override public CharSequence encodeURL(CharSequence url) { return url; } }); } /** * @return true if cookieless use is supported through URL rewriting. */ public boolean isCookielessSupported() { return cookielessSupported; } /** * Set to false to disable URL rewriting and consequentally hamper cookieless * browsing. Users with cookies disabled, and more importantly search engines, * will still be able to browse the application through bookmarkable URLs. Because * rewriting is disabled, these URLs will have no jsessionid appended and will * remain static. * <p> The Application's "page expired" error page will be set to PageExpiredCookieless * if cookielessSupported is false, unless an alternate error page has already been * specified. This page will appear when cookieless users try to follow a link or * form-submit that requires a session, informing them that cookies are required. * </p> * @param cookielessSupported true if cookieless use is supported through * URL rewriting * @see net.databinder.components.PageExpiredCookieless */ protected void setCookielessSupported(boolean cookielessSupported) { Class expected = this.cookielessSupported ? PageExpiredErrorPage.class : PageExpiredCookieless.class; this.cookielessSupported = cookielessSupported; if (getApplicationSettings().getPageExpiredErrorPage().equals(expected)) getApplicationSettings().setPageExpiredErrorPage(cookielessSupported ? PageExpiredErrorPage.class : PageExpiredCookieless.class); } }
package com.zhan_dui.animetaste; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Typeface; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v7.app.ActionBarActivity; import android.text.InputFilter; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.OrientationEventListener; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import com.avos.avoscloud.AVException; import com.avos.avoscloud.AVOSCloud; import com.avos.avoscloud.AVObject; import com.avos.avoscloud.AVQuery; import com.avos.avoscloud.SaveCallback; import com.baidu.cyberplayer.core.BVideoView; import com.baidu.cyberplayer.core.BVideoView.OnCompletionListener; import com.baidu.cyberplayer.core.BVideoView.OnErrorListener; import com.baidu.cyberplayer.core.BVideoView.OnPreparedListener; import com.basv.gifmoviewview.widget.GifMovieView; import com.github.johnpersano.supertoasts.SuperToast; import com.loopj.android.http.JsonHttpResponseHandler; import com.squareup.picasso.Picasso; import com.squareup.picasso.Picasso.LoadedFrom; import com.squareup.picasso.Target; import com.umeng.analytics.MobclickAgent; import com.zhan_dui.auth.SocialPlatform; import com.zhan_dui.auth.User; import com.zhan_dui.data.ApiConnector; import com.zhan_dui.download.DownloadHelper; import com.zhan_dui.model.Animation; import com.zhan_dui.model.Comment; import com.zhan_dui.model.DownloadRecord; import com.zhan_dui.sns.ShareHelper; import com.zhan_dui.utils.NetworkUtils; import com.zhan_dui.utils.OrientationHelper; import com.zhan_dui.utils.Screen; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.ocpsoft.prettytime.PrettyTime; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import cn.sharesdk.sina.weibo.SinaWeibo; import cn.sharesdk.tencent.qzone.QZone; public class PlayActivity extends ActionBarActivity implements OnClickListener, Target, OnPreparedListener, OnCompletionListener, OnErrorListener, OnTouchListener { private TextView mTitleTextView; private TextView mContentTextView; private TextView mAuthorTextView; // private android.support.v7.widget.ShareActionProvider mShareActionProvider; private ImageView mDetailImageView; private ImageButton mPrePlayButton; private GifMovieView mLoadingGif; private int mCurrentScape; private Context mContext; private SharedPreferences mSharedPreferences; private View mVideoAction; private Animation mAnimation; private OrientationEventListener mOrientationEventListener; private MenuItem mFavMenuItem; private Bitmap mDetailPicture; private LinearLayout mComments, mRecomendView; private LayoutInflater mLayoutInflater; private RelativeLayout mHeaderWrapper; private View mLoadMoreComment; private View mRecommendView; private Button mLoadMoreButton; private Button mZoomButton; private boolean mCommentFinished; private User mUser; private final String mDir = "AnimeTaste"; private final String mShareName = "animetaste-share.jpg"; private int mCommentCount; private int mSkip = 0; private int mStep = 5; private int mLastPos = 0; private final int UI_EVENT_UPDATE_CURRPOSITION = 1; private PrettyTime mPrettyTime; private BVideoView mVV = null; private RelativeLayout mViewHolder = null; private RelativeLayout mController = null; private SeekBar mProgress = null; private TextView mDuration = null; private TextView mCurPosition = null; private Button mPlayBtn = null; private EditText mCommentEditText; private String AK = "TrqQtzMhuoKhyLmNsfvwfWDo"; private String SK = "UuhbIKiNfr8SA3NM"; private Typeface mRobotoBold, mRobotoThin; private DownloadHelper mDownloadHelper; private PLAY_STATE mPlayState; @Override public void onCreate(Bundle savedInstance) { super.onCreate(savedInstance); AVOSCloud.initialize(this, "w43xht9daji0uut74pseeiibax8c2tnzxowmx9f81nvtpims", "86q8251hrodk6wnf4znistay1mva9rm1xikvp1s9mhp5n7od"); mPrettyTime = new PrettyTime(); mContext = this; if (getIntent().getExtras().containsKey("Animation")) { mAnimation = getIntent().getParcelableExtra("Animation"); } mDownloadHelper = new DownloadHelper(this); if (savedInstance != null && savedInstance.containsKey("Animation")) { mAnimation = savedInstance.getParcelable("Animation"); mLastPos = savedInstance.getInt("LastPosition"); } mUser = new User(mContext); setContentView(R.layout.activity_play); mLayoutInflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mSharedPreferences = PreferenceManager .getDefaultSharedPreferences(mContext); mCurrentScape = OrientationHelper.PORTRAIT; mTitleTextView = (TextView) findViewById(R.id.title); mContentTextView = (TextView) findViewById(R.id.content); mDetailImageView = (ImageView) findViewById(R.id.detailPic); mVideoAction = findViewById(R.id.VideoAction); mAuthorTextView = (TextView) findViewById(R.id.author); mPrePlayButton = (ImageButton) findViewById(R.id.pre_play_button); mLoadingGif = (GifMovieView) findViewById(R.id.loading_gif); mComments = (LinearLayout) findViewById(R.id.comments); mRecommendView = findViewById(R.id.recommand_view); mPlayBtn = (Button) findViewById(R.id.play_btn); mProgress = (SeekBar) findViewById(R.id.media_progress); mDuration = (TextView) findViewById(R.id.time_total); mCurPosition = (TextView) findViewById(R.id.time_current); mController = (RelativeLayout) findViewById(R.id.controlbar); mViewHolder = (RelativeLayout) findViewById(R.id.view_holder); mVV = (BVideoView) findViewById(R.id.video_view); mCommentEditText = (EditText) findViewById(R.id.comment_edit_text); mHeaderWrapper = (RelativeLayout) findViewById(R.id.header_wrapper); mZoomButton = (Button) findViewById(R.id.zoom_btn); mRecomendView = (LinearLayout) findViewById(R.id.recommend_list); mRobotoBold = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Bold.ttf"); mRobotoThin = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Thin.ttf"); initPlayer(); initContent(); mAnimation.recordWatch(); ApiConnector.instance().getRandom(5, mRandomHandler); new CommentsTask().execute(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("LastPosition", mLastPos); outState.putParcelable("Animation", mAnimation); } @Override protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState.containsKey("Animation")) { mAnimation = savedInstanceState.getParcelable("Animation"); mLastPos = savedInstanceState.getInt("LastPosition"); } } private class RandomRecommendTask extends AsyncTask<Void, Void, Void> { private JSONArray mRandomJsonArray; private LinearLayout mRandomLayout; public RandomRecommendTask(JSONArray recommendJsonArray) { mRandomJsonArray = recommendJsonArray; mRandomLayout = new LinearLayout(mContext); mRandomLayout.setOrientation(LinearLayout.VERTICAL); } @Override protected Void doInBackground(Void... voids) { for (int i = 0; i < mRandomJsonArray.length(); i++) { LinearLayout recommend_item = (LinearLayout) mLayoutInflater .inflate(R.layout.recommend_item, null); ImageView recommendThumb = (ImageView) recommend_item .findViewById(R.id.thumb); TextView recommendTitle = (TextView) recommend_item .findViewById(R.id.recommand_title); TextView recommendContent = (TextView) recommend_item .findViewById(R.id.recommand_content); try { JSONObject animationObject = mRandomJsonArray.getJSONObject(i); Animation animation = Animation .build(animationObject); Picasso.with(mContext).load(animation.HomePic) .placeholder(R.drawable.placeholder_thumb) .error(R.drawable.placeholder_fail) .into(recommendThumb); recommendTitle.setText(animation.Name); recommendContent.setText(animation.Brief); recommend_item.setTag(animation); recommend_item.setOnClickListener(PlayActivity.this); View line = mRecommendView .findViewById(R.id.divide_line); if (i == mRandomJsonArray.length() - 1 && line != null) { recommend_item.removeView(line); } mRandomLayout.addView(recommend_item); } catch (Exception e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); mRecomendView.addView(mRandomLayout); } } private JsonHttpResponseHandler mRandomHandler = new JsonHttpResponseHandler() { public void onSuccess(int statusCode, org.json.JSONObject response) { if (statusCode == 200) { try { JSONArray animations = response.getJSONObject("data").getJSONObject("list").getJSONArray("anime"); new RandomRecommendTask(animations).execute(); } catch (JSONException e) { e.printStackTrace(); } } } ; }; private Intent getDefaultIntent() { Intent intent = new Intent(Intent.ACTION_SEND); String shareTitle = getString(R.string.share_video_title); shareTitle = String.format(shareTitle, mAnimation.Name); String shareContent = getString(R.string.share_video_body);
package net.simpvp.Jail; import org.bukkit.OfflinePlayer; import org.bukkit.Statistic; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerLoginEvent; import net.md_5.bungee.api.ChatColor; import java.net.InetAddress; public class AntiVPNCommand implements Listener,CommandExecutor{ public static int hours_required; public AntiVPNCommand(Jail plugin) { hours_required = plugin.getConfig().getInt("novpns"); plugin.getLogger().info("NoVpns set to " + hours_required); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled=true) public void onPlayerLogin(PlayerLoginEvent event) { Player player = event.getPlayer(); String reason = GeoIP.check_asn(event.getAddress()); if (!requiredConditions(player) && reason != null) { event.disallow(PlayerLoginEvent.Result.KICK_OTHER, ChatColor.RED + "Please turn off your VPN to connect"); String as = GeoIP.getAs(event.getAddress()); Jail.instance.getLogger().info("Blocking " + player.getDisplayName() + " from joining with a vpn"); Jail.instance.getLogger().info(player.getDisplayName() + " tried to join from AS " + as + " Reason: " + reason); } } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Jail.instance.reloadConfig(); Player player = null; if (sender instanceof Player) { player = (Player) sender; if (!player.isOp()) { sender.sendMessage(ChatColor.RED + "You must be an admin to use this command"); return true; } } if (args.length == 0) { sender.sendMessage(ChatColor.GREEN + "/novpn will prevent players using vpns with less than the set amount of hours from joining. It is currently set to " + hours_required); return true; } try { hours_required = Integer.parseInt(args[0]); } catch (Exception e) { sender.sendMessage("Invalid integer " + args[0]); return true; } Jail.instance.reloadConfig(); Jail.instance.getConfig().set("novpns", hours_required); Jail.instance.saveConfig(); String m = ChatColor.GREEN + "/novpns hours required set to " + hours_required; sender.sendMessage(m); Jail.instance.getLogger().info(m); return true; } /* Return true if player meets all required conditions */ private boolean requiredConditions(Player p) { /* OPs can join unconditionally */ if (p.isOp()) { return true; } /* Whitelisted players can join unconditionally */ if (p.isWhitelisted()) { return true; } OfflinePlayer offplayer = Jail.instance.getServer().getOfflinePlayer(p.getUniqueId()); int hours = -1; if (offplayer.hasPlayedBefore()) { int played_ticks = p.getStatistic(Statistic.PLAY_ONE_MINUTE); hours = played_ticks / (20 * 60 * 60); } if (hours < hours_required) { return false; } return true; } }
package de.alpharogroup.lang; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import de.alpharogroup.file.FileExtension; import de.alpharogroup.file.FilenameExtensions; import de.alpharogroup.file.filter.ClassFileFilter; import de.alpharogroup.string.StringExtensions; import lombok.experimental.ExtensionMethod; /** * The class {@link ClassExtensions} provides extension methods for the class {@link Class}. */ @ExtensionMethod(StringExtensions.class) public final class ClassExtensions { /** The Constant CGLIB_TAG contains the tag of a cglib class name. */ protected static final String CGLIB_TAG = "$$"; /** * Equal the given class objects by they qualified class names. * * @param oneClass * one class for equation by the qualified class name. * @param otherClass * the other class for equation by the qualified class name. * @return s true if the qualified class names are equal otherwise false. */ public static boolean equalsByClassName(final Class<?> oneClass, final Class<?> otherClass) { final String oneNormalizedClassName = ClassExtensions .normalizeQualifiedClassName(oneClass.getName()); final String otherNormalizedClassName = ClassExtensions .normalizeQualifiedClassName(otherClass.getName()); if (otherNormalizedClassName.equals(oneNormalizedClassName)) { return true; } return false; } /** * Look up the class in the "current" ClassLoader. * * @param className * The class name to load * @return the class * @throws ClassNotFoundException * is thrown if the Class was not found or could not be located. */ public static Class<?> forName(final String className) throws ClassNotFoundException { Class<?> clazz = null; try { clazz = Class.forName(className); } catch (final Throwable throwable) { clazz = Class.forName(className, true, getClassLoader()); if (clazz == null) { clazz = Class.forName(className, false, getClassLoader()); if (clazz == null) { throw throwable; } } } return clazz; } /** * Gets the parent base class from the given child class. * * @param childClass * the child class * @return the parent base class from the given child class. */ public static Class<?> getBaseClass(final Class<?> childClass) { if (childClass == null || childClass.equals(Object.class)) { return childClass; } Class<?> superClass = childClass.getSuperclass(); if (superClass != null && superClass.equals(Object.class)) { return childClass; } while (!(superClass.getSuperclass() != null && superClass.getSuperclass().equals(Object.class))) { superClass = superClass.getSuperclass(); } return superClass; } /** * Gets the {@link Class} of the given object. * * @param object * the object to resolve the class * @return the {@link Class} of the given object or null if the object is null. */ @SuppressWarnings("unchecked") public static <T> Class<T> getClass(final T object) { if (object != null) { return (Class<T>)object.getClass(); } return null; } /** * Gets the current class loader. * * @return 's the current class loader */ public static ClassLoader getClassLoader() { return ClassExtensions.getClassLoader(null); } /** * Gets the ClassLoader from the given object. * * @param obj * The object. * @return the ClassLoader from the given object. */ public static ClassLoader getClassLoader(final Object obj) { ClassLoader classLoader = null; if (null != obj) { if (isDerivate(Thread.currentThread().getContextClassLoader(), obj.getClass().getClassLoader())) { classLoader = obj.getClass().getClassLoader(); } else { classLoader = Thread.currentThread().getContextClassLoader(); } if (isDerivate(classLoader, ClassLoader.getSystemClassLoader())) { classLoader = ClassLoader.getSystemClassLoader(); } } else { if (isDerivate(Thread.currentThread().getContextClassLoader(), ClassLoader.getSystemClassLoader())) { classLoader = ClassLoader.getSystemClassLoader(); } else { classLoader = Thread.currentThread().getContextClassLoader(); } } return classLoader; } /** * Gets the classname from the given class. * * @param clazz * The class. * @return The classname. */ public static String getClassname(final Class<?> clazz) { final String className = clazz.getName(); return className; } /** * Gets the classname and concats the suffix ".class" from the class. * * @param clazz * The class. * @return The classname and concats the suffix ".class". */ public static String getClassnameWithSuffix(final Class<?> clazz) { String className = clazz.getName(); className = className.substring(className.lastIndexOf('.') + 1) + FileExtension.CLASS.getExtension(); return className; } /** * Gets the classname and concats the suffix ".class" from the object. * * @param obj * The object. * @return The classname and concats the suffix ".class". */ public static String getClassnameWithSuffix(final Object obj) { return getClassnameWithSuffix(obj.getClass()); } /** * Gets the {@link ClassType} from the given class. * * @param clazz * The class. * @return the {@link ClassType} from the given class. */ public static ClassType getClassType(final Class<?> clazz) { if (clazz.isArray()) { return ClassType.ARRAY; } if (isCollection(clazz)) { return ClassType.COLLECTION; } if (isMap(clazz)) { return ClassType.MAP; } if (clazz.isLocalClass()) { return ClassType.LOCAL; } if (clazz.isMemberClass()) { return ClassType.MEMBER; } if (clazz.isPrimitive()) { return ClassType.PRIMITIVE; } if (clazz.isAnnotation()) { return ClassType.ANNOTATION; } if (clazz.isEnum()) { return ClassType.ENUM; } if (clazz.isInterface()) { return ClassType.INTERFACE; } if (clazz.isSynthetic()) { return ClassType.SYNTHETIC; } if (clazz.isAnonymousClass()) { return ClassType.ANONYMOUS; } return ClassType.DEFAULT; } /** * Gets the directories from the given path. * * @param path * the path * @param isPackage * If the Flag is true than the given path is a package. * @return the directories from resources * @throws IOException * Signals that an I/O exception has occurred. */ public static List<File> getDirectoriesFromResources(String path, final boolean isPackage) throws IOException { if (isPackage) { path = path.replace('.', '/'); } final List<URL> resources = ClassExtensions.getResources(path); final List<File> dirs = new ArrayList<>(); for (final URL resource : resources) { dirs.add(new File(URLDecoder.decode(resource.getFile(), "UTF-8"))); } return dirs; } /** * If the given class is in a JAR file than the jar path as String will be returned. * * @param clazz * The class. * @return the jar path as String if the given class is in a JAR file. */ public static String getJarPath(final Class<?> clazz) { String jarPath = null; final String jarPathPrefix = "jar:"; final String jarPathFilePrefix = jarPathPrefix + "file:"; final String path = ClassExtensions.getPath(clazz); final URL classUrl = ClassExtensions.getResource(path); if (classUrl != null) { final String classUrlString = classUrl.toString(); if ((classUrlString.startsWith(jarPathPrefix) && (classUrlString.indexOf(path) > 0))) { jarPath = classUrlString.replace("!" + path, ""); if (jarPath.startsWith(jarPathFilePrefix)) { final int beginIndex = jarPathFilePrefix.length(); jarPath = jarPath.substring(beginIndex, jarPath.length()); } } } return jarPath; } /** * If the given class is in a JAR, WAR or EAR file than the manifest url as String is returned. * * @param clazz * The class. * @return the manifest url as String if the given class is in a JAR, WAR or EAR file. */ public static String getManifestUrl(final Class<?> clazz) { String manifestUrl = null; final String path = ClassExtensions.getPath(clazz); final URL classUrl = ClassExtensions.getResource(path); if (classUrl != null) { final String classUrlString = classUrl.toString(); if ((classUrlString.startsWith("jar:") && (classUrlString.indexOf(path) > 0)) || (classUrlString.startsWith("war:") && (classUrlString.indexOf(path) > 0)) || (classUrlString.startsWith("ear:") && (classUrlString.indexOf(path) > 0)) || (classUrlString.startsWith("file:") && (classUrlString.indexOf(path) > 0))) { manifestUrl = classUrlString.replace(path, "/META-INF/MANIFEST.MF"); } } return manifestUrl; } /** * Returns the name of the given class or null if the given class is null. * * @param clazz * The class. * * @return The name of the given class. */ public static String getName(final Class<?> clazz) { return getName(clazz, false); } /** * Returns the name of the given class or null if the given class is null. If the given flag * 'simple' is true the simple name (without the package) will be returned. * * @param clazz * The class * @param simple * The flag if the simple name should be returned. * * @return The name of the given class or if the given flag 'simple' is true the simple name * (without the package) will be returned. */ public static String getName(Class<?> clazz, final boolean simple) { String name = null; if (clazz != null) { while (clazz.isAnonymousClass()) { clazz = clazz.getSuperclass(); } if (simple) { name = clazz.getSimpleName(); } else { name = clazz.getName(); } } return name; } /** * Gets the path from the given class. For instance /java/lang/Object.class if the given class * is from {@code Object} * * @param clazz * The class. * @return the path from the given class. */ public static String getPath(final Class<?> clazz) { final String packagePath = PackageExtensions.getPackagePath(clazz); final String className = ClassExtensions.getSimpleName(clazz); final StringBuilder sb = new StringBuilder().append("/").append(packagePath) .append(className).append(FileExtension.CLASS.getExtension()); final String path = sb.toString(); return path; } /** * Finds the absolute path from the object. * * @param obj * The object. * @return The absolute path from the object. */ public static String getPathFromObject(final Object obj) { if (obj == null) { return null; } final String pathFromObject = obj.getClass() .getResource(ClassExtensions.getClassnameWithSuffix(obj)).getPath(); return pathFromObject; } /** * Gives the url from the path back. * * @param clazz * The class-object. * @return 's the url from the path. */ public static URL getResource(final Class<?> clazz) { final String path = ClassExtensions.getPath(clazz); URL url = clazz.getResource(path); if (url == null) { url = ClassExtensions.getClassLoader().getResource(path); } return url; } /** * Gives the url from the path back. * * @param clazz * The class-object. * @param path * The path. * @return 's the url from the path. */ public static URL getResource(final Class<?> clazz, final String path) { URL url = clazz.getResource(path); if (url == null) { url = ClassExtensions.getClassLoader().getResource(path); } return url; } /** * Gives the URL from the resource. Wrapes the Class.getResource(String)-method. * * @param name * The name from the resource. * @return The resource or null if the resource does not exists. */ public static URL getResource(final String name) { String path = name; if (name.startsWith("/")) { path = name.substring(1, name.length()); } final URL url = ClassExtensions.getClassLoader().getResource(path); return url; } /** * Gives the URL from the resource. Wrapes the Class.getResource(String)-method. * * @param <T> * the generic type * @param name * The name from the resource. * @param obj * The Object. * @return The resource or null if the resource does not exists. */ public static <T> URL getResource(final String name, final T obj) { final Class<?> clazz = obj.getClass(); URL url = clazz.getResource(name); if (url == null) { url = getResource(clazz, name); } return url; } /** * Gives the resource as a file Object. * * @param name * The name from the file. * @return The file or null if the file does not exists. * @throws URISyntaxException * occurs by creation of the file with an uri. */ public static File getResourceAsFile(final String name) throws URISyntaxException { File file = null; URL url = getResource(name); if (null == url) { url = ClassExtensions.getClassLoader().getResource(name); if (null != url) { file = new File(url.toURI()); } } else { file = new File(url.toURI()); } return file; } /** * Gives the resource as a file Object. * * @param name * The name from the file. * @param obj * The Object. * @return The file or null if the file does not exists. * @throws URISyntaxException * occurs by creation of the file with an uri. */ public static File getResourceAsFile(final String name, final Object obj) throws URISyntaxException { File file = null; URL url = getResource(name, obj); if (null == url) { url = ClassExtensions.getClassLoader(obj).getResource(name); if (null != url) { file = new File(url.toURI()); } } else { file = new File(url.toURI()); } return file; } /** * This method call the getResourceAsStream from the ClassLoader. You can use this method to * read files from jar-files. * * @param clazz * the clazz * @param uri * The uri as String. * @return The InputStream from the uri. */ public static InputStream getResourceAsStream(final Class<?> clazz, final String uri) { InputStream is = clazz.getResourceAsStream(uri); if (null == is) { is = ClassExtensions.getClassLoader().getResourceAsStream(uri); } return is; } /** * Gives the Inputstream from the resource. Wrapes the Class.getResourceAsStream(String)-method. * * @param name * The name from the resource. * @return The resource or null if the resource does not exists. */ public static InputStream getResourceAsStream(final String name) { final ClassLoader loader = ClassExtensions.getClassLoader(); final InputStream inputStream = loader.getResourceAsStream(name); return inputStream; } /** * Gives the Inputstream from the resource. Wrapes the Class.getResourceAsStream(String)-method. * * @param name * The name from the resource. * @param obj * The Object. * @return The resource or null if the resource does not exists. */ public static InputStream getResourceAsStream(final String name, final Object obj) { InputStream inputStream = obj.getClass().getResourceAsStream(name); if (null == inputStream) { final ClassLoader loader = ClassExtensions.getClassLoader(obj); inputStream = loader.getResourceAsStream(name); } return inputStream; } /** * Gets a list with urls from the given path for all resources. * * @param path * The base path. * @return The resources. * @throws IOException * Signals that an I/O exception has occurred. */ public static List<URL> getResources(final String path) throws IOException { final ClassLoader classLoader = ClassExtensions.getClassLoader(); final List<URL> list = Collections.list(classLoader.getResources(path)); return list; } /** * Returns the simple name of the given class or null if the given class is null. * * @param clazz * The class. * * @return The simple name of the given class. */ public static String getSimpleName(final Class<?> clazz) { return getName(clazz, true); } /** * Returns the URL from the given class. * * @param clazz * The class. * @return the URL from the given class. */ public static URL getURL(final Class<?> clazz) { return ClassExtensions.getResource(ClassExtensions.getPath(clazz)); } /** * Checks if the given {@link Class} is cglib proxy class. * * @param <T> the generic type * @param result the result * @return true, if the given {@link Class} is cglib proxy class otherwise false. */ public static <T> boolean isCglib(Class<T> result) { return result.getName().contains(CGLIB_TAG); } /** * Checks if the given class is assignable from {@link Collection}. * * @param clazz * The class. * @return true, if the given class is assignable from {@link Collection} otherwise false. */ public static boolean isCollection(final Class<?> clazz) { return Collection.class.isAssignableFrom(clazz); } /** * Compares the two given ClassLoader objects and returns true if compare is a derivate of * source. * * @param source * the source * @param compare * the compare * @return true, if compare is a derivate of source. */ public static boolean isDerivate(final ClassLoader source, ClassLoader compare) { if (source == compare) { return true; } if (compare == null) { return false; } if (source == null) { return true; } while (null != compare) { compare = compare.getParent(); if (source == compare) { return true; } } return false; } /** * Checks if the given class is assignable from {@link Map}. * * @param clazz * The class. * @return true, if the given class is assignable from {@link Map} otherwise false. */ public static boolean isMap(final Class<?> clazz) { return Map.class.isAssignableFrom(clazz); } /** * Normalizes the given full qualified class name. This can be an entry from a jar file for * instance. * * @param qualifiedClassname * the full qualified class name to normalize. * @return The normalized class name. */ public static String normalizeQualifiedClassName(final String qualifiedClassname) { return normalizeSimpleClassName(qualifiedClassname).replaceAll("/", "."); } /** * Normalizes the given simple class name. * * @param className * the class name to normalize. * @return The normalized class name. */ public static String normalizeSimpleClassName(final String className) { String result = className; if (className.endsWith(FileExtension.CLASS.getExtension())) { result = className.replaceLast(FileExtension.CLASS.getExtension(), ""); } final int lastIndexOf$ = result.lastIndexOf("$"); if (lastIndexOf$ != -1) { final String prefix = result.substring(0, lastIndexOf$); final String compilerClassName = result.substring(lastIndexOf$ + 1, result.length()); if (StringUtils.isNumeric(compilerClassName)) { return prefix; } } return result; } /** * Scan for classes in the given directory. * * @param directory * the directory * @param packagePath * the package path * @return the list * @throws ClassNotFoundException * the class not found exception */ public static Set<Class<?>> scanClassesFromPackage(final File directory, final String packagePath) throws ClassNotFoundException { return scanClassesFromPackage(directory, packagePath, false); } /** * Scan recursive for classes in the given directory. * * @param directory * the directory * @param packagePath * the package path * @param recursive * the recursive * @return the list * @throws ClassNotFoundException * is thrown if a class in the given path cannot be located. */ public static Set<Class<?>> scanClassesFromPackage(final File directory, final String packagePath, final boolean recursive) throws ClassNotFoundException { final Set<Class<?>> foundClasses = new LinkedHashSet<>(); if (!directory.exists()) { return foundClasses; } // define the include filefilter for class files... final FileFilter includeFileFilter = new ClassFileFilter(); final File[] files = directory.listFiles(includeFileFilter); for (final File file : files) { String qualifiedClassname = null; if (file.isDirectory() && recursive) { qualifiedClassname = packagePath + "." + file.getName(); foundClasses.addAll(scanClassesFromPackage(file, qualifiedClassname, recursive)); } else { if (!file.isDirectory()) { final String filename = FilenameExtensions.getFilenameWithoutExtension(file); qualifiedClassname = packagePath + '.' + filename; foundClasses.add(forName(qualifiedClassname)); } } } return foundClasses; } /** * Scan class names from the given package name. * * @param packageName * the package name * @return the Set with all class found in the given package name. * @throws IOException * Signals that an I/O exception has occurred. * @throws ClassNotFoundException * is thrown if a class in the given path cannot be located. */ public static Set<Class<?>> scanClassNames(final String packageName) throws IOException, ClassNotFoundException { return scanClassNames(packageName, false); } /** * Scan class names from the given package name. * * @param packageName * the package name * @param recursive * the recursive flag * @return the Set with all class found in the given package name. * @throws IOException * Signals that an I/O exception has occurred. * @throws ClassNotFoundException * is thrown if a class in the given path cannot be located. */ public static Set<Class<?>> scanClassNames(final String packageName, final boolean recursive) throws IOException, ClassNotFoundException { final Set<Class<?>> foundClasses = new LinkedHashSet<>(); final Set<String> qualifiedClassnames = PackageExtensions.scanClassNames(packageName, recursive, true); for (final String qualifiedClassname : qualifiedClassnames) { foundClasses.add(forName(qualifiedClassname)); } return foundClasses; } }
package net.simpvp.Portals; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.UUID; import org.bukkit.Location; import org.bukkit.Statistic; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.entity.Sittable; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; public class PortalUtils { /** * For teleporting the given player using a specific portal * @param player player who is trying to teleport * @param portal block to check for portal location at */ public static void teleport(Player player, Location portal) { /* Check if the player is trying to teleport again too fast */ if (Portals.justTeleportedEntities.contains(player.getUniqueId())) { return; } Location location = player.getLocation(); SQLite.PortalLookup lookup = SQLite.get_other_portal(portal); /* If this portal is not a Portals portal */ if (lookup == null) { Portals.instance.getLogger().info(player.getName() + " destination was null."); return; } /* Stop Yaw and Pitch from changing if portal location is not directly from player */ lookup.destination.setYaw(location.getYaw()); lookup.destination.setPitch(location.getPitch()); /* Make sure a valid portal is at destination */ if (!PortalCheck.is_valid_portal(lookup.destination.getBlock())) { Portals.instance.getLogger().info(player.getName() + " destination portal frame is missing."); return; } ArrayList<UUID> portal_user_list = SQLite.get_portal_users(lookup.a); // Check if this is a players first time using this portal if (!portal_user_list.contains(player.getUniqueId()) && player.getGameMode() == (GameMode.SURVIVAL)) { SQLite.add_portal_user(lookup.a, lookup.b, player.getUniqueId()); int played_ticks = player.getStatistic(Statistic.PLAY_ONE_MINUTE); int played_minutes = played_ticks / (20 * 60); double played_hours = played_minutes / 60.0; int x = player.getLocation().getBlockX(); int y = player.getLocation().getBlockY(); int z = player.getLocation().getBlockZ(); String world = player.getLocation().getWorld().getName(); Portals.instance.getLogger().info(String.format("%s just used a portal for the first time at '%d %d %d %s'", player.getName(), x, y, z, world)); TextComponent msg = new TextComponent(player.getName() + " just used a portal for the first time"); msg.setColor(ChatColor.RED); ClickEvent click = new ClickEvent(ClickEvent.Action.RUN_COMMAND, String.format("/tpc %d %d %d %s", x, y, z, world)); msg.setClickEvent(click); HoverEvent hover = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("Teleport to portal coordinates").create()); msg.setHoverEvent(hover); for (Player p : Portals.instance.getServer().getOnlinePlayers()) { if (!p.isOp()) { continue; } if (played_hours < SQLite.get_playtime_constraint(p.getUniqueId().toString())) { p.spigot().sendMessage(msg); } } } Portals.instance.getLogger().info(String.format("Teleporting %s to '%d %d %d %s'", player.getName(), lookup.destination.getBlockX(), lookup.destination.getBlockY(), lookup.destination.getBlockZ(), lookup.destination.getWorld().getName() )); Location fLoc = new Location(lookup.destination.getWorld(), lookup.destination.getBlockX(), lookup.destination.getBlockY() - 1, lookup.destination.getBlockZ()); player.sendBlockChange(fLoc, fLoc.getBlock().getBlockData()); fLoc = new Location(lookup.destination.getWorld(), lookup.destination.getBlockX(), lookup.destination.getBlockY(), lookup.destination.getBlockZ()); player.sendBlockChange(fLoc, fLoc.getBlock().getBlockData()); player.teleport(lookup.destination); teleportNearby(portal, lookup.destination, player); /* Fix players from being stuck sneaking after a teleport*/ unsneak(player); setTeleported(player); } /** * For teleporting the given player using their current location * @param player player who is trying to teleport */ public static void teleport(Player player) { Location location = player.getLocation(); teleport(player, location); } /** * For limiting portal attempts * Allows two way minecart travel and maybe fixes the instant death bug * @param entity entity to stop from teleporting again too soon */ public static void setTeleported(Entity entity) { final UUID uuid = entity.getUniqueId(); Portals.justTeleportedEntities.add(uuid); Portals.instance.getServer().getScheduler().runTaskLater(Portals.instance, new Runnable() { public void run() { Portals.justTeleportedEntities.remove(uuid); } }, 20L); } /** * For stopping a player from being locked sneaking after switching worlds with a Portal * @param player player to unsneak */ public static void unsneak(final Player player) { Portals.instance.getServer().getScheduler().runTaskLater(Portals.instance, new Runnable() { public void run() { player.setSneaking(false); } }, 1L); } /** * Teleports nearby non-player entities through a nearby portal * @param location Location from which someone is being teleported * @param destination Location of the portal to which things are to be teleported * @param player player who used the portal and may have to be teleported again to stop visual bug */ public static void teleportNearby(Location from, final Location destination, Player player) { /* First teleport all entities at the same time as the player * The delay in previous versions seems to cause the duplication bug */ Collection<Entity> nearby = from.getWorld().getNearbyEntities(from, 2, 2, 2); boolean somethingTeleported = false; for (Entity entity : nearby) { if (!TELEPORTABLE_ENTITIES.contains(entity.getType())) { continue; } if (entity instanceof Sittable) { if (((Sittable) entity).isSitting()) { continue; } } entity.teleport(destination); somethingTeleported = true; } /* A bug seems to make all the entities invisible for just the player who used the portal. * Teleporting the player to the original location and then back seems to fix this. */ if (somethingTeleported) { // Only bother reteleporting players if an entity came with them Portals.instance.getServer().getScheduler().runTaskLater(Portals.instance, new Runnable() { public void run() { player.teleport(from); } }, 1L); Portals.instance.getServer().getScheduler().runTaskLater(Portals.instance, new Runnable() { public void run() { player.teleport(destination); } }, 2L); } } private static final HashSet<EntityType> TELEPORTABLE_ENTITIES = new HashSet<EntityType>(Arrays.asList( // EntityType.AREA_EFFECT_CLOUD, // EntityType.ARMOR_STAND, //EntityType.ARROW, EntityType.BAT, EntityType.BLAZE, EntityType.BOAT, EntityType.CAT, EntityType.CAVE_SPIDER, EntityType.CHICKEN, EntityType.COW, EntityType.CREEPER, EntityType.DOLPHIN, EntityType.DONKEY, // EntityType.DRAGON_FIREBALL, EntityType.DROPPED_ITEM, EntityType.EGG, EntityType.ELDER_GUARDIAN, // EntityType.ENDER_CRYSTAL, // EntityType.ENDER_DRAGON, EntityType.ENDER_PEARL, // EntityType.ENDER_SIGNAL, EntityType.ENDERMAN, EntityType.ENDERMITE, EntityType.EVOKER, // EntityType.EVOKER_FANGS, EntityType.EXPERIENCE_ORB, // EntityType.FALLING_BLOCK, EntityType.FIREBALL, // EntityType.FIREWORK, // EntityType.FISHING_HOOK, EntityType.FOX, EntityType.GHAST, // EntityType.GIANT, EntityType.GUARDIAN, EntityType.HOGLIN, EntityType.HORSE, EntityType.HUSK, EntityType.ILLUSIONER, EntityType.IRON_GOLEM, // EntityType.ITEM_FRAME, // EntityType.LEASH_HITCH, // EntityType.LIGHTNING, EntityType.LLAMA, // EntityType.LLAMA_SPIT, EntityType.MAGMA_CUBE, EntityType.MINECART, EntityType.MINECART_CHEST, // EntityType.MINECART_COMMAND, EntityType.MINECART_FURNACE, EntityType.MINECART_HOPPER, // EntityType.MINECART_MOB_SPAWNER, EntityType.MINECART_TNT, EntityType.MULE, EntityType.MUSHROOM_COW, EntityType.OCELOT, // EntityType.PAINTING, EntityType.PANDA, EntityType.PARROT, // EntityType.PHANTOM, EntityType.PIG, EntityType.PIGLIN, EntityType.PIGLIN_BRUTE, EntityType.PILLAGER, // EntityType.PLAYER, EntityType.POLAR_BEAR, EntityType.PRIMED_TNT, EntityType.PUFFERFISH, EntityType.RABBIT, EntityType.RAVAGER, EntityType.SALMON, EntityType.SHEEP, EntityType.SHULKER, // EntityType.SHULKER_BULLET, EntityType.SILVERFISH, EntityType.SKELETON, EntityType.SKELETON_HORSE, EntityType.SLIME, // EntityType.SMALL_FIREBALL, // EntityType.SNOWBALL, EntityType.SNOWMAN, // EntityType.SPECTRAL_ARROW, EntityType.SPIDER, // EntityType.SPLASH_POTION, EntityType.SQUID, EntityType.STRAY, EntityType.STRIDER, // EntityType.THROWN_EXP_BOTTLE, EntityType.TRADER_LLAMA, // EntityType.TRIDENT, EntityType.TROPICAL_FISH, EntityType.TURTLE, // EntityType.UNKNOWN, EntityType.VEX, EntityType.VILLAGER, EntityType.VINDICATOR, EntityType.WANDERING_TRADER, EntityType.WITCH, // EntityType.WITHER, EntityType.WITHER_SKELETON, // EntityType.WITHER_SKULL, EntityType.WOLF, EntityType.ZOGLIN, EntityType.ZOMBIE, EntityType.ZOMBIE_HORSE, EntityType.ZOMBIE_VILLAGER, EntityType.ZOMBIFIED_PIGLIN )); }
package de.diesner.ehzlogger; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import org.openmuc.jsml.structures.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class InfluxDbForward implements SmlForwarder { private final String remoteUri; private final String measurement; private final Client client; private List<SmartMeterRegister> registerList = new ArrayList<SmartMeterRegister>() {{ add(new SmartMeterRegister(new byte[]{(byte) 0x01, 0x00, 0x01, 0x08, 0x00, (byte) 0xFF}, "Wirkenergie_Total_Bezug")); // 1.8.0 add(new SmartMeterRegister(new byte[]{(byte) 0x01, 0x00, 0x01, 0x08, 0x01, (byte) 0xFF}, "Wirkenergie_Tarif_1_Bezug")); // 1.8.1 add(new SmartMeterRegister(new byte[]{(byte) 0x01, 0x00, 0x01, 0x08, 0x02, (byte) 0xFF}, "Wirkenergie_Tarif_2_Bezug")); // 1.8.2 add(new SmartMeterRegister(new byte[]{(byte) 0x01, 0x00, 0x02, 0x08, 0x00, (byte) 0xFF}, "Wirkenergie_Total_Lieferung")); // 2.8.0 add(new SmartMeterRegister(new byte[]{(byte) 0x01, 0x00, 0x02, 0x08, 0x01, (byte) 0xFF}, "Wirkenergie_Tarif_1_Lieferung")); // 2.8.1 add(new SmartMeterRegister(new byte[]{(byte) 0x01, 0x00, 0x02, 0x08, 0x02, (byte) 0xFF}, "Wirkenergie_Tarif_2_Lieferung")); // 2.8.2 add(new SmartMeterRegister(new byte[]{(byte) 0x01, 0x00, 0x10, 0x07, 0x00, (byte) 0xFF}, "Aktuelle_Gesamtwirkleistung")); // 16.7.0 }}; public InfluxDbForward(String remoteUri, String measurement) { this.remoteUri = remoteUri; this.measurement = measurement; ClientConfig clientConfig = new DefaultClientConfig(); client = Client.create(clientConfig); } public void enableHttpDebug() { client.addFilter(new LoggingFilter(System.out)); } @Override public void messageReceived(List<SML_Message> messageList) { Map<String, String> values = extractValues(messageList); postData(values); } private Map<String, String> extractValues(List<SML_Message> messageList) { Map<String, String> values = new HashMap<>(); for (int i = 0; i < messageList.size(); i++) { SML_Message sml_message = messageList.get(i); int tag = sml_message.getMessageBody().getTag().getVal(); if (tag == SML_MessageBody.GetListResponse) { SML_GetListRes resp = (SML_GetListRes) sml_message.getMessageBody().getChoice(); SML_List smlList = resp.getValList(); SML_ListEntry[] list = smlList.getValListEntry(); for (SML_ListEntry entry : list) { int unit = entry.getUnit().getVal(); if (unit == SML_Unit.WATT || unit == SML_Unit.WATT_HOUR) { SML_Value value = entry.getValue(); Long numericalValue = SmlDecoder.decodeASN(value.getChoice()); if (numericalValue == null) { System.out.println("Got non-numerical value for an energy measurement. Skipping."); continue; } byte objNameBytes[] = entry.getObjName().getOctetString(); for (SmartMeterRegister register : registerList) { if (register.matches(objNameBytes)) { values.put(register.getLabel(), String.valueOf(numericalValue / 10.0)); break; } } } } } } return values; } private String toLineProtocol(String measurement, Map<String, String> values) { StringBuffer data = new StringBuffer(measurement); boolean isFirst = true; for (Map.Entry<String, String> entry : values.entrySet()) { if (!isFirst) { data.append(","); } else { data.append(" "); isFirst = false; } data.append(entry.getKey()).append("=").append(entry.getValue()); } data.append(" ").append(System.currentTimeMillis()); return data.toString(); } private void postData(Map<String, String> values) { if (values == null || values.isEmpty()) { return; } WebResource webResource = client.resource(remoteUri); String postData = toLineProtocol(measurement, values); ClientResponse response = webResource.post(ClientResponse.class, postData); if (response.getStatus() != 204) { System.out.println("Failed : HTTP error code : " + response.getStatus()); if (response.hasEntity()) { System.out.println(response.getEntity(String.class)); } } } }
package de.iani.cubequest.sql; import de.iani.cubequest.CubeQuest; import de.iani.cubequest.Reward; import de.iani.cubequest.questStates.QuestState; import de.iani.cubequest.questStates.QuestState.Status; import de.iani.cubequest.sql.util.SQLConnection; import de.iani.cubequest.util.Pair; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; public class PlayerDatabase { private SQLConnection connection; private String playersTableName; private String questStatesTableName; private String rewardsToDeliverTableName; private final String getPlayerDataString; private final String updatePlayerDataString; private final String countPlayersGivenToString; private final String getQuestStatesString; private final String getPlayerStateString; private final String updatePlayerStateString; private final String deletePlayerStateString; private final String getRewardsToDeliverString; private final String addRewardsToDeliverString; private final String deleteRewardsToDeliverString; protected PlayerDatabase(SQLConnection connection, String tablePrefix) { this.connection = connection; this.playersTableName = tablePrefix + "_players"; this.questStatesTableName = tablePrefix + "_playerStates"; this.rewardsToDeliverTableName = tablePrefix + "_rewardsToDeliver"; this.getPlayerDataString = "SELECT questPoints, xp FROM `" + this.playersTableName + "` WHERE id = ?"; this.updatePlayerDataString = "INSERT INTO `" + this.playersTableName + "` (id, questPoints, xp) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE questPoints = ?, xp = ?"; this.countPlayersGivenToString = "SELECT COUNT(player) FROM `" + this.questStatesTableName + "` WHERE status=1 AND quest=?"; // 1 ist GIVENTO this.getQuestStatesString = "SELECT quest, status, data FROM `" + this.questStatesTableName + "` WHERE status=1 AND player=?"; // 1 ist GIVENTO this.deletePlayerStateString = "DELETE FROM `" + this.questStatesTableName + "` WHERE quest=? AND player=?"; this.getPlayerStateString = "SELECT status, data FROM `" + this.questStatesTableName + "` WHERE quest=? AND player=?"; this.updatePlayerStateString = "INSERT INTO `" + this.questStatesTableName + "` (quest, player, status, data) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE status = ?, data = ?"; this.getRewardsToDeliverString = "SELECT reward FROM `" + this.rewardsToDeliverTableName + "` WHERE player=?"; this.addRewardsToDeliverString = "INSERT INTO `" + this.rewardsToDeliverTableName + "` (player, reward) VALUES (?, ?)"; this.deleteRewardsToDeliverString = "DELETE FROM `" + this.rewardsToDeliverTableName + "` WHERE player=?"; } protected void createTables() throws SQLException { this.connection.runCommands((connection, sqlConnection) -> { if (!sqlConnection.hasTable(this.playersTableName)) { Statement smt = connection.createStatement(); smt.executeUpdate("CREATE TABLE `" + this.playersTableName + "` (" + "`id` CHAR(36), " + "`questPoints` INT NOT NULL DEFAULT 0, " + "`xp` INT NOT NULL DEFAULT 0, " + "PRIMARY KEY (`id`)) " + "ENGINE = innodb"); smt.close(); } if (!sqlConnection.hasTable(this.questStatesTableName)) { Statement smt = connection.createStatement(); smt.executeUpdate("CREATE TABLE `" + this.questStatesTableName + "` (" + "`quest` INT, " + "`player` CHAR(36), " + "`status` INT NOT NULL, " + "`data` MEDIUMTEXT, " + "PRIMARY KEY (`quest`, `player`), " + "FOREIGN KEY (`quest`) REFERENCES `" + CubeQuest.getInstance().getDatabaseFassade().getQuestDB().getTableName() + "` (`id`) ON UPDATE CASCADE ON DELETE CASCADE) ENGINE = innodb"); smt.close(); } if (!sqlConnection.hasTable(this.rewardsToDeliverTableName)) { Statement smt = connection.createStatement(); smt.executeUpdate("CREATE TABLE `" + this.rewardsToDeliverTableName + "` (" + "`id` INT AUTO_INCREMENT, " + "`player` CHAR(36), " + "`reward` MEDIUMTEXT, " + "PRIMARY KEY (`id`) ) " + "ENGINE = innodb"); smt.close(); } return null; }); } protected Pair<Integer, Integer> getPlayerData(UUID id) throws SQLException { return this.connection.runCommands((connection, sqlConnection) -> { PreparedStatement smt = sqlConnection.getOrCreateStatement(this.getPlayerDataString); smt.setString(1, id.toString()); ResultSet rs = smt.executeQuery(); if (!rs.next()) { rs.close(); return null; } rs.first(); Pair<Integer, Integer> result = new Pair<>(rs.getInt(1), rs.getInt(2)); rs.close(); return result; }); } protected void setPlayerData(UUID id, int questPoints, int xp) throws SQLException { this.connection.runCommands((connection, sqlConnection) -> { PreparedStatement smt = sqlConnection.getOrCreateStatement(this.updatePlayerDataString); smt.setString(1, id.toString()); smt.setInt(2, questPoints); smt.setInt(3, xp); smt.setInt(4, questPoints); smt.setInt(5, xp); smt.executeUpdate(); return null; }); } protected int countPlayersGivenTo(int questId) throws SQLException { return this.connection.runCommands((connection, sqlConnection) -> { PreparedStatement smt = sqlConnection.getOrCreateStatement(this.countPlayersGivenToString); smt.setInt(1, questId); ResultSet rs = smt.executeQuery(); if (!rs.next()) { rs.close(); return 0; } rs.first(); int result = rs.getInt(1); rs.close(); return result; }); } protected Map<Integer, QuestState> getQuestStates(UUID playerId) throws SQLException { return this.connection.runCommands((connection, sqlConnection) -> { PreparedStatement smt = sqlConnection.getOrCreateStatement(this.getQuestStatesString); smt.setString(1, playerId.toString()); ResultSet rs = smt.executeQuery(); HashMap<Integer, QuestState> result = new HashMap<>(); while (rs.next()) { Status status = Status.values()[rs.getInt(2)]; String serialized = rs.getString(3); result.put(rs.getInt(1), CubeQuest.getInstance().getQuestStateCreator() .create(playerId, rs.getInt(1), status, serialized)); } rs.close(); return result; }); } /* * protected Map<UUID, String> getSerializedPlayerStates(int questId) throws SQLException { * * return this.connection.runCommands((connection, sqlConnection) -> { PreparedStatement smt = * sqlConnection.getOrCreateStatement(getPlayerStatesString); smt.setInt(1, questId); ResultSet * rs = smt.executeQuery(); HashMap<UUID, QuestState> result = new HashMap<UUID, QuestState>(); * while (rs.next()) { //result.put(UUID.fromString(rs.getString(1)), * Status.values()[rs.getInt(2)]); result.put(UUID.fromString(rs.getString(1)), rs.getString(2)) * } rs.close(); return result; }); * * } */ /* * protected Status getPlayerStatus(int questId, UUID playerId) throws SQLException { * * return this.connection.runCommands((connection, sqlConnection) -> { PreparedStatement smt = * sqlConnection.getOrCreateStatement(getPlayerStatusString); smt.setInt(1, questId); * smt.setString(2, playerId.toString()); ResultSet rs = smt.executeQuery(); if (!rs.next()) { * rs.close(); return null; } Status result = Status.values()[rs.getInt(1)]; rs.close(); return * result; }); * * } */ protected QuestState getPlayerState(int questId, UUID playerId) throws SQLException { return this.connection.runCommands((connection, sqlConnection) -> { PreparedStatement smt = sqlConnection.getOrCreateStatement(this.getPlayerStateString); smt.setInt(1, questId); smt.setString(2, playerId.toString()); ResultSet rs = smt.executeQuery(); if (!rs.next()) { rs.close(); return null; } Status status = Status.values()[rs.getInt(1)]; String serialized = rs.getString(2); rs.close(); return CubeQuest.getInstance().getQuestStateCreator().create(playerId, questId, status, serialized); }); } protected void setPlayerState(int questId, UUID playerId, QuestState state) throws SQLException { if (state == null) { this.connection.runCommands((connection, sqlConnection) -> { PreparedStatement smt = sqlConnection.getOrCreateStatement(this.deletePlayerStateString); smt.setInt(1, questId); smt.setString(2, playerId.toString()); smt.executeUpdate(); return true; }); } else { this.connection.runCommands((connection, sqlConnection) -> { PreparedStatement smt = sqlConnection.getOrCreateStatement(this.updatePlayerStateString); String stateString = state.serialize(); smt.setInt(1, questId); smt.setString(2, playerId.toString()); smt.setInt(3, state.getStatus().ordinal()); smt.setString(4, stateString); smt.setInt(5, state.getStatus().ordinal()); smt.setString(6, stateString); smt.executeUpdate(); return true; }); } } protected List<String> getSerializedRewardsToDeliver(UUID playerId) throws SQLException { return this.connection.runCommands((connection, sqlConnection) -> { PreparedStatement smt = sqlConnection.getOrCreateStatement(this.getRewardsToDeliverString); smt.setString(1, playerId.toString()); ResultSet rs = smt.executeQuery(); LinkedList<String> result = new LinkedList<>(); while (rs.next()) { String serialized = rs.getString(1); result.add(serialized); } rs.close(); return result; }); } protected List<Reward> getAndDeleteRewardsToDeliver(UUID playerId) throws SQLException, InvalidConfigurationException { LinkedList<Reward> result = new LinkedList<>(); List<String> serializedList = getSerializedRewardsToDeliver(playerId); YamlConfiguration yc = new YamlConfiguration(); for (String s: serializedList) { yc.loadFromString(s); result.add((Reward) yc.get("reward")); } this.connection.runCommands((connection, sqlConnection) -> { PreparedStatement smt = sqlConnection.getOrCreateStatement(this.deleteRewardsToDeliverString); smt.setString(1, playerId.toString()); smt.executeUpdate(); return null; }); return result; } protected void addRewardToDeliver(Reward reward, UUID playerId) throws SQLException { this.connection.runCommands((connection, sqlConnection) -> { PreparedStatement smt = sqlConnection.getOrCreateStatement(this.addRewardsToDeliverString); YamlConfiguration yc = new YamlConfiguration(); yc.getDefaultSection().set("reward", reward); smt.setString(1, playerId.toString()); smt.setString(2, yc.saveToString()); smt.executeUpdate(); return null; }); } }
package org.basex.server; import static org.basex.core.Text.*; import static org.basex.util.Token.*; import java.io.IOException; import java.net.Socket; import org.basex.BaseXServer; import org.basex.core.CommandParser; import org.basex.core.Context; import org.basex.core.Main; import org.basex.core.Proc; import org.basex.core.Prop; import org.basex.core.proc.Close; import org.basex.core.proc.Exit; import org.basex.data.Data; import org.basex.data.XMLSerializer; import org.basex.io.BufferInput; import org.basex.io.BufferedOutput; import org.basex.io.PrintOutput; import org.basex.query.QueryException; import org.basex.query.QueryProcessor; import org.basex.query.item.Item; import org.basex.query.iter.Iter; import org.basex.util.Performance; public final class ServerProcess extends Thread { /** Database context. */ public final Context context; /** Socket reference. */ private final Socket socket; /** Input stream. */ private BufferInput in; /** Output stream. */ private PrintOutput out; /** Current process. */ private Proc proc; /** Timeout thread. */ private Thread timeout; /** Log. */ private final Log log; /** * Constructor. * @param s socket * @param b server reference */ public ServerProcess(final Socket s, final BaseXServer b) { context = new Context(b.context); log = b.log; socket = s; } /** * Initializes the session via cram-md5 authentication. * @return success flag */ public boolean init() { try { final String ts = Long.toString(System.nanoTime()); // send timestamp (cram-md5) out = new PrintOutput(new BufferedOutput(socket.getOutputStream())); out.print(ts); send(true); // evaluate login data in = new BufferInput(socket.getInputStream()); final String us = in.readString(); final String pw = in.readString(); context.user = context.users.get(us); final boolean ok = context.user != null && md5(string(context.user.pw) + ts).equals(pw); send(ok); if(ok) start(); else if(!us.isEmpty()) log.write(this, "LOGIN " + us, "failed"); return ok; } catch(final IOException ex) { ex.printStackTrace(); log.write(ex.getMessage()); return false; } } @Override public void run() { log.write(this, "LOGIN " + context.user.name, "OK"); String input = null; try { while(true) { try { byte b = in.readByte(); if(b == 0) { iterate(); return; } input = in.readString(b); } catch(final IOException ex) { // this exception is thrown for each session if the server is stopped exit(); break; } // parse input and create process instance final Performance perf = new Performance(); proc = null; try { final Proc[] procs = new CommandParser(input, context, true).parse(); if(procs.length != 1) throw new QueryException(SERVERPROC, procs.length); proc = procs[0]; } catch(final QueryException ex) { // invalid command was sent by a client; create error feedback log.write(this, input, perf, INFOERROR + ex.extended()); out.write(0); out.print(ex.extended()); out.write(0); send(false); continue; } // stop console if(proc instanceof Exit) { exit(); break; } // process command and send results startTimer(proc); final boolean ok = proc.exec(context, out); out.write(0); final String inf = proc.info(); out.print(inf.equals(PROGERR) ? SERVERTIME : inf); out.write(0); send(ok); stopTimer(); final String pr = proc.toString().replaceAll("\\r|\\n", " "); log.write(this, pr, ok ? "OK" : INFOERROR + inf, perf); } log.write(this, "LOGOUT " + context.user.name, "OK"); } catch(final IOException ex) { log.write(this, input, INFOERROR + ex.getMessage()); ex.printStackTrace(); exit(); } } /** * Query is executed in iterate mode. * @throws IOException Exception */ private void iterate() throws IOException { String input = in.readString(); QueryProcessor processor = new QueryProcessor(input, context); try { Iter iter = processor.iter(); XMLSerializer serializer = new XMLSerializer(out); send(true); Item item; while(in.read() == 0) { if((item = iter.next()) != null) { send(true); item.serialize(serializer); send(true); } else { send(false); } } serializer.close(); processor.close(); } catch(QueryException ex) { // invalid command was sent by a client; create error feedback log.write(this, input, INFOERROR + ex.extended()); send(false); out.print(ex.extended()); send(true); } } /** * Sends the success flag to the client. * @param ok success flag * @throws IOException I/O exception */ private void send(final boolean ok) throws IOException { out.write(ok ? 0 : 1); out.flush(); } /** * Starts a timeout thread for the specified process. * @param p process reference */ private void startTimer(final Proc p) { final long to = context.prop.num(Prop.TIMEOUT); if(to == 0) return; timeout = new Thread() { @Override public void run() { Performance.sleep(to * 1000); p.stop(); } }; timeout.start(); } /** * Stops the current timeout thread. */ private void stopTimer() { if(timeout != null) timeout.interrupt(); } /** * Exits the session. */ public void exit() { new Close().exec(context); if(proc != null) proc.stop(); stopTimer(); context.delete(this); try { socket.close(); } catch(final IOException ex) { log.write(ex.getMessage()); ex.printStackTrace(); } } /** * Returns session information. * @return database information */ String info() { final Data data = context.data; return this + (data != null ? ": " + data.meta.name : ""); } @Override public String toString() { final String host = socket.getInetAddress().getHostAddress(); final int port = socket.getPort(); return Main.info("[%:%]", host, port); } }
package de.quaddy_services.proxy; import java.awt.AWTException; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Frame; import java.awt.Image; import java.awt.SystemTray; import java.awt.TrayIcon; import java.awt.TrayIcon.MessageType; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import javax.imageio.ImageIO; import javax.swing.AbstractAction; import javax.swing.Timer; import javax.swing.WindowConstants; import de.quaddy_services.proxy.events.PortStatusListener; import de.quaddy_services.proxy.logging.Logger; import de.quaddy_services.proxy.logging.LoggerFactory; public class EscapeProxy { private static Logger LOGGER; private boolean applicationIsExiting = false; private EscapeProxyFrame escapeProxyFrame; private Properties properties; public static void main(String[] args) { initializeLogger(); EventQueue.invokeLater(() -> { try { EscapeProxy tempEscapeProxy = new EscapeProxy(); tempEscapeProxy.mainInEventQueue(); } catch (IOException e) { LOGGER.error("Error initializing", e); System.exit(5); } }); } /** * @throws IOException * */ private void mainInEventQueue() throws IOException { LOGGER.info("Start"); properties = readConfig(); final EscapeProxyConfig tempEscapeProxyConfig = new EscapeProxyConfig(properties); escapeProxyFrame = new EscapeProxyFrame(tempEscapeProxyConfig, getFrameTitle()); escapeProxyFrame.setSize(new Dimension(500, 400)); escapeProxyFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); escapeProxyFrame.setShutdownAndExitAction(new AbstractAction("Shutdown and Exit") { private static final long serialVersionUID = 8818325653972860075L; @Override public void actionPerformed(@SuppressWarnings("unused") ActionEvent event) { shutdownAndExit(); } }); escapeProxyFrame.setClearProxyDecisionAction(new AbstractAction("Clear Proxy Decision") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(@SuppressWarnings("unused") ActionEvent event) { clearProxyDecision(); } }); Thread.setDefaultUncaughtExceptionHandler(new LoggingUncaughtExceptionHandler()); // See java.awt.EventDispatchThread.handlerPropName System.setProperty("sun.awt.exception.handler", LoggingUncaughtExceptionHandler.class.getName()); trayImage = new Image[] { getImage("offline.png"), getImage("online.png") }; initWindowListener(); initSystemTray(tempEscapeProxyConfig); setVisible(tempEscapeProxyConfig); addStatusListener(tempEscapeProxyConfig); new EscapeProxyWorkerAccept(tempEscapeProxyConfig).start(); } protected void clearProxyDecision() { EscapeProxyWorkerSocket.clearProxyDecisionCache(); } private String getFrameTitle() { final Properties tempProperties = new Properties(); final InputStream tempIn = EscapeProxy.class.getResourceAsStream("/META-INF/maven/de.quaddy_services/escape-from-intranet/pom.properties"); if (tempIn != null) { try { tempProperties.load(tempIn); tempIn.close(); } catch (final IOException e) { LOGGER.error("Ignore readingerror pom.properties", e); } } final String tempVersion = tempProperties.getProperty("version", "?"); return "Escape from intranet proxy " + tempVersion; } private void addStatusListener(EscapeProxyConfig aEscapeProxyConfig) { aEscapeProxyConfig.addStatusListener(new PortStatusListener() { @Override public void statusChanged(boolean aOkFlag, @SuppressWarnings("unused") String aText) { EventQueue.invokeLater(new Runnable() { @Override public void run() { escapeProxyFrame.setIconImage(trayImage[aOkFlag ? 1 : 0]); } }); } }); } /** * Before loading logback.xml, set the properties */ private static void initializeLogger() { final String tempDefaultLevel = System.getProperty("defaultLogLevel"); if (tempDefaultLevel == null) { System.setProperty("defaultLogLevel", "info"); } LOGGER = LoggerFactory.getLogger(EscapeProxy.class); } /** * @return */ private synchronized Properties readConfig() { final Properties tempProperties = new Properties(); final File tempFile = getFile(); if (tempFile.exists()) { try { final FileInputStream tempIn = new FileInputStream(tempFile); tempProperties.loadFromXML(tempIn); tempIn.close(); LOGGER.info("Loaded config " + tempFile.getAbsolutePath()); LOGGER.debug("Content={}", tempProperties); previouslySavedProperties = new Properties(); previouslySavedProperties.putAll(tempProperties); } catch (final IOException e) { LOGGER.error("error", e); } } return tempProperties; } private File getFile() { final File tempFile = new File(System.getProperty("user.home") + "/" + "escape-from-intranet.xml"); return tempFile; } private Image[] trayImage; private Properties previouslySavedProperties; /** * @param aEscapeProxyConfig */ private void initSystemTray(EscapeProxyConfig aEscapeProxyConfig) { if (SystemTray.isSupported()) { EventQueue.invokeLater(new Runnable() { /** * Init gui in eventqueue */ @Override public void run() { try { final SystemTray tempSystemTray = SystemTray.getSystemTray(); final TrayIcon tempTrayIcon = new TrayIcon(trayImage[0]); tempTrayIcon.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(@SuppressWarnings("unused") MouseEvent aE) { escapeProxyFrame.setVisible(true); escapeProxyFrame.toFront(); escapeProxyFrame.setState(Frame.NORMAL); } }); tempSystemTray.add(tempTrayIcon); } catch (final AWTException e) { LOGGER.error("Error", e); } } }); aEscapeProxyConfig.addStatusListener(new PortStatusListener() { private Boolean currentStatus = null; @Override public void statusChanged(boolean aOkFlag, String aText) { if (SystemTray.isSupported()) { EventQueue.invokeLater(new Runnable() { @Override public void run() { final TrayIcon tempTrayIcon = SystemTray.getSystemTray().getTrayIcons()[0]; tempTrayIcon.setImageAutoSize(true); tempTrayIcon.setImage(trayImage[aOkFlag ? 1 : 0]); tempTrayIcon.setToolTip(aText); } }); if (currentStatus == null || currentStatus ^ aOkFlag) { // show first status or changes EventQueue.invokeLater(new Runnable() { @Override public void run() { final TrayIcon tempTrayIcon = SystemTray.getSystemTray().getTrayIcons()[0]; tempTrayIcon.displayMessage("Status change", aText, MessageType.INFO); } }); } currentStatus = aOkFlag; } EventQueue.invokeLater(new Runnable() { @Override public void run() { escapeProxyFrame.setIconImage(trayImage[aOkFlag ? 1 : 0]); } }); } }); } } /** * @throws IOException */ private Image getImage(String aString) throws IOException { final InputStream tempIn = EscapeProxy.class.getClassLoader().getResourceAsStream(aString); final BufferedImage tempImage = ImageIO.read(tempIn); return tempImage; } /** * @param aEscapeProxyConfig */ private void setVisible(EscapeProxyConfig aEscapeProxyConfig) { EventQueue.invokeLater(new Runnable() { @Override public void run() { escapeProxyFrame.setIconImage(trayImage[0]); escapeProxyFrame.setVisible(true); final String tempProxyUser = aEscapeProxyConfig.getProxyUser(); if (tempProxyUser != null && tempProxyUser.length() > 0) { escapeProxyFrame.setState(Frame.ICONIFIED); } } }); } private ActionListener shutdownAndExitActionListener = new ActionListener() { @Override public void actionPerformed(@SuppressWarnings("unused") ActionEvent aE2) { LOGGER.info("Exit"); setApplicationIsExiting(true); System.exit(0); } }; private void shutdownAndExit() { escapeProxyFrame.setVisible(false); saveConfig(); LOGGER.info("Window Closing"); final Timer tempTimer = new Timer(5000, shutdownAndExitActionListener); tempTimer.start(); if (SystemTray.isSupported()) { final TrayIcon tempTrayIcon = SystemTray.getSystemTray().getTrayIcons()[0]; tempTrayIcon.displayMessage("Shutdown", "localhost proxy\nis shutting down...", MessageType.WARNING); } } /** * @param aProperties */ private void initWindowListener() { escapeProxyFrame.addWindowListener(new WindowAdapter() { /** * shutdown and exit if no other action is set */ @Override public void windowClosing(@SuppressWarnings("unused") WindowEvent aE) { if (escapeProxyFrame.getShutdownAndExitAction() == null) { shutdownAndExit(); } else { windowIconified(aE); if (SystemTray.isSupported()) { final TrayIcon tempTrayIcon = SystemTray.getSystemTray().getTrayIcons()[0]; tempTrayIcon.displayMessage("Still running", "The proxy\nist still running...", MessageType.INFO); } } } /** * called when windows looses focus. */ @Override public void windowDeactivated(WindowEvent aE) { saveConfig(); super.windowDeactivated(aE); } @Override public void windowIconified(WindowEvent aE) { super.windowIconified(aE); if (SystemTray.isSupported()) { escapeProxyFrame.setVisible(false); } } }); } private synchronized void saveConfig() { if (isApplicationIsExiting()) { LOGGER.info("Not saving as already Sytem.exit() is in progress"); return; } if (previouslySavedProperties == null || !previouslySavedProperties.equals(properties)) { saveConfigFile(); } else { LOGGER.debug("Skip saving same properties"); } previouslySavedProperties = new Properties(); previouslySavedProperties.putAll(properties); } private void saveConfigFile() { try { final File tempFile = getFile(); LOGGER.info("Save config " + tempFile.getAbsolutePath() + " ..."); final OutputStream tempOut = new FileOutputStream(tempFile); properties.storeToXML(tempOut, ""); tempOut.close(); LOGGER.info("Saved config " + tempFile.getAbsolutePath()); } catch (final IOException e) { LOGGER.error("error", e); } } /** * @see #applicationIsExiting */ public synchronized boolean isApplicationIsExiting() { return applicationIsExiting; } /** * @see #applicationIsExiting */ public synchronized void setApplicationIsExiting(boolean aApplicationIsExiting) { applicationIsExiting = aApplicationIsExiting; } }
package org.codelibs.riverweb; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicLong; import java.util.function.IntConsumer; import java.util.stream.Stream; import javax.annotation.Resource; import org.apache.http.auth.AuthScheme; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.NTCredentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.auth.DigestScheme; import org.apache.http.impl.auth.NTLMScheme; import org.codelibs.core.lang.StringUtil; import org.codelibs.fess.crawler.Crawler; import org.codelibs.fess.crawler.CrawlerContext; import org.codelibs.fess.crawler.client.http.Authentication; import org.codelibs.fess.crawler.client.http.HcHttpClient; import org.codelibs.fess.crawler.client.http.RequestHeader; import org.codelibs.fess.crawler.client.http.impl.AuthenticationImpl; import org.codelibs.fess.crawler.client.http.ntlm.JcifsEngine; import org.codelibs.riverweb.app.service.ScriptService; import org.codelibs.riverweb.entity.RiverConfig; import org.codelibs.riverweb.interval.WebRiverIntervalController; import org.codelibs.riverweb.util.ConfigProperties; import org.codelibs.riverweb.util.SettingsUtils; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.index.IndexNotFoundException; import org.elasticsearch.index.engine.DocumentAlreadyExistsException; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.script.ScriptService.ScriptType; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.kohsuke.args4j.ParserProperties; import org.lastaflute.di.core.SingletonLaContainer; import org.lastaflute.di.core.factory.SingletonLaContainerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RiverWeb { private static final Logger logger = LoggerFactory.getLogger(RiverWeb.class); private static final String NTLM_SCHEME = "NTLM"; private static final String DIGEST_SCHEME = "DIGEST"; private static final String BASIC_SCHEME = "BASIC"; @Option(name = "--queue-timeout") protected long queueTimeout = 300000; // 5min @Option(name = "--threads") protected int numThreads = 1; @Option(name = "--interval") protected long interval = 1000; @Option(name = "--config-id") protected String configId; @Option(name = "--session-id") protected String sessionId; @Option(name = "--cleanup") protected boolean cleanup; @Option(name = "--es-hosts") protected String esHosts; @Option(name = "--cluster-name") protected String clusterName; @Option(name = "--quiet") protected boolean quiet; @Resource protected org.codelibs.fess.crawler.client.EsClient esClient; @Resource protected ConfigProperties config; @Resource protected ScriptService scriptService; @Resource protected Crawler crawler; @Resource protected RiverConfig riverConfig; @Resource protected String defaultUserAgent; protected static IntConsumer exitMethod = System::exit; public static void main(final String[] args) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { SingletonLaContainerFactory.destroy(); } }); SingletonLaContainerFactory.init(); final RiverWeb riverWeb = SingletonLaContainer.getComponent(RiverWeb.class); final CmdLineParser parser = new CmdLineParser(riverWeb, ParserProperties.defaults().withUsageWidth(80)); try { parser.parseArgument(args); } catch (final Exception e) { parser.printUsage(System.out); exitMethod.accept(1); return; } try { exitMethod.accept(riverWeb.execute()); } catch (final Exception e) { riverWeb.print(e.getMessage()); exitMethod.accept(1); logger.error("Failed to process your request.", e); } finally { SingletonLaContainerFactory.destroy(); } } private void print(final String format, final Object... args) { final String log = String.format(format, args); if (quiet) { logger.info(log); } else { System.out.println(log); } } private int execute() { // update esClient esClient.setClusterName(config.getElasticsearchClusterName(clusterName)); esClient.setAddresses(config.getElasticsearchHosts(esHosts)); esClient.connect(); if (StringUtil.isNotBlank(configId)) { return crawl(configId, sessionId); } else { final String configIndex = config.getConfigIndex(); final String queueType = config.getQueueType(); final ExecutorService threadPool = Executors.newFixedThreadPool(numThreads); final Future<?>[] results = new Future[numThreads]; for (int i = 0; i < numThreads; i++) { final int threadId = i + 1; results[i] = threadPool.submit(() -> { AtomicLong lastProcessed = new AtomicLong(System.currentTimeMillis()); while (SingletonLaContainerFactory.hasContainer() && (queueTimeout <= 0 || lastProcessed.get() + queueTimeout > System.currentTimeMillis())) { logger.debug("Checking queue: {}/{}", configIndex, queueType); try { esClient.prepareSearch(configIndex).setTypes(queueType).setQuery(QueryBuilders.matchAllQuery()).setSize(1) .execute().actionGet().getHits().forEach(hit -> { if (esClient.prepareDelete(hit.getIndex(), hit.getType(), hit.getId()).execute().actionGet().isFound()) { Map<String, Object> source = hit.getSource(); final Object configId = source.get("config_id"); final String sessionId = (String) source.get("session_id"); if (configId instanceof String) { print("Config %s is started with Session %s.", configId, sessionId); try { crawler = SingletonLaContainer.getComponent(Crawler.class); crawl(configId.toString(), sessionId); } finally { print("Config %s is finished.", configId); lastProcessed.set(System.currentTimeMillis()); } } } else if (logger.isDebugEnabled()) { logger.debug("No data in queue."); } }); } catch (IndexNotFoundException e) { logger.debug("Index is not found.", e); } catch (Exception e) { logger.warn("Failed to process a queue.", e); } try { Thread.sleep(interval); } catch (InterruptedException e) { // ignore } } print("Thread %d is finished.", threadId); }); } Stream.of(results).forEach(f -> { try { f.get(); } catch (Exception e) { // ignore } }); threadPool.shutdown(); return 0; } } private int crawl(String configId, String sessionId) { // Load config data final String configIndex = config.getConfigIndex(); final String configType = config.getConfigType(); final GetResponse response = esClient.prepareGet(configIndex, configType, configId).execute().actionGet(); if (!response.isExists()) { print("Config ID %s is not found in %s/%s.", configId, configIndex, configType); return 1; } final Map<String, Object> crawlSettings = response.getSource(); if (StringUtil.isBlank(sessionId)) { sessionId = UUID.randomUUID().toString(); } final Map<String, Object> vars = new HashMap<String, Object>(); vars.put("configId", configId); vars.put("client", esClient); vars.put("sessionId", sessionId); try { // invoke execute event script executeScript(crawlSettings, vars, "execute"); @SuppressWarnings("unchecked") final List<Map<String, Object>> targetList = (List<Map<String, Object>>) crawlSettings.get("target"); if (targetList == null || targetList.isEmpty()) { print("No targets for crawling."); return 1; } crawler.setSessionId(sessionId); // HttpClient Parameters final Map<String, Object> paramMap = new HashMap<String, Object>(); crawler.getClientFactory().setInitParameterMap(paramMap); // user agent final String userAgent = SettingsUtils.get(crawlSettings, "user_agent", defaultUserAgent); if (StringUtil.isNotBlank(userAgent)) { paramMap.put(HcHttpClient.USER_AGENT_PROPERTY, userAgent); } // robots.txt parser final Boolean robotsTxtEnabled = SettingsUtils.get(crawlSettings, "robots_txt", Boolean.TRUE); paramMap.put(HcHttpClient.ROBOTS_TXT_ENABLED_PROPERTY, robotsTxtEnabled); // proxy final Map<String, Object> proxyMap = SettingsUtils.get(crawlSettings, "proxy", null); if (proxyMap != null) { final Object host = proxyMap.get("host"); if (host != null) { paramMap.put(HcHttpClient.PROXY_HOST_PROPERTY, host); final Object portObj = proxyMap.get("port"); if (portObj instanceof Integer) { paramMap.put(HcHttpClient.PROXY_PORT_PROPERTY, portObj); } else { paramMap.put(HcHttpClient.PROXY_PORT_PROPERTY, Integer.valueOf(8080)); } } } // authentications // "authentications":[{"scope":{"scheme":"","host":"","port":0,"realm":""}, // "credentials":{"username":"","password":""}},{...}] final List<Map<String, Object>> authList = SettingsUtils.get(crawlSettings, "authentications", null); if (authList != null && !authList.isEmpty()) { final List<Authentication> basicAuthList = new ArrayList<Authentication>(); for (final Map<String, Object> authObj : authList) { @SuppressWarnings("unchecked") final Map<String, Object> scopeMap = (Map<String, Object>) authObj.get("scope"); String scheme = SettingsUtils.get(scopeMap, "scheme", StringUtil.EMPTY).toUpperCase(Locale.ENGLISH); if (StringUtil.isBlank(scheme)) { logger.warn("Invalid authentication: " + authObj); continue; } @SuppressWarnings("unchecked") final Map<String, Object> credentialMap = (Map<String, Object>) authObj.get("credentials"); final String username = SettingsUtils.get(credentialMap, "username", null); if (StringUtil.isBlank(username)) { logger.warn("Invalid authentication: " + authObj); continue; } final String host = SettingsUtils.get(authObj, "host", AuthScope.ANY_HOST); final int port = SettingsUtils.get(authObj, "port", AuthScope.ANY_PORT); final String realm = SettingsUtils.get(authObj, "realm", AuthScope.ANY_REALM); final String password = SettingsUtils.get(credentialMap, "password", null); AuthScheme authScheme = null; Credentials credentials = null; if (BASIC_SCHEME.equalsIgnoreCase(scheme)) { authScheme = new BasicScheme(); credentials = new UsernamePasswordCredentials(username, password); } else if (DIGEST_SCHEME.equals(scheme)) { authScheme = new DigestScheme(); credentials = new UsernamePasswordCredentials(username, password); } else if (NTLM_SCHEME.equals(scheme)) { authScheme = new NTLMScheme(new JcifsEngine()); scheme = AuthScope.ANY_SCHEME; final String workstation = SettingsUtils.get(credentialMap, "workstation", null); final String domain = SettingsUtils.get(credentialMap, "domain", null); credentials = new NTCredentials(username, password, workstation == null ? StringUtil.EMPTY : workstation, domain == null ? StringUtil.EMPTY : domain); } final AuthenticationImpl auth = new AuthenticationImpl(new AuthScope(host, port, realm, scheme), credentials, authScheme); basicAuthList.add(auth); } paramMap.put(HcHttpClient.BASIC_AUTHENTICATIONS_PROPERTY, basicAuthList.toArray(new Authentication[basicAuthList.size()])); } // request header // "headers":[{"name":"","value":""},{}] final List<Map<String, Object>> headerList = SettingsUtils.get(crawlSettings, "headers", null); if (headerList != null && !headerList.isEmpty()) { final List<RequestHeader> requestHeaderList = new ArrayList<RequestHeader>(); for (final Map<String, Object> headerObj : headerList) { final String name = SettingsUtils.get(headerObj, "name", null); final String value = SettingsUtils.get(headerObj, "value", null); if (name != null && value != null) { requestHeaderList.add(new RequestHeader(name, value)); } } paramMap.put(HcHttpClient.REQUERT_HEADERS_PROPERTY, requestHeaderList.toArray(new RequestHeader[requestHeaderList.size()])); } // url @SuppressWarnings("unchecked") final List<String> urlList = (List<String>) crawlSettings.get("urls"); if (urlList == null || urlList.isEmpty()) { print("No url for crawling."); return 1; } for (final String url : urlList) { try { crawler.addUrl(url); } catch (DocumentAlreadyExistsException e) { logger.warn(url + " exists in " + sessionId); } } // include regex @SuppressWarnings("unchecked") final List<String> includeFilterList = (List<String>) crawlSettings.get("include_urls"); if (includeFilterList != null) { for (final String regex : includeFilterList) { try { crawler.addIncludeFilter(regex); } catch (DocumentAlreadyExistsException e) { logger.warn(regex + " exists in " + sessionId); } } } // exclude regex @SuppressWarnings("unchecked") final List<String> excludeFilterList = (List<String>) crawlSettings.get("exclude_urls"); if (excludeFilterList != null) { for (final String regex : excludeFilterList) { try { crawler.addExcludeFilter(regex); } catch (DocumentAlreadyExistsException e) { logger.warn(regex + " exists in " + sessionId); } } } final CrawlerContext robotContext = crawler.getCrawlerContext(); // max depth final int maxDepth = SettingsUtils.get(crawlSettings, "max_depth", -1); robotContext.setMaxDepth(maxDepth); // max access count final int maxAccessCount = SettingsUtils.get(crawlSettings, "max_access_count", 100); robotContext.setMaxAccessCount(maxAccessCount); // num of thread final int numOfThread = SettingsUtils.get(crawlSettings, "num_of_thread", 5); robotContext.setNumOfThread(numOfThread); // interval final long interval = SettingsUtils.get(crawlSettings, "interval", 1000L); final WebRiverIntervalController intervalController = (WebRiverIntervalController) crawler.getIntervalController(); intervalController.setDelayMillisForWaitingNewUrl(interval); // river params riverConfig.setIndex(SettingsUtils.get(crawlSettings, "index", "web")); riverConfig.setType(SettingsUtils.get(crawlSettings, "type", configId)); riverConfig.setOverwrite(SettingsUtils.get(crawlSettings, "overwrite", Boolean.FALSE)); riverConfig.setIncremental(SettingsUtils.get(crawlSettings, "incremental", Boolean.FALSE)); // crawl config for (final Map<String, Object> targetMap : targetList) { @SuppressWarnings("unchecked") final Map<String, Object> patternMap = (Map<String, Object>) targetMap.get("pattern"); @SuppressWarnings("unchecked") final Map<String, Map<String, Object>> propMap = (Map<String, Map<String, Object>>) targetMap.get("properties"); if (patternMap != null && propMap != null) { if (logger.isDebugEnabled()) { logger.debug("patternMap: " + patternMap); logger.debug("propMap: " + propMap); } @SuppressWarnings("unchecked") final Map<String, Object> settingMap = (Map<String, Object>) targetMap.get("settings"); riverConfig.addScrapingRule(settingMap, patternMap, propMap); } else { logger.warn("Invalid pattern or target: patternMap: " + patternMap + ", propMap: " + propMap); } } // run s2robot crawler.execute(); crawler.stop(); } finally { // invoke finish event script executeScript(crawlSettings, vars, "finish"); if (cleanup) { crawler.cleanup(sessionId); } } return 0; } protected void executeScript(final Map<String, Object> crawlSettings, final Map<String, Object> vars, final String target) { final Map<String, Object> scriptSettings = SettingsUtils.get(crawlSettings, "script"); final String script = SettingsUtils.get(scriptSettings, target); final String lang = SettingsUtils.get(scriptSettings, "lang", WebRiverConstants.DEFAULT_SCRIPT_LANG); final String scriptTypeValue = SettingsUtils.get(scriptSettings, "script_type", "inline"); ScriptType scriptType; if (ScriptType.FILE.toString().equalsIgnoreCase(scriptTypeValue)) { scriptType = ScriptType.FILE; } else if (ScriptType.INDEXED.toString().equalsIgnoreCase(scriptTypeValue)) { scriptType = ScriptType.INDEXED; } else { scriptType = ScriptType.INLINE; } if (StringUtil.isNotBlank(script)) { final Map<String, Object> localVars = new HashMap<String, Object>(vars); localVars.put("container", SingletonLaContainerFactory.getContainer()); localVars.put("settings", crawlSettings); localVars.put("logger", logger); try { final Object result = scriptService.execute(lang, script, scriptType, localVars); logger.info("[{}] \"{}\" => {}", target, script, result); } catch (final Exception e) { logger.warn("Failed to execute script: {}", e, script); } } } }
package org.ddd4j.value.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.ddd4j.contract.Require; @FunctionalInterface public interface Seq<E> extends Iterable<E> { @FunctionalInterface interface ThrowingConsumer<E, T extends Throwable> { void accept(E entry) throws T; } @FunctionalInterface interface Extender<E> { Seq<E> apply(Seq<? extends E> other); default Seq<E> array(E[] entries) { return array(entries, entries.length); } default Seq<E> array(E[] entries, int newLength) { entries = Arrays.copyOf(entries, newLength); return apply(Arrays.asList(entries)::stream); } default Seq<E> array(E[] entries, int from, int to) { entries = Arrays.copyOfRange(entries, from, to); return apply(Arrays.asList(entries)::stream); } default Seq<E> collection(Collection<? extends E> entries) { return apply(new ArrayList<E>(entries)::stream); } default Seq<E> entry(E entry) { return apply(Collections.singleton(entry)::stream); } default Seq<E> iterable(Iterable<? extends E> iterable) { List<E> list = new ArrayList<>(); iterable.forEach(list::add); return apply(list::stream); } default Seq<E> nextIfAvailable(Iterator<? extends E> iterator) { return iterator.hasNext() ? entry(iterator.next()) : apply(Seq.empty()); } default Seq<E> repeated(int repeat, E entry) { return apply(Collections.nCopies(repeat, entry)::stream); } default Seq<E> seq(Seq<? extends E> seq) { return apply(Require.nonNull(seq)); } } @FunctionalInterface interface Filter<E> { <X> Seq<X> apply(Function<Seq<E>, Stream<X>> filter); default <X> Seq<X> applyStream(Function<Stream<E>, Stream<X>> filter) { Require.nonNull(filter); return apply(s -> filter.apply(s.stream())); } default Seq<E> by(Predicate<? super E> predicate) { Require.nonNull(predicate); return applyStream(s -> s.filter(predicate)); } default Seq<E> by(Supplier<Predicate<? super E>> predicateSupplier) { Require.nonNull(predicateSupplier); return applyStream(s -> s.filter(predicateSupplier.get())); } default <X> Seq<X> byType(Class<? extends X> type) { Require.nonNull(type); return applyStream(s -> s.filter(type::isInstance).map(type::cast)); } default Seq<E> distinct() { return distinct(Function.identity()); } default Seq<E> distinct(Function<? super E, ?> keyMapper) { Require.nonNull(keyMapper); return by(() -> { Set<Object> visited = new HashSet<>(); return e -> visited.add(keyMapper.apply(e)); }); } default Seq<E> limit(long count) { return applyStream(s -> s.limit(count)); } default Seq<E> limitUntil(Predicate<? super E> predicate) { return limitWhile(predicate.negate()); } default Seq<E> limitWhile(Predicate<? super E> predicate) { Require.nonNull(predicate); return by(() -> { Ref<Boolean> filterOutcome = Ref.of(Boolean.TRUE); return e -> filterOutcome.updateAndGet(b -> predicate.test(e), b -> b); }); } default Seq<E> nonNull() { return by(Objects::nonNull); } default Seq<E> skip(long count) { return applyStream(s -> s.skip(count)); } default Seq<E> skipUntil(Predicate<? super E> predicate) { Require.nonNull(predicate); return by(() -> { Ref<Boolean> filterOutcome = Ref.of(Boolean.FALSE); return e -> filterOutcome.updateAndGet(b -> predicate.test(e), b -> !b); }); } default Seq<E> skipWhile(Predicate<? super E> predicate) { return skipUntil(predicate.negate()); } default Seq<E> slice(long from, long to) { return applyStream(s -> s.skip(from).limit(to - from)); } default <X> Seq<E> where(Function<Mapper<E>, X> mapper, Predicate<? super X> predicate) { Require.nonNullElements(mapper, predicate); return apply(s -> s.stream().filter(e -> predicate.test(mapper.apply(s.map())))); } } @FunctionalInterface interface Joiner<L> { @FunctionalInterface interface Join<L, R, T> { Seq<T> apply(BiPredicate<? super L, ? super R> predicate, Function<Seq<L>, Seq<L>> leftEmpty, Function<Seq<R>, Seq<R>> rightEmpty); default Seq<T> execute() { // TODO return apply(null, null, null); } default Join<L, R, T> on(BiPredicate<? super L, ? super R> predicate) { return on(Function.identity(), Function.identity(), predicate); } default <X, Y> Join<L, R, T> on(Function<? super L, X> leftProperty, Function<? super R, Y> rightProperty, BiPredicate<? super X, ? super Y> predicate) { Require.nonNullElements(leftProperty, rightProperty, predicate); return (p, le, re) -> apply((l, r) -> p.test(l, r) && predicate.test(leftProperty.apply(l), rightProperty.apply(r)), le, re); } default Join<L, R, T> onEqual() { return on(Function.identity(), Function.identity(), Objects::equals); } default Join<L, R, T> onEqual(Function<? super L, ?> leftProperty, Function<? super R, ?> rightProperty) { return on(leftProperty, rightProperty, Objects::equals); } default Join<L, R, T> withDefaults(L left, R right) { return (p, le, re) -> apply(p, le.andThen(s -> s.append().entry(left)), re.andThen(s -> s.append().entry(right))); } } <R, T> Seq<T> apply(Seq<R> other, BiPredicate<? super L, ? super R> predicate, BiFunction<? super L, ? super R, T> mapper, Function<Seq<L>, Seq<L>> leftEmpty, Function<Seq<R>, Seq<R>> rightEmpty); default <R> Join<L, R, Tpl<L, R>> inner(Seq<R> other) { return inner(other, Tpl::of); } default <R, T> Join<L, R, T> inner(Seq<R> other, BiFunction<? super L, ? super R, T> mapper) { return (p, le, re) -> apply(other, (l, r) -> true, mapper, le, re); } } @FunctionalInterface interface Mapper<E> { <X> Seq<X> apply(Function<Seq<E>, Seq<X>> mapper); default Seq<Tpl<E, E>> consecutivePairwise() { return toSupplied(() -> { Ref<E> last = Ref.create(); return e -> last.update(t -> e); }).filter().skip(1); } default Seq<E> consecutiveScanned(BinaryOperator<E> operator) { Require.nonNull(operator); return consecutivePairwise().map().to(t -> t.fold(operator)); } default <X> Seq<X> flat(Function<? super E, ? extends Seq<? extends X>> mapper) { return flatStream(mapper.andThen(Seq::stream)); } default <X> Seq<X> flatArray(Function<? super E, X[]> mapper) { return flatStream(mapper.andThen(Stream::of)); } default <X> Seq<X> flatCollection(Function<? super E, Collection<? extends X>> mapper) { return flatStream(mapper.andThen(Collection::stream)); } default <X> Seq<X> flatStream(Function<? super E, Stream<? extends X>> mapper) { Require.nonNull(mapper); return apply(s -> () -> s.stream().flatMap(mapper)); } default <K> Seq<Tpl<K, Seq<E>>> grouped(Function<? super E, K> mapper) { Require.nonNull(mapper); return apply(s -> s.map().to(mapper).filter().distinct().map().to(k -> Tpl.of(k, s.filter().by(e -> Objects.equals(k, mapper.apply(e)))))); } default Seq<Seq<E>> partition(long partitionSize) { return apply(s -> { long index = 0L; long size = s.size(); List<Seq<E>> partitions = new ArrayList<>((int) (size / partitionSize) + 1); for (int i = 0; i < size; i++) { partitions.add(s.filter().slice(index, index += partitionSize)); } return partitions::stream; }); } default <P> Seq<Tpl<E, P>> project(Function<? super E, P> mapper) { Require.nonNull(mapper); return to(e -> Tpl.of(e, mapper.apply(e))); } default Seq<E> recursively(Function<? super E, Seq<E>> mapper) { Require.nonNull(mapper); return apply(s -> s.append().seq(flat(mapper).map().recursively(mapper))); } default Seq<E> recursivelyArray(Function<? super E, E[]> mapper) { Require.nonNull(mapper); return apply(s -> s.append().seq(flatArray(mapper).map().recursivelyArray(mapper))); } default Seq<E> recursivelyCollection(Function<? super E, Collection<? extends E>> mapper) { Require.nonNull(mapper); return apply(s -> s.append().seq(flatCollection(mapper).map().recursivelyCollection(mapper))); } default Seq<E> recursivelyStream(Function<? super E, Stream<? extends E>> mapper) { Require.nonNull(mapper); return apply(s -> s.append().seq(flatStream(mapper).map().recursivelyStream(mapper))); } default <X> Seq<X> to(Function<? super E, ? extends X> mapper) { Require.nonNull(mapper); return apply(s -> () -> s.stream().map(mapper)); } default <X> Seq<X> toSupplied(Supplier<Function<? super E, ? extends X>> mapperSupplier) { Require.nonNull(mapperSupplier); return apply(s -> () -> s.stream().map(mapperSupplier.get())); } default Seq<Tpl<E, Long>> zipWithIndex() { return toSupplied(() -> { Ref<Long> index = Ref.of(0L); return e -> Tpl.of(e, index.getAndUpdate(t -> t++)); }); } } @SuppressWarnings("unchecked") static <E> Seq<E> cast(Seq<? extends E> sequence) { Require.nonNull(sequence); return () -> { return (Stream<E>) sequence.stream(); }; } static <E> Seq<E> concat(Seq<? extends E> a, Seq<? extends E> b) { if (a.isEmpty()) { return Seq.cast(b); } else if (b.isEmpty()) { return Seq.cast(a); } else { return () -> Stream.concat(a.stream(), b.stream()); } } static <E> Seq<E> empty() { return Stream::empty; } static <E> Seq<E> of(Collection<E> collection) { return new ArrayList<>(collection)::stream; } @SafeVarargs static <E> Seq<E> of(E... entries) { return Arrays.asList(entries)::stream; } static <E> Seq<E> of(Iterable<E> iterable) { Require.nonNull(iterable); return () -> StreamSupport.stream(iterable.spliterator(), false); } static <E> Seq<E> ofRemaining(Iterator<E> iterator) { List<E> list = new ArrayList<>(); iterator.forEachRemaining(list::add); return list::stream; } static <E> Seq<E> singleton(E entry) { return Collections.singleton(entry)::stream; } default Extender<E> append() { return o -> concat(this, o); } default Extender<Object> appendAny() { return o -> concat(this, o); } default String asString() { return toList().toString(); } default <X> Seq<X> cast(Class<X> type) { return cast(type, true); } default <X> Seq<X> cast(Class<X> type, boolean failFast) { if (failFast && !stream().allMatch(type::isInstance)) { throw new ClassCastException("Could not cast " + this + " to " + type); } else { return map().to(type::cast); } } default Seq<E> compact() { return isFinite() ? toList()::stream : this; } default <X> boolean contains(Class<X> type) { return contains(type::isInstance); } default <X> boolean contains(Class<X> type, Predicate<? super X> predicate) { return stream().filter(type::isInstance).map(type::cast).anyMatch(predicate); } default <X> boolean contains(Object element) { return contains(element::equals); } default <X> boolean contains(Predicate<? super E> predicate) { return stream().anyMatch(predicate); } default boolean equal(Seq<E> other) { Iterator<E> iterator = other.iterator(); return stream().allMatch(e -> Objects.equals(e, iterator.next())); } default Filter<E> filter() { return this::filter; } default <X> Seq<X> filter(Function<Seq<E>, Stream<X>> filter) { Require.nonNull(filter); return () -> filter.apply(this); } default Optional<E> fold(BiFunction<? super E, ? super E, ? extends E> mapper) { return fold(Function.identity(), mapper); } default <T> Optional<T> fold(Function<? super E, ? extends T> creator, BiFunction<? super T, ? super E, ? extends T> mapper) { Optional<T> identity = head().map(creator); return tail().fold(identity, (o, e) -> o.map(t -> mapper.apply(t, e))); } default <T> T fold(T identity, BiFunction<? super T, ? super E, ? extends T> mapper) { T result = identity; for (E element : this) { result = mapper.apply(result, element); } return result; } default <T extends Throwable> void forEach(ThrowingConsumer<? super E, T> action) throws T { Iterator<E> iterator = iterator(); while (iterator.hasNext()) { action.accept(iterator.next()); } } default Optional<E> get(long index) { return stream().skip(index).findFirst(); } default <K> Map<K, Seq<E>> groupBy(Function<? super E, K> mapper) { return map().grouped(mapper).toMap(tpl -> tpl.getLeft(), tpl -> tpl.getRight()); } default Optional<E> head() { return stream().findFirst(); } default Seq<E> ifMatches(Predicate<? super Seq<E>> predicate, Function<? super Seq<E>, ? extends Seq<E>> function) { return predicate.test(this) ? function.apply(this) : this; } default Seq<E> intersect(Seq<? extends E> other, boolean anyInfinite) { Require.nonNull(other); return of(() -> { Iterator<? extends E> i1 = this.iterator(); Iterator<? extends E> i2 = other.iterator(); return new Iterator<E>() { private boolean useFirst = true; @Override public boolean hasNext() { return anyInfinite ? i1.hasNext() && i2.hasNext() : i1.hasNext() || i2.hasNext(); } @Override public E next() { if (!hasNext()) { throw new NoSuchElementException(); } else if (useFirst && i1.hasNext()) { useFirst = !i2.hasNext(); return i1.next(); } else if (i2.hasNext()) { useFirst = i1.hasNext(); return i2.next(); } else { throw new NoSuchElementException(); } } }; }); } default boolean isEmpty() { return size() == 0L; } default boolean isFinite() { long size = size(); return size >= 0L && size != Long.MAX_VALUE; } default boolean isNotEmpty() { return !isEmpty(); } @Override default Iterator<E> iterator() { return stream().iterator(); } default Joiner<E> join() { return this::join; } default <R, T> Seq<T> join(Seq<R> other, BiPredicate<? super E, ? super R> predicate, BiFunction<? super E, ? super R, T> mapper, Function<Seq<E>, Seq<E>> leftEmpty, Function<Seq<R>, Seq<R>> rightEmpty) { Require.nonNullElements(other, predicate, mapper, leftEmpty, rightEmpty); return this.map() .flat(l -> other.filter().by(r -> predicate.test(l, r)).ifMatches(Seq::isEmpty, rightEmpty).map().to(r -> mapper.apply(l, r))) .append() .seq(other.filter().by(r -> this.stream().noneMatch(l -> predicate.test(l, r))).map().flat( r -> leftEmpty.apply(Seq.empty()).map().to(l -> mapper.apply(l, r)))); } default Optional<E> last() { return fold((t, e) -> e); } default Mapper<E> map() { return this::map; } default <X> Seq<X> map(Function<Seq<E>, Seq<X>> mapper) { Require.nonNull(mapper); return mapper.apply(this); } default Extender<E> prepend() { return o -> concat(o, this); } default Extender<Object> prependAny() { return o -> concat(o, this); } default Seq<E> reverse() { List<E> result = toList(); Collections.reverse(result); return result::stream; } default long size() { return stream().spliterator().getExactSizeIfKnown(); } default Tpl<Seq<E>, Seq<E>> splitAt(long position) { return Tpl.of(filter().limit(position), filter().skip(position)); } default Tpl<Optional<E>, Seq<E>> splitAtHead() { return Tpl.of(head(), tail()); } Stream<E> stream(); default Seq<E> tail() { return new Seq<E>() { @Override public long size() { // skipped stream have no size :( long size = Seq.this.size(); if (size == 0) { return 0; } else if (size < 0) { return -1; } else { return size - 1; } } @Override public Stream<E> stream() { return Seq.this.stream().skip(1L); } }; } default E[] toArray(IntFunction<E[]> generator) { return stream().toArray(generator); } default List<E> toList() { return stream().collect(Collectors.toList()); } default <K> Map<K, E> toMap(Function<? super E, K> keyMapper) { return stream().collect(Collectors.toMap(keyMapper, Function.identity())); } default <K, V> Map<K, V> toMap(Function<? super E, K> keyMapper, Function<? super E, V> valueMapper) { return stream().collect(Collectors.toMap(keyMapper, valueMapper)); } default Joiner<E> zip() { return this::zip; } default <R, T> Seq<T> zip(Seq<R> other, BiPredicate<? super E, ? super R> predicate, BiFunction<? super E, ? super R, T> mapper, Function<Seq<E>, Seq<E>> leftEmpty, Function<Seq<R>, Seq<R>> rightEmpty) { Require.nonNullElements(other, predicate, mapper, leftEmpty, rightEmpty); return of(() -> { Iterator<E> i1 = this.iterator(); Iterator<R> i2 = other.iterator(); return new Iterator<T>() { private Ref<R> remainder; @Override public boolean hasNext() { return remainder != null || i1.hasNext() || i2.hasNext(); } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } else if (remainder != null) { if (i1.hasNext()) { // TODO } return null; } return null; } }; }); } }
package edu.gatech.oad.antlab.person; /** * A simple class for person 1 * returns their name and a * modified string * * @author Bob * @version 1.1 */ public class Person1 { /** Holds the persons real name */ private String name; /** * The constructor, takes in the persons * name * @param pname the person's real name */ public Person1(String pname) { name = pname; } /** * This method should take the string * input and return its characters rotated * 2 positions. * given "gtg123b" it should return * "g123bgt". * * @param input the string to be modified * @return the modified string */ private String calc(String input) { //Person 1 put your implementation here char[] original = input.tocharArray(); String modified = ""; for(int i = 2; i < original.length; i++) { modified += original[i]; } for(int i = 0; i < 2; i++) { modified += original[i]; } return modified; } /** * Return a string rep of this object * that varies with an input string * * @param input the varying string * @return the string representing the * object */ public String toString(String input) { return name + calc(input); } }
package org.jtrfp.trcl.gui; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.beans.PropertyEditorSupport; import org.jtrfp.trcl.gpu.GLFrameBuffer; public class TRBeanUtils { public static PropertyEditor getDefaultPropertyEditor(Object o){ try{final PropertyEditorSupport pe = (PropertyEditorSupport)PropertyEditorManager.findEditor(o.getClass()); pe.setSource(o); return pe;} catch(Exception e){e.printStackTrace();} return null; }//end getDefaultPropertyEditor(...) public static String camelCaseToSentence(String camelCase) { String sentence = ""; final char [] camelChars = camelCase.toCharArray(); for( int i = 0; i < camelChars.length; i++ ) { boolean addSpace = ( Character.isUpperCase(camelChars[i])); if( i+1 < camelChars.length) { if( Character.isUpperCase(camelChars[i+1]) || Character.isDigit(camelChars[i+1]) ) addSpace = false; } else if( Character.isUpperCase(camelChars[i]) || Character.isDigit(camelChars[i])) addSpace = false; if( i > 0 && Character.isLowerCase(camelChars[i-1]) && Character.isUpperCase(camelChars[i])) addSpace = true; if( i == 0) addSpace = false; if(addSpace) sentence += " "; if( i == 0 ) sentence += Character.toUpperCase(camelChars[i]); else sentence += camelChars[i]; }//end for(chars) return sentence; }//end camelCaseToSentence() }//end TRBeanUtils
package gg.uhc.uhc.command; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.bukkit.ChatColor; import org.bukkit.command.*; import org.bukkit.util.StringUtil; import java.util.Arrays; import java.util.List; import java.util.Map; public class SubcommandCommand implements TabExecutor { protected final Map<String, CommandExecutor> commandExecutors = Maps.newHashMap(); protected final Map<String, TabCompleter> tabCompleters = Maps.newHashMap(); public void registerSubcommand(String name, TabExecutor tabExecutor) { this.registerSubcommand(name, tabExecutor, tabExecutor); } public void registerSubcommand(String name, CommandExecutor executor) { this.registerSubcommand(name, executor, null); } public void registerSubcommand(String name, CommandExecutor commandExecutor, TabCompleter tabCompleter) { Preconditions.checkState(!commandExecutors.containsKey(name), "Subroute is already registered"); commandExecutors.put(name.toLowerCase(), commandExecutor); if (tabCompleter != null) { tabCompleters.put(name.toLowerCase(), tabCompleter); } } protected void sendUsage(CommandSender sender) { sender.sendMessage(ChatColor.RED + "This command requires an argument. Available: [" + Joiner.on(",").join(commandExecutors.keySet())+ "]"); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (args.length == 0) { sendUsage(sender); return true; } CommandExecutor subcommand = commandExecutors.get(args[0]); if (subcommand == null) { sendUsage(sender); return true; } // cut subroute arg off and run subcommand return subcommand.onCommand(sender, command, label, Arrays.copyOfRange(args, 1, args.length)); } @Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) { if (args.length == 1) { List<String> potentials = Lists.newArrayList(); StringUtil.copyPartialMatches(args[0], commandExecutors.keySet(), potentials); return potentials; } else { TabCompleter subcommand = tabCompleters.get(args[0]); if (subcommand == null) { return ImmutableList.of(); } return subcommand.onTabComplete(sender, command, alias, Arrays.copyOfRange(args, 1, args.length)); } } }
package org.junit.runners; import static org.junit.internal.runners.rules.RuleFieldValidator.CLASS_RULE_METHOD_VALIDATOR; import static org.junit.internal.runners.rules.RuleFieldValidator.CLASS_RULE_VALIDATOR; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.internal.AssumptionViolatedException; import org.junit.internal.runners.model.EachTestNotifier; import org.junit.internal.runners.statements.RunAfters; import org.junit.internal.runners.statements.RunBefores; import org.junit.rules.RunRules; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.Filterable; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.manipulation.Sortable; import org.junit.runner.manipulation.Sorter; import org.junit.runner.notification.RunNotifier; import org.junit.runner.notification.StoppedByUserException; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.MultipleFailureException; import org.junit.runners.model.RunnerScheduler; import org.junit.runners.model.Statement; import org.junit.runners.model.TestClass; /** * Provides most of the functionality specific to a Runner that implements a * "parent node" in the test tree, with children defined by objects of some data * type {@code T}. (For {@link BlockJUnit4ClassRunner}, {@code T} is * {@link Method} . For {@link Suite}, {@code T} is {@link Class}.) Subclasses * must implement finding the children of the node, describing each child, and * running each child. ParentRunner will filter and sort children, handle * {@code @BeforeClass} and {@code @AfterClass} methods, * handle annotated {@link ClassRule}s, create a composite * {@link Description}, and run children sequentially. * * @since 4.5 */ public abstract class ParentRunner<T> extends Runner implements Filterable, Sortable { private final Object fLock = new Object(); private final TestClass fTestClass; private volatile Collection<T> fFilteredChildren = null; private volatile RunnerScheduler fScheduler = new RunnerScheduler() { public void schedule(Runnable childStatement) { childStatement.run(); } public void finished() { // do nothing } }; /** * Constructs a new {@code ParentRunner} that will run {@code @TestClass} */ protected ParentRunner(Class<?> testClass) throws InitializationError { fTestClass = new TestClass(testClass); validate(); } // Must be overridden /** * Returns a list of objects that define the children of this Runner. */ protected abstract List<T> getChildren(); /** * Returns a {@link Description} for {@code child}, which can be assumed to * be an element of the list returned by {@link ParentRunner#getChildren()} */ protected abstract Description describeChild(T child); /** * Runs the test corresponding to {@code child}, which can be assumed to be * an element of the list returned by {@link ParentRunner#getChildren()}. * Subclasses are responsible for making sure that relevant test events are * reported through {@code notifier} */ protected abstract void runChild(T child, RunNotifier notifier); // May be overridden /** * Adds to {@code errors} a throwable for each problem noted with the test class (available from {@link #getTestClass()}). * Default implementation adds an error for each method annotated with * {@code @BeforeClass} or {@code @AfterClass} that is not * {@code public static void} with no arguments. */ protected void collectInitializationErrors(List<Throwable> errors) { validatePublicVoidNoArgMethods(BeforeClass.class, true, errors); validatePublicVoidNoArgMethods(AfterClass.class, true, errors); validateClassRules(errors); } /** * Adds to {@code errors} if any method in this class is annotated with * {@code annotation}, but: * <ul> * <li>is not public, or * <li>takes parameters, or * <li>returns something other than void, or * <li>is static (given {@code isStatic is false}), or * <li>is not static (given {@code isStatic is true}). */ protected void validatePublicVoidNoArgMethods(Class<? extends Annotation> annotation, boolean isStatic, List<Throwable> errors) { List<FrameworkMethod> methods = getTestClass().getAnnotatedMethods(annotation); for (FrameworkMethod eachTestMethod : methods) { eachTestMethod.validatePublicVoidNoArg(isStatic, errors); } } private void validateClassRules(List<Throwable> errors) { CLASS_RULE_VALIDATOR.validate(getTestClass(), errors); CLASS_RULE_METHOD_VALIDATOR.validate(getTestClass(), errors); } /** * Constructs a {@code Statement} to run all of the tests in the test class. Override to add pre-/post-processing. * Here is an outline of the implementation: * <ul> * <li>Call {@link #runChild(Object, RunNotifier)} on each object returned by {@link #getChildren()} (subject to any imposed filter and sort).</li> * <li>ALWAYS run all non-overridden {@code @BeforeClass} methods on this class * and superclasses before the previous step; if any throws an * Exception, stop execution and pass the exception on. * <li>ALWAYS run all non-overridden {@code @AfterClass} methods on this class * and superclasses before any of the previous steps; all AfterClass methods are * always executed: exceptions thrown by previous steps are combined, if * necessary, with exceptions from AfterClass methods into a * {@link MultipleFailureException}. * </ul> * * @return {@code Statement} */ protected Statement classBlock(final RunNotifier notifier) { Statement statement = childrenInvoker(notifier); statement = withBeforeClasses(statement); statement = withAfterClasses(statement); statement = withClassRules(statement); return statement; } /** * Returns a {@link Statement}: run all non-overridden {@code @BeforeClass} methods on this class * and superclasses before executing {@code statement}; if any throws an * Exception, stop execution and pass the exception on. */ protected Statement withBeforeClasses(Statement statement) { List<FrameworkMethod> befores = fTestClass .getAnnotatedMethods(BeforeClass.class); return befores.isEmpty() ? statement : new RunBefores(statement, befores, null); } /** * Returns a {@link Statement}: run all non-overridden {@code @AfterClass} methods on this class * and superclasses before executing {@code statement}; all AfterClass methods are * always executed: exceptions thrown by previous steps are combined, if * necessary, with exceptions from AfterClass methods into a * {@link MultipleFailureException}. */ protected Statement withAfterClasses(Statement statement) { List<FrameworkMethod> afters = fTestClass .getAnnotatedMethods(AfterClass.class); return afters.isEmpty() ? statement : new RunAfters(statement, afters, null); } /** * Returns a {@link Statement}: apply all * static fields assignable to {@link TestRule} * annotated with {@link ClassRule}. * * @param statement the base statement * @return a RunRules statement if any class-level {@link Rule}s are * found, or the base statement */ private Statement withClassRules(Statement statement) { List<TestRule> classRules = classRules(); return classRules.isEmpty() ? statement : new RunRules(statement, classRules, getDescription()); } /** * @return the {@code ClassRule}s that can transform the block that runs * each method in the tested class. */ protected List<TestRule> classRules() { List<TestRule> result = fTestClass.getAnnotatedMethodValues(null, ClassRule.class, TestRule.class); result.addAll(fTestClass.getAnnotatedFieldValues(null, ClassRule.class, TestRule.class)); return result; } /** * Returns a {@link Statement}: Call {@link #runChild(Object, RunNotifier)} * on each object returned by {@link #getChildren()} (subject to any imposed * filter and sort) */ protected Statement childrenInvoker(final RunNotifier notifier) { return new Statement() { @Override public void evaluate() { runChildren(notifier); } }; } private void runChildren(final RunNotifier notifier) { final RunnerScheduler scheduler = fScheduler; try { for (final T each : getFilteredChildren()) { scheduler.schedule(new Runnable() { public void run() { ParentRunner.this.runChild(each, notifier); } }); } } finally { scheduler.finished(); } } /** * Returns a name used to describe this Runner */ protected String getName() { return fTestClass.getName(); } // Available for subclasses /** * Returns a {@link TestClass} object wrapping the class to be executed. */ public final TestClass getTestClass() { return fTestClass; } /** * Runs a {@link Statement} that represents a leaf (aka atomic) test. */ protected final void runLeaf(Statement statement, Description description, RunNotifier notifier) { EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description); eachNotifier.fireTestStarted(); try { statement.evaluate(); } catch (AssumptionViolatedException e) { eachNotifier.addFailedAssumption(e); } catch (Throwable e) { eachNotifier.addFailure(e); } finally { eachNotifier.fireTestFinished(); } } /** * @return the annotations that should be attached to this runner's * description. */ protected Annotation[] getRunnerAnnotations() { return fTestClass.getAnnotations(); } // Implementation of Runner @Override public Description getDescription() { Description description = Description.createSuiteDescription(getName(), getRunnerAnnotations()); for (T child : getFilteredChildren()) { description.addChild(describeChild(child)); } return description; } @Override public void run(final RunNotifier notifier) { EachTestNotifier testNotifier = new EachTestNotifier(notifier, getDescription()); try { Statement statement = classBlock(notifier); statement.evaluate(); } catch (AssumptionViolatedException e) { testNotifier.fireTestIgnored(); } catch (StoppedByUserException e) { throw e; } catch (Throwable e) { testNotifier.addFailure(e); } } // Implementation of Filterable and Sortable public void filter(Filter filter) throws NoTestsRemainException { synchronized (fLock) { List<T> sortedChildren = new ArrayList<T>(getFilteredChildren()); try { for (Iterator<T> iter = sortedChildren.iterator(); iter.hasNext(); ) { T each = iter.next(); if (shouldRun(filter, each)) { try { filter.apply(each); } catch (NoTestsRemainException e) { iter.remove(); } } else { iter.remove(); } } } finally { setFilteredChildren(sortedChildren); } } if (getFilteredChildren().isEmpty()) { throw new NoTestsRemainException(); } } public void sort(Sorter sorter) { synchronized (fLock) { for (T each : getFilteredChildren()) { sortChild(each, sorter); } List<T> sortedChildren = new ArrayList<T>(getFilteredChildren()); Collections.sort(sortedChildren, comparator(sorter)); setFilteredChildren(sortedChildren); } } // Private implementation private void validate() throws InitializationError { List<Throwable> errors = new ArrayList<Throwable>(); collectInitializationErrors(errors); if (!errors.isEmpty()) { throw new InitializationError(errors); } } private void setFilteredChildren(Collection<T> filteredChildren) { fFilteredChildren = Collections.unmodifiableCollection(filteredChildren); } private Collection<T> getFilteredChildren() { if (fFilteredChildren == null) { synchronized (fLock) { setFilteredChildren(getChildren()); } } return fFilteredChildren; } private void sortChild(T child, Sorter sorter) { sorter.apply(child); } private boolean shouldRun(Filter filter, T each) { return filter.shouldRun(describeChild(each)); } private Comparator<? super T> comparator(final Sorter sorter) { return new Comparator<T>() { public int compare(T o1, T o2) { return sorter.compare(describeChild(o1), describeChild(o2)); } }; } /** * Sets a scheduler that determines the order and parallelization * of children. Highly experimental feature that may change. */ public void setScheduler(RunnerScheduler scheduler) { this.fScheduler = scheduler; } }
package invtweaks; import org.jetbrains.annotations.NotNull; import java.awt.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Stores a sorting rule, as a target plus a keyword. The target is provided as an array of preferred slots (ex: target * "1", i.e. first column, is stored as [0, 9, 18, 27]) * * @author Jimeo Wan */ public class InvTweaksConfigSortingRule implements Comparable<InvTweaksConfigSortingRule> { private String constraint; private int[] preferredPositions; private String keyword; private InvTweaksConfigSortingRuleType type; private int priority; private int containerSize; private int containerRowSize; private static final Pattern constraintVertical = Pattern.compile("v", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.LITERAL); private static final Pattern constraintReverse = Pattern.compile("r", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.LITERAL); public InvTweaksConfigSortingRule(InvTweaksItemTree tree, String constraint_, String keyword_, int containerSize_, int containerRowSize_) { keyword = keyword_; constraint = constraint_; containerSize = containerSize_; containerRowSize = containerRowSize_; type = getRuleType(constraint, containerRowSize); preferredPositions = getRulePreferredPositions(constraint); // Compute priority // 1st criteria : the rule type // 2st criteria : the keyword category depth // 3st criteria : the item order in a same category priority = type.getLowestPriority() + 100000 + tree.getKeywordDepth(keyword) * 1000 - tree.getKeywordOrder(keyword); } public static int[] getRulePreferredPositions(String constraint, int containerSize, int containerRowSize) { int[] result = null; int containerColumnSize = containerSize / containerRowSize; // Rectangle rules if(constraint.length() >= 5) { boolean vertical = false; Matcher verticalMatcher = constraintVertical.matcher(constraint); if(verticalMatcher.matches()) { vertical = true; constraint = verticalMatcher.reset().replaceAll(""); } String[] elements = constraint.split("-"); if(elements.length == 2) { int[] slots1 = getRulePreferredPositions(elements[0], containerSize, containerRowSize); int[] slots2 = getRulePreferredPositions(elements[1], containerSize, containerRowSize); if(slots1.length == 1 && slots2.length == 1) { int slot1 = slots1[0], slot2 = slots2[0]; Point point1 = new Point(slot1 % containerRowSize, slot1 / containerRowSize), point2 = new Point(slot2 % containerRowSize, slot2 / containerRowSize); result = new int[(Math.abs(point2.y - point1.y) + 1) * (Math.abs(point2.x - point1.x) + 1)]; int resultIndex = 0; // Swap coordinates for vertical ordering if(vertical) { for(Point p : new Point[]{point1, point2}) { int buffer = p.x; //noinspection SuspiciousNameCombination p.x = p.y; p.y = buffer; } } int y = point1.y; while((point1.y < point2.y) ? y <= point2.y : y >= point2.y) { int x = point1.x; while((point1.x < point2.x) ? x <= point2.x : x >= point2.x) { result[resultIndex++] = (vertical) ? index(containerRowSize, x, y) : index(containerRowSize, y, x); x += (point1.x < point2.x) ? 1 : -1; } y += (point1.y < point2.y) ? 1 : -1; } if(constraintReverse.matcher(constraint).matches()) { reverseArray(result); } } } } else { // Default values int column = -1, row = -1; boolean reverse = false; // Extract chars for(int i = 0; i < constraint.length(); i++) { char c = constraint.charAt(i); int digitValue = Character.digit(c, 36); // radix-36 maps 0-9 to 0-9, and [a-zA-Z] to 10-36, see javadoc if(digitValue >= 1 && digitValue <= containerRowSize && digitValue < 10) { // 1 column = 0, 9 column = 8 column = digitValue - 1; } else if(digitValue >= 10 && (digitValue-10) <= containerColumnSize) { // A row = 0, D row = 3, H row = 7 row = digitValue - 10; } else if(charEqualsIgnoreCase(c, 'r')) { reverse = true; } } // Tile case if(column != -1 && row != -1) { result = new int[]{index(containerRowSize, row, column)}; } // Row case else if(row != -1) { result = new int[containerRowSize]; for(int i = 0; i < containerRowSize; i++) { result[i] = index(containerRowSize, row, reverse ? containerRowSize - 1 - i : i); } } // Column case else { result = new int[containerColumnSize]; for(int i = 0; i < containerColumnSize; i++) { result[i] = index(containerRowSize, reverse ? i : containerColumnSize - 1 - i, column); } } } return result; } public static InvTweaksConfigSortingRuleType getRuleType(String constraint, int rowSize) { InvTweaksConfigSortingRuleType result = InvTweaksConfigSortingRuleType.SLOT; if(constraint.length() == 1 || (constraint.length() == 2 && constraintReverse.matcher(constraint).matches())) { constraint = constraintReverse.matcher(constraint).replaceAll(""); // Column rule int digitValue = Character.digit(constraint.charAt(0), 10); if(digitValue >= 1 && digitValue <= rowSize) { result = InvTweaksConfigSortingRuleType.COLUMN; } // Row rule else { result = InvTweaksConfigSortingRuleType.ROW; } } // Rectangle rule else if(constraint.length() > 4) { // Special case: rectangle rule on a single column if(charEqualsIgnoreCase(constraint.charAt(1), constraint.charAt(4))) { result = InvTweaksConfigSortingRuleType.COLUMN; } // Special case: rectangle rule on a single row else if(charEqualsIgnoreCase(constraint.charAt(0), constraint.charAt(3))) { result = InvTweaksConfigSortingRuleType.ROW; } // Usual case else { result = InvTweaksConfigSortingRuleType.RECTANGLE; } } return result; } private static boolean charEqualsIgnoreCase(char a, char b) { // A crappy basic case-folding comparison, see String.equalsIgnoreCase & the behavior of Pattern with CASE_INSENSITIVE | UNICODE_CASE char aU = Character.toUpperCase(a), bU = Character.toUpperCase(b); return aU == bU || Character.toLowerCase(aU) == Character.toLowerCase(bU); } private static int index(int rowSize, int row, int column) { return row * rowSize + column; } private static void reverseArray(int[] data) { int left = 0; int right = data.length - 1; while(left < right) { int temp = data[left]; data[left] = data[right]; data[right] = temp; left++; right } } public InvTweaksConfigSortingRuleType getType() { return type; } /** * @return An array of preferred positions (from the most to the less preferred). */ public int[] getPreferredSlots() { return preferredPositions; } public String getKeyword() { return keyword; } /** * @return rule priority (for rule sorting) */ public int getPriority() { return priority; } /** * @return Container size (TODO: Map rules to target section) */ public int getContainerSize() { return containerSize; } /** * Compares rules priority : positive value means 'this' is of greater priority than o */ public int compareTo(@NotNull InvTweaksConfigSortingRule o) { return priority - o.priority; } public int[] getRulePreferredPositions(String constraint) { // TODO Caching return InvTweaksConfigSortingRule.getRulePreferredPositions(constraint, containerSize, containerRowSize); } public String toString() { return constraint + " " + keyword; } }
package org.lantern; import java.io.IOException; import java.lang.management.ManagementFactory; import java.net.InetSocketAddress; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicReference; import javax.management.InstanceAlreadyExistsException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.security.auth.login.CredentialException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.jivesoftware.smack.Chat; import org.jivesoftware.smack.MessageListener; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.RosterEntry; import org.jivesoftware.smack.SmackConfiguration; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.Presence.Type; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.lastbamboo.common.p2p.P2PConnectionEvent; import org.lastbamboo.common.p2p.P2PConnectionListener; import org.lastbamboo.common.p2p.P2PConstants; import org.lastbamboo.common.portmapping.NatPmpService; import org.lastbamboo.common.portmapping.PortMapListener; import org.lastbamboo.common.portmapping.PortMappingProtocol; import org.lastbamboo.common.portmapping.UpnpService; import org.lastbamboo.common.stun.client.StunServerRepository; import org.littleshoot.commom.xmpp.XmppP2PClient; import org.littleshoot.commom.xmpp.XmppUtils; import org.littleshoot.p2p.P2P; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.Subscribe; import com.hoodcomputing.natpmp.NatPmpException; /** * Handles logging in to the XMPP server and processing trusted users through * the roster. */ public class DefaultXmppHandler implements XmppHandler { private static final Logger LOG = LoggerFactory.getLogger(DefaultXmppHandler.class); /** * These are the centralized proxies this Lantern instance is using. */ private final Set<ProxyHolder> proxySet = new HashSet<ProxyHolder>(); private final Queue<ProxyHolder> proxies = new ConcurrentLinkedQueue<ProxyHolder>(); /** * This is the set of all peer proxies we know about. We may have * established connections with some of them. The main purpose of this is * to avoid exchanging keys multiple times. */ private final Set<URI> peerProxySet = new HashSet<URI>(); private final Set<ProxyHolder> laeProxySet = new HashSet<ProxyHolder>(); private final Queue<ProxyHolder> laeProxies = new ConcurrentLinkedQueue<ProxyHolder>(); private final AtomicReference<XmppP2PClient> client = new AtomicReference<XmppP2PClient>(); static { SmackConfiguration.setPacketReplyTimeout(30 * 1000); } private final Timer updateTimer = new Timer(true); private volatile long lastInfoMessageScheduled = 0L; private final MessageListener typedListener = new MessageListener() { @Override public void processMessage(final Chat ch, final Message msg) { // Note the Chat will always be null here. We try to avoid using // actual Chat instances due to Smack's strange and inconsistent // behavior with message listeners on chats. final String part = msg.getFrom(); LOG.info("Got chat participant: {} with message:\n {}", part, msg.toXML()); if (StringUtils.isNotBlank(part) && part.startsWith(LanternConstants.LANTERN_JID)) { processLanternHubMessage(msg); } final Integer type = (Integer) msg.getProperty(P2PConstants.MESSAGE_TYPE); if (type != null) { LOG.info("Not processing typed message"); processTypedMessage(msg, type); } } }; private String lastJson = ""; private String hubAddress; private final org.lantern.Roster roster = new org.lantern.Roster(this); private GoogleTalkState state; private String lastUserName; private String lastPass; /** * Creates a new XMPP handler. */ public DefaultXmppHandler() { // This just links connectivity with Google Talk login status when // running in give mode. new GiveModeConnectivityHandler(); LanternUtils.configureXmpp(); prepopulateProxies(); LanternHub.register(this); //setupJmx(); } @Subscribe public void onAuthStatus(final GoogleTalkStateEvent ase) { this.state = ase.getState(); switch (state) { case LOGGED_IN: // We wait until we're logged in before creating our roster. this.roster.loggedIn(); //LanternHub.asyncEventBus().post(new SyncEvent()); synchronized (this.rosterLock) { this.rosterLock.notifyAll(); } break; case LOGGED_OUT: this.roster.reset(); break; case LOGGING_IN: break; case LOGGING_OUT: break; case LOGIN_FAILED: this.roster.reset(); break; } } private void prepopulateProxies() { // Add all the stored proxies. final Collection<String> saved = LanternHub.settings().getProxies(); LOG.info("Proxy set is: {}", saved); for (final String proxy : saved) { // Don't use peer proxies since we're not connected to XMPP yet. if (!proxy.contains("@")) { LOG.info("Adding prepopulated proxy: {}", proxy); addProxy(proxy); } } } @Override public void connect() throws IOException, CredentialException { if (!LanternUtils.isConfigured() && LanternHub.settings().isUiEnabled()) { LOG.info("Not connecting when not configured"); return; } LOG.info("Connecting to XMPP servers..."); String email = LanternHub.settings().getEmail(); String pwd = LanternHub.settings().getPassword(); if (StringUtils.isBlank(email)) { if (!LanternHub.settings().isUiEnabled()) { email = askForEmail(); pwd = askForPassword(); LanternHub.settings().setEmail(email); LanternHub.settings().setPassword(pwd); } else { LOG.error("No user name"); throw new IllegalStateException("No user name"); } LanternHub.settingsIo().write(); } if (StringUtils.isBlank(pwd)) { if (!LanternHub.settings().isUiEnabled()) { pwd = askForPassword(); LanternHub.settings().setPassword(pwd); } else { LOG.error("No password."); throw new IllegalStateException("No password"); } LanternHub.settingsIo().write(); } connect(email, pwd); } @Override public void connect(final String email, final String pwd) throws IOException, CredentialException { LOG.info("Connecting to XMPP servers with user name and password..."); this.lastUserName = email; this.lastPass = pwd; final InetSocketAddress plainTextProxyRelayAddress = new InetSocketAddress("127.0.0.1", LanternUtils.PLAINTEXT_LOCALHOST_PROXY_PORT); NatPmpService natPmpService = null; try { natPmpService = new NatPmp(); } catch (final NatPmpException e) { // This will happen when NAT-PMP is not supported on the local // network. LOG.info("Could not map", e); // We just use a dummy one in this case. natPmpService = new NatPmpService() { @Override public void removeNatPmpMapping(int arg0) { } @Override public int addNatPmpMapping( final PortMappingProtocol arg0, int arg1, int arg2, PortMapListener arg3) { return -1; } }; } final UpnpService upnpService = new Upnp(); this.client.set(P2P.newXmppP2PHttpClient("shoot", natPmpService, upnpService, new InetSocketAddress(LanternHub.settings().getServerPort()), LanternUtils.newTlsSocketFactory(), LanternUtils.newTlsServerSocketFactory(), //SocketFactory.getDefault(), ServerSocketFactory.getDefault(), plainTextProxyRelayAddress, false)); this.client.get().addConnectionListener(new P2PConnectionListener() { @Override public void onConnectivityEvent(final P2PConnectionEvent event) { LOG.info("Got connectivity event: {}", event); LanternHub.asyncEventBus().post(event); } }); // This is a global, backup listener added to the client. We might // get notifications of messages twice in some cases, but that's // better than the alternative of sometimes not being notified // at all. LOG.info("Adding message listener..."); this.client.get().addMessageListener(typedListener); if (this.proxies.isEmpty()) { connectivityEvent(ConnectivityStatus.CONNECTING); } LanternHub.eventBus().post( new GoogleTalkStateEvent(GoogleTalkState.LOGGING_IN)); final String id; if (LanternHub.settings().isGetMode()) { LOG.info("Setting ID for get mode..."); id = "gmail."; } else { LOG.info("Setting ID for give mode"); id = LanternConstants.UNCENSORED_ID; } try { this.client.get().login(email, pwd, id); LanternHub.eventBus().post( new GoogleTalkStateEvent(GoogleTalkState.LOGGED_IN)); } catch (final IOException e) { if (this.proxies.isEmpty()) { connectivityEvent(ConnectivityStatus.DISCONNECTED); } LanternHub.eventBus().post( new GoogleTalkStateEvent(GoogleTalkState.LOGIN_FAILED)); LanternHub.settings().setPasswordSaved(false); LanternHub.settings().setStoredPassword(""); LanternHub.settings().setPassword(""); throw e; } catch (final CredentialException e) { if (this.proxies.isEmpty()) { connectivityEvent(ConnectivityStatus.DISCONNECTED); } LanternHub.eventBus().post( new GoogleTalkStateEvent(GoogleTalkState.LOGIN_FAILED)); throw e; } // Note we don't consider ourselves connected in get mode until we // actually get proxies to work with. final XMPPConnection connection = this.client.get().getXmppConnection(); final Collection<InetSocketAddress> googleStunServers = XmppUtils.googleStunServers(connection); StunServerRepository.setStunServers(googleStunServers); LanternHub.settings().setStunServers( new HashSet<String>(toStringServers(googleStunServers))); // Make sure all connections between us and the server are stored // OTR. LanternUtils.activateOtr(connection); LOG.info("Connection ID: {}", connection.getConnectionID()); // Here we handle allowing the server to subscribe to our presence. connection.addPacketListener(new PacketListener() { @Override public void processPacket(final Packet pack) { final Presence pres = (Presence) pack; LOG.debug("Processing packet!! {}", pres); final String from = pres.getFrom(); LOG.debug("Responding to presence from {} and to {}", from, pack.getTo()); final Type type = pres.getType(); // Allow subscription requests from the lantern bot. if (from.startsWith("lanternctrl@") && from.endsWith("lanternctrl.appspotchat.com")) { if (type == Type.subscribe) { final Presence packet = new Presence(Presence.Type.subscribed); packet.setTo(from); packet.setFrom(pack.getTo()); connection.sendPacket(packet); } else { LOG.info("Non-subscribed packet from hub? {}", pres.toXML()); } } else { switch (type) { case available: return; case error: LOG.warn("Got error packet!! {}", pack.toXML()); return; case subscribe: LOG.info("Adding subscription request from: {}", from); // If we get a subscription request from someone // already on our roster, auto-accept it. if (roster.autoAcceptSubscription(from)) { subscribed(from); } roster.addIncomingSubscriptionRequest(from); break; case subscribed: break; case unavailable: return; case unsubscribe: LOG.info("Removing subscription request from: {}",from); roster.removeIncomingSubscriptionRequest(from); return; case unsubscribed: break; } } } }, new PacketFilter() { @Override public boolean accept(final Packet packet) { if(packet instanceof Presence) { return true; } else { LOG.debug("Not a presence packet: {}", packet.toXML()); } return false; } }); gTalkSharedStatus(); updatePresence(); } private Set<String> toStringServers( final Collection<InetSocketAddress> googleStunServers) { final Set<String> strings = new HashSet<String>(); for (final InetSocketAddress isa : googleStunServers) { strings.add(isa.getHostName()+":"+isa.getPort()); } return strings; } private void connectivityEvent(final ConnectivityStatus cs) { if (LanternHub.settings().isGetMode()) { LanternHub.eventBus().post( new ConnectivityStatusChangeEvent(cs)); } else { LOG.info("Ignoring connectivity event in give mode.."); } } @Override public void clearProxies() { this.proxies.clear(); this.proxySet.clear(); this.peerProxySet.clear(); this.laeProxySet.clear(); this.laeProxies.clear(); } @Override public void disconnect() { if (this.client.get() == null) { LOG.info("Not disconnecting since we're not yet connected"); return; } LOG.info("Disconnecting!!"); lastJson = ""; LanternHub.eventBus().post( new GoogleTalkStateEvent(GoogleTalkState.LOGGING_OUT)); this.client.get().logout(); this.client.set(null); if (this.proxies.isEmpty()) { connectivityEvent(ConnectivityStatus.DISCONNECTED); } LanternHub.eventBus().post( new GoogleTalkStateEvent(GoogleTalkState.LOGGED_OUT)); peerProxySet.clear(); } private void processLanternHubMessage(final Message msg) { LOG.debug("Lantern controlling agent response"); this.hubAddress = msg.getFrom(); LOG.debug("Set hub address to: {}", hubAddress); final String body = msg.getBody(); LOG.debug("Body: {}", body); final Object obj = JSONValue.parse(body); final JSONObject json = (JSONObject) obj; final JSONArray servers = (JSONArray) json.get(LanternConstants.SERVERS); final Long delay = (Long) json.get(LanternConstants.UPDATE_TIME); LOG.debug("Server sent delay of: "+delay); if (delay != null) { final long now = System.currentTimeMillis(); final long elapsed = now - lastInfoMessageScheduled; if (elapsed > 10000 && delay != 0L) { lastInfoMessageScheduled = now; updateTimer.schedule(new TimerTask() { @Override public void run() { updatePresence(); } }, delay); LOG.debug("Scheduled next info request in {} milliseconds", delay); } else { LOG.debug("Ignoring duplicate info request scheduling- "+ "scheduled request {} milliseconds ago.", elapsed); } } if (servers == null) { LOG.debug("No servers in message"); } else { final Iterator<String> iter = servers.iterator(); while (iter.hasNext()) { final String server = iter.next(); addProxy(server); } } // This is really a JSONObject, but that itself is a map. final JSONObject update = (JSONObject) json.get(LanternConstants.UPDATE_KEY); if (update != null) { LOG.info("About to propagate update..."); LanternHub.display().asyncExec (new Runnable () { @Override public void run () { final Map<String, Object> event = new HashMap<String, Object>(); event.putAll(update); LanternHub.eventBus().post(new UpdateEvent(event)); } }); } final Long invites = (Long) json.get(LanternConstants.INVITES_KEY); if (invites != null) { LOG.info("Setting invites to: {}", invites); LanternHub.settings().setInvites(invites.intValue()); } } private void gTalkSharedStatus() { // This is for Google Talk compatibility. Surprising, all we need to // do is grab our Google Talk shared status, signifying support for // their protocol, and then we don't interfere with GChat visibility. final Packet status = XmppUtils.getSharedStatus( this.client.get().getXmppConnection()); LOG.info("Status:\n{}", status.toXML()); } private String askForEmail() { try { System.out.print("Please enter your gmail e-mail, as in johndoe@gmail.com: "); return LanternUtils.readLineCLI(); } catch (final IOException e) { final String msg = "IO error trying to read your email address!"; System.out.println(msg); LOG.error(msg, e); throw new IllegalStateException(msg, e); } } private String askForPassword() { try { System.out.print("Please enter your gmail password: "); return new String(LanternUtils.readPasswordCLI()); } catch (IOException e) { final String msg = "IO error trying to read your email address!"; System.out.println(msg); LOG.error(msg, e); throw new IllegalStateException(msg, e); } } /** * Updates the user's presence. We also include any stats updates in this * message. Note that periodic presence updates are also used on the server * side to verify which clients are actually available. * * We in part send presence updates instead of typical chat messages to * get around these messages showing up in the user's gchat window. */ private void updatePresence() { if (!isLoggedIn()) { LOG.info("Not updating presence when we're not connected"); return; } final XMPPConnection conn = this.client.get().getXmppConnection(); LOG.info("Sending presence available"); // OK, this is bizarre. For whatever reason, we **have** to send the // following packet in order to get presence events from our peers. // DO NOT REMOVE THIS MESSAGE!! See XMPP spec. final Presence pres = new Presence(Presence.Type.available); conn.sendPacket(pres); final Presence forHub = new Presence(Presence.Type.available); forHub.setTo(LanternConstants.LANTERN_JID); //if (!LanternHub.settings().isGetMode()) { final String str = LanternUtils.jsonify(LanternHub.statsTracker()); LOG.debug("Reporting data: {}", str); if (!this.lastJson.equals(str)) { this.lastJson = str; forHub.setProperty("stats", str); LanternHub.statsTracker().resetCumulativeStats(); } else { LOG.info("No new stats to report"); } //} else { // LOG.info("Not reporting any stats in get mode"); conn.sendPacket(forHub); } /* private void sendInfoRequest() { // Send an "info" message to gather proxy data. LOG.info("Sending INFO request"); final Message msg = new Message(); msg.setType(Type.chat); //msg.setType(Type.normal); msg.setTo(LanternConstants.LANTERN_JID); msg.setFrom(this.client.getXmppConnection().getUser()); final JSONObject json = new JSONObject(); final StatsTracker statsTracker = LanternHub.statsTracker(); json.put(LanternConstants.COUNTRY_CODE, CensoredUtils.countryCode()); json.put(LanternConstants.BYTES_PROXIED, statsTracker.getTotalBytesProxied()); json.put(LanternConstants.DIRECT_BYTES, statsTracker.getDirectBytes()); json.put(LanternConstants.REQUESTS_PROXIED, statsTracker.getTotalProxiedRequests()); json.put(LanternConstants.DIRECT_REQUESTS, statsTracker.getDirectRequests()); json.put(LanternConstants.WHITELIST_ADDITIONS, LanternUtils.toJsonArray(Whitelist.getAdditions())); json.put(LanternConstants.WHITELIST_REMOVALS, LanternUtils.toJsonArray(Whitelist.getRemovals())); json.put(LanternConstants.VERSION_KEY, LanternConstants.VERSION); final String str = json.toJSONString(); LOG.info("Reporting data: {}", str); msg.setBody(str); this.client.getXmppConnection().sendPacket(msg); Whitelist.whitelistReported(); //statsTracker.clear(); } */ @Override public void addOrRemovePeer(final Presence p, final String from) { LOG.info("Processing peer: {}", from); final URI uri; try { uri = new URI(from); } catch (final URISyntaxException e) { LOG.error("Could not create URI from: {}", from); return; } if (p.isAvailable()) { LOG.info("Processing available peer"); // OK, we just request a certificate every time we get a present // peer. If we get a response, this peer will be added to active // peer URIs. sendAndRequestCert(uri); } else { LOG.info("Removing JID for peer '"+from); removePeer(uri); } } private void sendErrorMessage(final InetSocketAddress isa, final String message) { final Message msg = new Message(); msg.setProperty(P2PConstants.MESSAGE_TYPE, XmppMessageConstants.ERROR_TYPE); final String errorMessage = "Error: "+message+" with host: "+isa; msg.setProperty(XmppMessageConstants.MESSAGE, errorMessage); this.client.get().getXmppConnection().sendPacket(msg); } private void processTypedMessage(final Message msg, final Integer type) { final String from = msg.getFrom(); LOG.info("Processing typed message from {}", from); switch (type) { case (XmppMessageConstants.INFO_REQUEST_TYPE): LOG.info("Handling INFO request from {}", from); processInfoData(msg); sendInfoResponse(from); break; case (XmppMessageConstants.INFO_RESPONSE_TYPE): LOG.info("Handling INFO response from {}", from); processInfoData(msg); break; default: LOG.warn("Did not understand type: "+type); break; } } private void sendInfoResponse(final String from) { final Message msg = new Message(); // The from becomes the to when we're responding. msg.setTo(from); msg.setProperty(P2PConstants.MESSAGE_TYPE, XmppMessageConstants.INFO_RESPONSE_TYPE); msg.setProperty(P2PConstants.MAC, LanternUtils.getMacAddress()); msg.setProperty(P2PConstants.CERT, LanternHub.getKeyStoreManager().getBase64Cert()); this.client.get().getXmppConnection().sendPacket(msg); } private void processInfoData(final Message msg) { LOG.info("Processing INFO data from request or response."); final URI uri; try { uri = new URI(msg.getFrom()); } catch (final URISyntaxException e) { LOG.error("Could not create URI from: {}", msg.getFrom()); return; } final String mac = (String) msg.getProperty(P2PConstants.MAC); final String base64Cert = (String) msg.getProperty(P2PConstants.CERT); LOG.info("Base 64 cert: {}", base64Cert); if (StringUtils.isNotBlank(base64Cert)) { LOG.info("Got certificate:\n"+ new String(Base64.decodeBase64(base64Cert))); try { // Add the peer if we're able to add the cert. LanternHub.getKeyStoreManager().addBase64Cert(mac, base64Cert); if (LanternHub.settings().isAutoConnectToPeers()) { final String email = XmppUtils.jidToUser(msg.getFrom()); if (this.roster.isFullyOnRoster(email)) { LanternHub.trustedPeerProxyManager().onPeer(uri); } else { LanternHub.anonymousPeerProxyManager().onPeer(uri); } /* if (LanternHub.getTrustedContactsManager().isTrusted(msg)) { LanternHub.trustedPeerProxyManager().onPeer(uri); } else { LanternHub.anonymousPeerProxyManager().onPeer(uri); } */ } } catch (final IOException e) { LOG.error("Could not add cert??", e); } } else { LOG.error("No cert for peer?"); } } private void addProxy(final String cur) { LOG.info("Considering proxy: {}", cur); if (cur.contains("appspot")) { addLaeProxy(cur); return; } if (!cur.contains("@")) { addGeneralProxy(cur); return; } if (!isLoggedIn()) { LOG.info("Not connected -- ignoring proxy: {}", cur); return; } final String jid = this.client.get().getXmppConnection().getUser().trim(); final String emailId = XmppUtils.jidToUser(jid); LOG.info("We are: {}", jid); LOG.info("Service name: {}", this.client.get().getXmppConnection().getServiceName()); if (jid.equals(cur.trim())) { LOG.info("Not adding ourselves as a proxy!!"); return; } if (cur.startsWith(emailId+"/")) { try { addPeerProxy(new URI(cur)); } catch (final URISyntaxException e) { LOG.error("Error with proxy URI", e); } } else if (cur.contains("@")) { try { addPeerProxy(new URI(cur)); } catch (final URISyntaxException e) { LOG.error("Error with proxy URI", e); } } } private void addPeerProxy(final URI peerUri) { LOG.info("Considering peer proxy"); synchronized (peerProxySet) { // We purely do this to keep track of which peers we've attempted // to establish connections to. This is to avoid exchanging certs // multiple times. // TODO: I believe this excludes exchanging keys with peers who // are on multiple machines when the peer URI is a general JID and // not an instance JID. if (!peerProxySet.contains(peerUri)) { LOG.info("Actually adding peer proxy: {}", peerUri); peerProxySet.add(peerUri); sendAndRequestCert(peerUri); } else { LOG.info("We already know about the peer proxy"); } } } private void sendAndRequestCert(final URI cur) { LOG.info("Requesting cert from {}", cur); final Message msg = new Message(); msg.setProperty(P2PConstants.MESSAGE_TYPE, XmppMessageConstants.INFO_REQUEST_TYPE); msg.setTo(cur.toASCIIString()); // Set our certificate in the request as well -- we want to make // extra sure these get through! msg.setProperty(P2PConstants.MAC, LanternUtils.getMacAddress()); msg.setProperty(P2PConstants.CERT, LanternHub.getKeyStoreManager().getBase64Cert()); this.client.get().getXmppConnection().sendPacket(msg); } private void addLaeProxy(final String cur) { LOG.info("Adding LAE proxy"); addProxyWithChecks(this.laeProxySet, this.laeProxies, new ProxyHolder(cur, new InetSocketAddress(cur, 443)), cur); } private void addGeneralProxy(final String cur) { final String hostname = StringUtils.substringBefore(cur, ":"); final int port = Integer.parseInt(StringUtils.substringAfter(cur, ":")); final InetSocketAddress isa = new InetSocketAddress(hostname, port); addProxyWithChecks(proxySet, proxies, new ProxyHolder(hostname, isa), cur); } private void addProxyWithChecks(final Set<ProxyHolder> set, final Queue<ProxyHolder> queue, final ProxyHolder ph, final String fullProxyString) { if (set.contains(ph)) { LOG.info("We already know about proxy "+ph+" in {}", set); // Send the event again in case we've somehow gotten into the // wrong state. LOG.info("Dispatching CONNECTED event"); connectivityEvent(ConnectivityStatus.CONNECTED); return; } final Socket sock = new Socket(); try { sock.connect(ph.isa, 60*1000); LOG.info("Dispatching CONNECTED event"); connectivityEvent(ConnectivityStatus.CONNECTED); // This is a little odd because the proxy could have originally // come from the settings themselves, but it'll remove duplicates, // so no harm done. LanternHub.settings().addProxy(fullProxyString); synchronized (set) { if (!set.contains(ph)) { set.add(ph); queue.add(ph); LOG.info("Queue is now: {}", queue); } } } catch (final IOException e) { LOG.error("Could not connect to: {}", ph); sendErrorMessage(ph.isa, e.getMessage()); onCouldNotConnect(ph.isa); LanternHub.settings().removeProxy(fullProxyString); } finally { IOUtils.closeQuietly(sock); } } @Override public void onCouldNotConnect(final InetSocketAddress proxyAddress) { // This can happen in several scenarios. First, it can happen if you've // actually disconnected from the internet. Second, it can happen if // the proxy is blocked. Third, it can happen when the proxy is simply // down for some reason. LOG.info("COULD NOT CONNECT TO STANDARD PROXY!! Proxy address: {}", proxyAddress); // For now we assume this is because we've lost our connection. //onCouldNotConnect(new ProxyHolder(proxyAddress.getHostName(), proxyAddress), // this.proxySet, this.proxies); } @Override public void onCouldNotConnectToLae(final InetSocketAddress proxyAddress) { LOG.info("COULD NOT CONNECT TO LAE PROXY!! Proxy address: {}", proxyAddress); // For now we assume this is because we've lost our connection. //onCouldNotConnect(new ProxyHolder(proxyAddress.getHostName(), proxyAddress), // this.laeProxySet, this.laeProxies); } private void onCouldNotConnect(final ProxyHolder proxyAddress, final Set<ProxyHolder> set, final Queue<ProxyHolder> queue){ LOG.info("COULD NOT CONNECT!! Proxy address: {}", proxyAddress); synchronized (this.proxySet) { set.remove(proxyAddress); queue.remove(proxyAddress); } } @Override public void onCouldNotConnectToPeer(final URI peerUri) { removePeer(peerUri); } @Override public void onError(final URI peerUri) { removePeer(peerUri); } private void removePeer(final URI uri) { // We always remove from both since their trusted status could have // changed removePeerUri(uri); removeAnonymousPeerUri(uri); //if (LanternHub.getTrustedContactsManager().isJidTrusted(uri.toASCIIString())) { LanternHub.trustedPeerProxyManager().removePeer(uri); //} else { // LanternHub.anonymousPeerProxyManager().removePeer(uri); } private void removePeerUri(final URI peerUri) { LOG.info("Removing peer with URI: {}", peerUri); //remove(peerUri, this.establishedPeerProxies); } private void removeAnonymousPeerUri(final URI peerUri) { LOG.info("Removing anonymous peer with URI: {}", peerUri); //remove(peerUri, this.establishedAnonymousProxies); } private void remove(final URI peerUri, final Queue<URI> queue) { LOG.info("Removing peer with URI: {}", peerUri); queue.remove(peerUri); } @Override public InetSocketAddress getLaeProxy() { return getProxy(this.laeProxies); } @Override public InetSocketAddress getProxy() { return getProxy(this.proxies); } @Override public PeerProxyManager getAnonymousPeerProxyManager() { return LanternHub.anonymousPeerProxyManager(); } @Override public PeerProxyManager getTrustedPeerProxyManager() { return LanternHub.trustedPeerProxyManager(); } private InetSocketAddress getProxy(final Queue<ProxyHolder> queue) { synchronized (queue) { if (queue.isEmpty()) { LOG.info("No proxy addresses"); return null; } final ProxyHolder proxy = queue.remove(); queue.add(proxy); LOG.info("FIFO queue is now: {}", queue); return proxy.isa; } } @Override public XmppP2PClient getP2PClient() { return client.get(); } private static final class ProxyHolder { private final String id; private final InetSocketAddress isa; private ProxyHolder(final String id, final InetSocketAddress isa) { this.id = id; this.isa = isa; } @Override public String toString() { return "ProxyHolder [isa=" + isa + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((isa == null) ? 0 : isa.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProxyHolder other = (ProxyHolder) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (isa == null) { if (other.isa != null) return false; } else if (!isa.equals(other.isa)) return false; return true; } } @Override public boolean isLoggedIn() { if (this.client.get() == null) { return false; } final XMPPConnection conn = client.get().getXmppConnection(); if (conn == null) { return false; } return conn.isAuthenticated(); } @Override public void sendInvite(final String email) { LOG.info("Sending invite"); if (StringUtils.isBlank(this.hubAddress)) { LOG.error("Blank hub address when sending invite?"); return; } final Set<String> invited = LanternHub.settings().getInvited(); if (invited.contains(email)) { LOG.info("Already invited"); return; } final Presence pres = new Presence(Presence.Type.available); pres.setTo(LanternConstants.LANTERN_JID); pres.setProperty(LanternConstants.INVITE_KEY, email); final XMPPConnection conn = this.client.get().getXmppConnection(); conn.sendPacket(pres); invited.add(email); final Runnable runner = new Runnable() { @Override public void run() { conn.sendPacket(pres); } }; final Thread t = new Thread(runner, "Invite-Thread"); t.setDaemon(true); t.start(); LanternHub.settings().setInvites(LanternHub.settings().getInvites()-1); LanternHub.settingsIo().write(); addToRoster(email); } @Override public void subscribe(final String jid) { LOG.info("Sending subscribe message to: {}", jid); sendTypedPacket(jid, Presence.Type.subscribe); } @Override public void subscribed(final String jid) { LOG.info("Sending subscribe message to: {}", jid); sendTypedPacket(jid, Presence.Type.subscribed); roster.removeIncomingSubscriptionRequest(jid); } @Override public void unsubscribe(final String jid) { LOG.info("Sending unsubscribe message to: {}", jid); sendTypedPacket(jid, Presence.Type.unsubscribe); } @Override public void unsubscribed(final String jid) { LOG.info("Sending unsubscribed message to: {}", jid); sendTypedPacket(jid, Presence.Type.unsubscribed); roster.removeIncomingSubscriptionRequest(jid); } private void sendTypedPacket(final String jid, final Type type) { final Presence packet = new Presence(type); packet.setTo(jid); final XMPPConnection conn = this.client.get().getXmppConnection(); //packet.setFrom(XmppUtils.jidToUser(conn)); //packet.setFrom(conn.getUser()); conn.sendPacket(packet); } @Override public void addToRoster(final String email) { // If the user is not already on our roster, we want to make sure to // send them an invite. If the e-mail address specified does not // correspond with a Jabber ID, then we're out of luck. If it does, // then this will send the roster invite. final XMPPConnection conn = this.client.get().getXmppConnection(); final Roster rost = conn.getRoster(); final RosterEntry entry = rost.getEntry(email); if (entry == null) { LOG.info("Inviting user to join roster: {}", email); try { // Note this also sends a subscription request!! rost.createEntry(email, StringUtils.substringBefore(email, "@"), new String[]{}); } catch (final XMPPException e) { LOG.error("Could not create entry?", e); } } } @Override public void removeFromRoster(final String email) { final XMPPConnection conn = this.client.get().getXmppConnection(); final Roster rost = conn.getRoster(); final RosterEntry entry = rost.getEntry(email); if (entry != null) { LOG.info("Removing user from roster: {}", email); try { rost.removeEntry(entry); } catch (final XMPPException e) { LOG.error("Could not create entry?", e); } } } private final Object rosterLock = new Object(); /** * This is primarily here because the frontend can request the roster * before we have it. We block until the roster comes in. */ private void waitForRoster() { synchronized (rosterLock) { while(!this.roster.populated()) { try { rosterLock.wait(40000); } catch (final InterruptedException e) { } } } } @Override public org.lantern.Roster getRoster() { if (this.roster == null) { waitForRoster(); } return this.roster; } @Override public void resetRoster() { this.roster.reset();; } @Override public String getLastUserName() { return lastUserName; } @Override public String getLastPass() { return lastPass; } private void setupJmx() { final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { final Class<? extends Object> clazz = getClass(); final String pack = clazz.getPackage().getName(); final String oName = pack+":type="+clazz.getSimpleName()+"-"+clazz.getSimpleName(); LOG.info("Registering MBean with name: {}", oName); final ObjectName mxBeanName = new ObjectName(oName); if(!mbs.isRegistered(mxBeanName)) { mbs.registerMBean(this, mxBeanName); } } catch (final MalformedObjectNameException e) { LOG.error("Could not set up JMX", e); } catch (final InstanceAlreadyExistsException e) { LOG.error("Could not set up JMX", e); } catch (final MBeanRegistrationException e) { LOG.error("Could not set up JMX", e); } catch (final NotCompliantMBeanException e) { LOG.error("Could not set up JMX", e); } } }
package org.lantern.http; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.cometd.server.CometdServlet; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.servlets.CrossOriginFilter; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.lantern.BayeuxInitializer; import org.lantern.LanternConstants; import org.lantern.LanternService; import org.lantern.Proxifier; import org.lantern.state.Model; import org.lantern.state.StaticSettings; import org.lantern.state.SyncService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Singleton; /** * Launcher and secure path handler for Jetty. */ @Singleton public class JettyLauncher implements LanternService { private final Logger log = LoggerFactory.getLogger(getClass()); private final Server server = new Server(); private final GoogleOauth2RedirectServlet redirectServlet; private final SyncService syncer; private final InteractionServlet interactionServlet; private final Model model; private final PhotoServlet photoServlet; @Inject public JettyLauncher(final SyncService syncer, final GoogleOauth2RedirectServlet redirectServlet, final InteractionServlet interactionServlet, final Model model, final PhotoServlet photoServlet) { this.syncer = syncer; this.redirectServlet = redirectServlet; this.interactionServlet = interactionServlet; this.model = model; this.photoServlet = photoServlet; } @Override public void start() { start(StaticSettings.getApiPort()); } public void start(final int port) { final QueuedThreadPool qtp = new QueuedThreadPool(); qtp.setMinThreads(5); qtp.setMaxThreads(200); qtp.setName("Lantern-Jetty-Thread"); qtp.setDaemon(true); server.setThreadPool(qtp); final String apiName = "Lantern-API"; final ContextHandlerCollection contexts = new ContextHandlerCollection(); String prefix = StaticSettings.getPrefix(); final ServletContextHandler contextHandler = newContext(prefix, apiName); //final ServletContextHandler api = newContext(secureBase, apiName); contexts.addHandler(contextHandler); //contextHandler.setResourceBase(this.resourceBaseFile.toString()); final String resourceBase; final String app = "./lantern-ui/app"; final File appFile = new File(app); if (appFile.isDirectory()) { resourceBase = app; } else { resourceBase = "./lantern-ui"; } contextHandler.setResourceBase(resourceBase); server.setHandler(contexts); server.setStopAtShutdown(true); final SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(port); connector.setMaxIdleTime(60 * 1000); connector.setLowResourcesMaxIdleTime(30 * 1000); connector.setLowResourcesConnections(2000); connector.setAcceptQueueSize(5000); //connector.setThreadPool(new QueuedThreadPool(20)); if (this.model.getSettings().isBindToLocalhost()) { log.info("Binding to localhost"); connector.setHost("127.0.0.1"); } else { log.info("Binding to any address"); } connector.setName(apiName); this.server.setConnectors(new Connector[]{connector}); final CometdServlet cometdServlet = new CometdServlet(); //final ServletConfig config = new ServletConfig //cometdServlet.init(config); final ServletHolder cometd = new ServletHolder(cometdServlet); cometd.setInitParameter("jsonContext", "org.lantern.SettingsJSONContextServer"); //cometd.setInitParameter("transports", // "org.cometd.websocket.server.WebSocketTransport"); cometd.setInitOrder(1); contextHandler.addFilter(filterHolder, secureBase + "/photo/*", FilterMapping.REQUEST); */ } //new SyncService(new SwtJavaScriptSyncStrategy()); final Thread serve = new Thread(new Runnable() { @Override public void run() { try { server.start(); server.join(); } catch (final Exception e) { log.error("Exception on HTTP server"); } } }, "HTTP-Server-Thread"); serve.setDaemon(true); serve.start(); } private String apiPath() {
package io.cfp.controller; import com.fasterxml.jackson.databind.ObjectMapper; import io.cfp.dto.FullCalendar; import io.cfp.dto.TalkUser; import io.cfp.dto.user.Schedule; import io.cfp.dto.user.UserProfil; import io.cfp.entity.Event; import io.cfp.entity.Role; import io.cfp.entity.Room; import io.cfp.entity.Talk; import io.cfp.repository.RoomRepo; import io.cfp.repository.TalkRepo; import io.cfp.service.TalkUserService; import io.cfp.service.email.EmailingService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; @RestController @RequestMapping(value = { "/v0/schedule", "/api/schedule" }, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public class ScheduleController { private static final Logger LOG = LoggerFactory.getLogger(ScheduleController.class); private final TalkUserService talkUserService; private final TalkRepo talks; private final RoomRepo rooms; private final EmailingService emailingService; @Autowired public ScheduleController(TalkUserService talkUserService, TalkRepo talks, RoomRepo rooms, EmailingService emailingService) { super(); this.talkUserService = talkUserService; this.talks = talks; this.rooms = rooms; this.emailingService = emailingService; } @RequestMapping(method = RequestMethod.GET) public List<Schedule> getSchedule() { final List<Talk> all = talks.findByEventIdAndStatesFetch(Event.current(), Collections.singleton(Talk.State.ACCEPTED)); return all.stream(). filter(t -> t.getDate() != null) .map(t -> { Schedule schedule = new Schedule(t.getId(), t.getName(), t.getDescription()); // speakers String spreakers = t.getUser().getFirstname() + " " + t.getUser().getLastname(); if (t.getCospeakers() != null) { spreakers += ", " + t.getCospeakers().stream().map(c -> c.getFirstname() + " " + c.getLastname()).collect(Collectors.joining(", ")); } schedule.setSpeakers(spreakers); schedule.setEventType(t.getTrack().getLibelle()); schedule.setFormat(t.getFormat().getName()); schedule.setEventStart(DateTimeFormatter.ISO_INSTANT.format(t.getDate().toInstant())); schedule.setEventEnd(DateTimeFormatter.ISO_INSTANT.format(t.getDate().toInstant().plus(t.getDuree(), ChronoUnit.MINUTES))); schedule.setVenue(t.getRoom() != null ? t.getRoom().getName() : "TBD"); schedule.setVenueId(t.getRoom() != null ? String.valueOf(t.getRoom().getId()) : null); return schedule; }).collect(toList()); } @RequestMapping(value = "fullcalendar", method = RequestMethod.GET) public FullCalendar getFullCalendar() { final List<Room> roomList = rooms.findByEventId(Event.current()); final List<Talk> all = talks.findByEventIdAndStatesFetch(Event.current(), Collections.singleton(Talk.State.ACCEPTED)); return new FullCalendar(all, roomList); } @RequestMapping(value = "fullcalendar", method = RequestMethod.PUT) public void getFullCalendar(FullCalendar calendar) { calendar.getEvents().forEach( e -> { talkUserService.updateConfirmedTalk( Integer.parseInt(e.getId()), LocalDateTime.parse(e.getStart(), DateTimeFormatter.ISO_OFFSET_DATE_TIME), e.getResourceId()); }); } /** * Get all All talks. * * @return Confirmed talks in "LikeBox" format. */ @RequestMapping(value = "/confirmed", method = RequestMethod.GET) @Secured(Role.ADMIN) public List<Schedule> getConfirmedScheduleList() { List<TalkUser> talkUserList = talkUserService.findAll(Talk.State.CONFIRMED); return getSchedules(talkUserList); } /** * Get all ACCEPTED talks'speakers . * * @return Speakers Set */ @RequestMapping(value = "/accepted/speakers", method = RequestMethod.GET) @Secured(Role.ADMIN) public Set<UserProfil> getSpeakerList() { List<TalkUser> talkUserList = talkUserService.findAll(Talk.State.ACCEPTED); return talkUserList.stream().map(t -> t.getSpeaker()).collect(toSet()); } /** * Get all ACCEPTED talks. * * @return Accepted talks in "LikeBox" format. */ @RequestMapping(value = "/accepted", method = RequestMethod.GET) @Secured(Role.ADMIN) public List<Schedule> getScheduleList() { List<TalkUser> talkUserList = talkUserService.findAll(Talk.State.ACCEPTED); return getSchedules(talkUserList); } private List<Schedule> getSchedules(List<TalkUser> talkUserList) { return talkUserList.stream().map(t -> { Schedule schedule = new Schedule(t.getId(), t.getName(), t.getDescription()); // speakers String spreakers = t.getSpeaker().getFirstname() + " " + t.getSpeaker().getLastname(); if (t.getCospeakers() != null) { spreakers += ", " + t.getCospeakers().stream().map(c -> c.getFirstname() + " " + c.getLastname()).collect(Collectors.joining(", ")); } schedule.setSpeakers(spreakers); // event_type schedule.setEventType(t.getTrackLabel()); return schedule; }).collect(toList()); } @RequestMapping(value = "", method = RequestMethod.POST, consumes = {"multipart/form-data", "multipart/mixed"}) @Secured(Role.ADMIN) public ResponseEntity uploadSchedule(@RequestParam("file") MultipartFile file) throws IOException { final Schedule[] schedules = new ObjectMapper().readValue(file.getBytes(), Schedule[].class); for (Schedule talk : schedules) { talkUserService.updateConfirmedTalk(talk.getId(), LocalDateTime.parse(talk.getEventStart(), DateTimeFormatter.ISO_OFFSET_DATE_TIME), talk.getVenueId()); } return new ResponseEntity<>(HttpStatus.OK); } /** * Notify by mails scheduling result. * @param filter , can be "accepted" or "refused", default is "all" * */ @RequestMapping(value = "/notification", method = RequestMethod.POST) @Secured(Role.ADMIN) public void notifyScheduling(@RequestParam(defaultValue = "all", name = "filter") String filter) { switch (filter) { case "refused" : List<Talk> refused = talks.findByEventIdAndStatesFetch(Event.current(), Collections.singleton(Talk.State.REFUSED)); sendRefusedMailsWithTempo(refused); break; case "accepted" : List<Talk> accepted = talks.findByEventIdAndStatesFetch(Event.current(), Collections.singleton(Talk.State.ACCEPTED)); sendAcceptedMailsWithTempo(accepted); break; case "all" : sendAcceptedMailsWithTempo(talks.findByEventIdAndStatesFetch(Event.current(), Collections.singleton(Talk.State.ACCEPTED))); sendRefusedMailsWithTempo(talks.findByEventIdAndStatesFetch(Event.current(), Collections.singleton(Talk.State.REFUSED))); break; } } /** * To help Google Compute Engine we wait 2 s between 2 mails. * @param accepted */ private void sendAcceptedMailsWithTempo(List<Talk> accepted) { accepted.forEach(t -> { try { Thread.sleep(2000); } catch (InterruptedException e) { LOG.warn("Thread Interrupted Exception", e); } emailingService.sendSelectionned(t, t.getUser().getLocale()); } ); } private void sendRefusedMailsWithTempo(List<Talk> refused) { refused.forEach(t -> { try { Thread.sleep(2000); } catch (InterruptedException e) { LOG.warn("Thread Interrupted Exception", e); } emailingService.sendNotSelectionned(t, t.getUser().getLocale()); }); } }
package io.featureflow.client; import org.apache.commons.codec.digest.DigestUtils; import java.util.ArrayList; import java.util.List; public class FeatureControl { String id; String key; //the key which is unique per project and used as the human-readable unique key String environmentId; //the environmentId //String salt; //The salt is used to hash context details (this is in the environment config) TBC int variationsSeed; //The variations seed is a fixed random number that is used in the hashing algorythm boolean enabled; //is this feature enabled? If not then we show the offVariant boolean available; //is the feature available in the environment? boolean deleted; //has this been deleted then ignore in all evaluations List<Rule> rules = new ArrayList<>(); //A list of feature rules which contain rules to target variant splits at particular audiences String offVariantId; // This is served if the feature is toggled off and is the last call but one (the coded in value is the final failover value) boolean inClientApi; //is this in the JS api (for any required logic) List<Variant> variants = new ArrayList<>(); //available variants for this feature public String getKey(){ return this.key; } public String evaluate(FeatureFlowContext context) { //if off then offVariant if(!enabled) { return getVariantById(offVariantId).name; } //if we have rules (we should always have at least one - the default rule for (Rule rule : rules) { if(rule.matches(context)){ //if the rule matches then pass back the variant based on the split evaluation return getVariantById(rule.getEvaluatedVariantId(context.key, variationsSeed)).name; } } return null; //at least the default rule above should have matched, if not, return null to invoke using the failover rule } //helpers public Variant getVariantByName(String name){ for (Variant v: variants) { if(name.equals(v.name)){ return v; } } return null; } public Variant getVariantById(String id){ for (Variant v: variants) { if(v.id.equals(id)){ return v; } } return null; } @Override public String toString() { /*String variants; for (Variant variant : variants) { variants += variant.name + " "; }*/ return "FeatureControl{" + "\n" + " key='" + key + '\'' + "\n" + " environmentId='" + environmentId + '\'' + "\n" + " variationsSeed=" + variationsSeed + "\n" + " enabled=" + enabled + "\n" + " available=" + available + "\n" + " deleted=" + deleted + "\n" + //insert barely readable one-liner here: " rules=" + rules.stream().map(r -> "Rule " + r.getPriority() + ": " + r.getVariantSplits().stream().map(s -> s.getVariantId() + ":" + s.getSplit() +"% ").reduce("", String::concat) + "\n").reduce("", String::concat) + "\n" + " offVariantId=" + offVariantId + "\n" + " inClientApi=" + inClientApi + "\n" + " variants=" + variants.stream().map(v -> v.name +" ").reduce("", String::concat) + "\n" + '}'; } }
package org.myrobotlab.service; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.commons.io.FilenameUtils; import org.myrobotlab.codec.CodecUtils; import org.myrobotlab.framework.Platform; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.framework.Status; import org.myrobotlab.framework.interfaces.Attachable; import org.myrobotlab.inmoov.Utils; import org.myrobotlab.inmoov.Vision; import org.myrobotlab.io.FileIO; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.opencv.OpenCVData; import org.myrobotlab.service.abstracts.AbstractSpeechSynthesis.Voice; import org.myrobotlab.service.data.JoystickData; import org.myrobotlab.service.data.Locale; import org.myrobotlab.service.data.Pin; import org.myrobotlab.service.interfaces.JoystickListener; import org.myrobotlab.service.interfaces.PinArrayControl; import org.myrobotlab.service.interfaces.LocaleProvider; import org.myrobotlab.service.interfaces.ServoControl; import org.myrobotlab.service.interfaces.Simulator; import org.myrobotlab.service.interfaces.SpeechRecognizer; import org.myrobotlab.service.interfaces.SpeechSynthesis; import org.myrobotlab.service.interfaces.TextListener; import org.myrobotlab.service.interfaces.TextPublisher; import org.slf4j.Logger; public class InMoov2 extends Service implements TextListener, TextPublisher, JoystickListener, LocaleProvider { public final static Logger log = LoggerFactory.getLogger(InMoov2.class); public static LinkedHashMap<String, String> lpVars = new LinkedHashMap<String, String>(); // FIXME - why static boolean RobotCanMoveRandom = true; private static final long serialVersionUID = 1L; static String speechRecognizer = "WebkitSpeechRecognition"; /** * This static method returns all the details of the class without it having to * be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(InMoov2.class); meta.addDescription("InMoov2 Service"); meta.addCategory("robot"); meta.sharePeer("mouthControl.mouth", "mouth", "MarySpeech", "shared Speech"); meta.addPeer("eye", "OpenCV", "eye"); meta.addPeer("servomixer", "ServoMixer", "for making gestures"); meta.addPeer("ultraSonicRight", "UltrasonicSensor", "measure distance"); meta.addPeer("ultraSonicLeft", "UltrasonicSensor", "measure distance"); meta.addPeer("pir", "Pir", "infrared sensor"); // the two legacy controllers .. :( meta.addPeer("left", "Arduino", "legacy controller"); meta.addPeer("right", "Arduino", "legacy controller"); meta.addPeer("controller3", "Arduino", "legacy controller"); meta.addPeer("controller4", "Arduino", "legacy controller"); meta.addPeer("htmlFilter", "HtmlFilter", "filter speaking html"); meta.addPeer("brain", "ProgramAB", "brain"); meta.addPeer("simulator", "JMonkeyEngine", "simulator"); meta.addPeer("head", "InMoov2Head", "head"); meta.addPeer("torso", "InMoov2Torso", "torso"); // meta.addPeer("eyelids", "InMoovEyelids", "eyelids"); meta.addPeer("leftArm", "InMoov2Arm", "left arm"); meta.addPeer("leftHand", "InMoov2Hand", "left hand"); meta.addPeer("rightArm", "InMoov2Arm", "right arm"); meta.addPeer("rightHand", "InMoov2Hand", "right hand"); meta.addPeer("mouthControl", "MouthControl", "MouthControl"); // meta.addPeer("imageDisplay", "ImageDisplay", "image display service"); meta.addPeer("mouth", "MarySpeech", "InMoov speech service"); meta.addPeer("ear", speechRecognizer, "InMoov webkit speech recognition service"); meta.addPeer("headTracking", "Tracking", "Head tracking system"); meta.sharePeer("headTracking.opencv", "eye", "OpenCV", "shared head OpenCV"); // meta.sharePeer("headTracking.controller", "left", "Arduino", "shared head // Arduino"); NO !!!! meta.sharePeer("headTracking.x", "head.rothead", "Servo", "shared servo"); meta.sharePeer("headTracking.y", "head.neck", "Servo", "shared servo"); // Global - undecorated by self name meta.addRootPeer("python", "Python", "shared Python service"); // latest - not ready until repo is ready meta.addDependency("fr.inmoov", "inmoov2", null, "zip"); return meta; } /** * This method will load a python file into the python interpreter. */ public static boolean loadFile(String file) { File f = new File(file); Python p = (Python) Runtime.getService("python"); log.info("Loading Python file {}", f.getAbsolutePath()); if (p == null) { log.error("Python instance not found"); return false; } String script = null; try { script = FileIO.toString(f.getAbsolutePath()); } catch (IOException e) { log.error("IO Error loading file : ", e); return false; } // evaluate the scripts in a blocking way. boolean result = p.exec(script, true); if (!result) { log.error("Error while loading file {}", f.getAbsolutePath()); return false; } else { log.debug("Successfully loaded {}", f.getAbsolutePath()); } return true; } public static void main(String[] args) { try { LoggingFactory.init(Level.INFO); Platform.setVirtual(true); // Runtime.main(new String[] { "--install", "InMoov2" }); // Runtime.main(new String[] { "--interactive", "--id", "inmoov", // "--install-dependency","fr.inmoov", "inmoov2", "latest", "zip"}); Runtime.main(new String[] { "--resource-override", "InMoov2=/lhome/grperry/github/mrl.develop/myrobotlab/src/main/resources/resource/InMoov2/resource/InMoov2", "WebGui=/lhome/grperry/github/mrl.develop/myrobotlab/src/main/resources/resource/InMoov2/resource/WebGui", "ProgramAB=/lhome/grperry/github/mrl.develop/myrobotlab/src/main/resources/resource/InMoov2/resource/ProgramAB", "--interactive", "--id", "inmoov" }); String[] langs = java.util.Locale.getISOLanguages(); java.util.Locale[] locales = java.util.Locale.getAvailableLocales(); log.info("{}", locales.length); for (java.util.Locale l : locales) { log.info(" log.info(CodecUtils.toJson(l)); log.info(l.getDisplayLanguage()); log.info(l.getLanguage()); log.info(l.getCountry()); log.info(l.getDisplayCountry()); log.info(CodecUtils.toJson(new Locale(l))); if (l.getLanguage().equals("en")) { log.info("here"); } } InMoov2 i01 = (InMoov2) Runtime.start("i01", "InMoov2"); WebGui webgui = (WebGui) Runtime.create("webgui", "WebGui"); webgui.autoStartBrowser(false); webgui.startService(); boolean done = true; if (done) { return; } i01.startBrain(); i01.startAll("COM3", "COM4"); Runtime.start("python", "Python"); // Runtime.start("log", "Log"); /* * OpenCV cv = (OpenCV) Runtime.start("cv", "OpenCV"); cv.setCameraIndex(2); */ // i01.startSimulator(); /* * Arduino mega = (Arduino) Runtime.start("mega", "Arduino"); * mega.connect("/dev/ttyACM0"); */ } catch (Exception e) { log.error("main threw", e); } } boolean autoStartBrowser = false; transient ProgramAB brain; Set<String> configs = null; String currentConfigurationName = "default"; transient SpeechRecognizer ear; transient OpenCV eye; transient Tracking eyesTracking; // waiting controable threaded gestures we warn user boolean gestureAlreadyStarted = false; // FIXME - what the hell is this for ? Set<String> gestures = new TreeSet<String>(); transient InMoov2Head head; transient Tracking headTracking; transient HtmlFilter htmlFilter; transient UltrasonicSensor ultraSonicRight; transient UltrasonicSensor ultraSonicLeft; transient Pir pir; private PinArrayControl pirArduino; public Integer pirPin = null; // transient ImageDisplay imageDisplay; /** * simple booleans to determine peer state of existence FIXME - should be an * auto-peer variable */ boolean isBrainActivated = false; boolean isEarActivated = false; boolean isEyeActivated = false; boolean isEyeLidsActivated = false; boolean isHeadActivated = false; boolean isLeftArmActivated = false; boolean isLeftHandActivated = false; boolean isMouthActivated = false; boolean isRightArmActivated = false; boolean isRightHandActivated = false; boolean isSimulatorActivated = false; boolean isTorsoActivated = false; boolean isNeopixelActivated = false; boolean isPirActivated = false; boolean isUltraSonicRightActivated = false; boolean isUltraSonicLeftActivated = false; boolean isServoMixerActivated = false; // TODO - refactor into a Simulator interface when more simulators are borgd transient JMonkeyEngine jme; String lastGestureExecuted; Long lastPirActivityTime; transient InMoov2Arm leftArm; // transient LanguagePack languagePack = new LanguagePack(); // transient InMoovEyelids eyelids; eyelids are in the head transient InMoov2Hand leftHand; Locale locale; /** * supported locales */ Map<String, Locale> locales = null; int maxInactivityTimeSeconds = 120; transient SpeechSynthesis mouth; // FIXME ugh - new MouthControl service that uses AudioFile output transient public MouthControl mouthControl; boolean mute = false; transient NeoPixel neopixel; transient ServoMixer servomixer; transient Python python; transient InMoov2Arm rightArm; transient InMoov2Hand rightHand; /** * used to remember/serialize configuration the user's desired speech type */ String speechService = "MarySpeech"; transient InMoov2Torso torso; @Deprecated public Vision vision; // FIXME - remove all direct references // transient private HashMap<String, InMoov2Arm> arms = new HashMap<>(); protected List<Voice> voices = null; protected String voiceSelected; transient WebGui webgui; public InMoov2(String n, String id) { super(n, id); // by default all servos will auto-disable Servo.setAutoDisableDefault(true); locales = Locale.getLocaleMap("en-US", "fr-FR", "es-ES", "de-DE", "nl-NL", "ru-RU", "hi-IN", "it-IT", "fi-FI", "pt-PT"); locale = Runtime.getInstance().getLocale(); python = (Python) startPeer("python"); load(locale.getTag()); // get events of new services and shutdown Runtime r = Runtime.getInstance(); subscribe(r.getName(), "shutdown"); listConfigFiles(); // FIXME - Framework should auto-magically auto-start peers AFTER // construction - unless explicitly told not to // peers to start on construction // imageDisplay = (ImageDisplay) startPeer("imageDisplay"); } @Override /* local strong type - is to be avoided - use name string */ public void addTextListener(TextListener service) { // CORRECT WAY ! - no direct reference - just use the name in a subscription addListener("publishText", service.getName()); } @Override public void attachTextListener(TextListener service) { addListener("publishText", service.getName()); } public void attachTextPublisher(String name) { subscribe(name, "publishText"); } @Override public void attachTextPublisher(TextPublisher service) { subscribe(service.getName(), "publishText"); } public void beginCheckingOnInactivity() { beginCheckingOnInactivity(maxInactivityTimeSeconds); } public void beginCheckingOnInactivity(int maxInactivityTimeSeconds) { this.maxInactivityTimeSeconds = maxInactivityTimeSeconds; // speakBlocking("power down after %s seconds inactivity is on", // this.maxInactivityTimeSeconds); log.info("power down after %s seconds inactivity is on", this.maxInactivityTimeSeconds); addTask("checkInactivity", 5 * 1000, 0, "checkInactivity"); } public long checkInactivity() { // speakBlocking("checking"); long lastActivityTime = getLastActivityTime(); long now = System.currentTimeMillis(); long inactivitySeconds = (now - lastActivityTime) / 1000; if (inactivitySeconds > maxInactivityTimeSeconds) { // speakBlocking("%d seconds have passed without activity", // inactivitySeconds); powerDown(); } else { // speakBlocking("%d seconds have passed without activity", // inactivitySeconds); info("checking checkInactivity - %d seconds have passed without activity", inactivitySeconds); } return lastActivityTime; } public void closeAllImages() { // imageDisplay.closeAll(); log.error("implement webgui.closeAllImages"); } public void cycleGestures() { // if not loaded load - // FIXME - this needs alot of "help" :P // WHY IS THIS DONE ? if (gestures.size() == 0) { loadGestures(); } for (String gesture : gestures) { try { String methodName = gesture.substring(0, gesture.length() - 3); speakBlocking(methodName); log.info("executing gesture {}", methodName); python.eval(methodName + "()"); // wait for finish - or timeout ? } catch (Exception e) { error(e); } } } public void disable() { if (head != null) { head.disable(); } if (rightHand != null) { rightHand.disable(); } if (leftHand != null) { leftHand.disable(); } if (rightArm != null) { rightArm.disable(); } if (leftArm != null) { leftArm.disable(); } if (torso != null) { torso.disable(); } } public void displayFullScreen(String src) { try { // imageDisplay.displayFullScreen(src); log.error("implement webgui.displayFullScreen"); } catch (Exception e) { error("could not display picture %s", src); } } public void enable() { if (head != null) { head.enable(); } if (rightHand != null) { rightHand.enable(); } if (leftHand != null) { leftHand.enable(); } if (rightArm != null) { rightArm.enable(); } if (leftArm != null) { leftArm.enable(); } if (torso != null) { torso.enable(); } } /** * This method will try to launch a python command with error handling */ public String execGesture(String gesture) { lastGestureExecuted = gesture; if (python == null) { log.warn("execGesture : No jython engine..."); return null; } subscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus"); startedGesture(lastGestureExecuted); return python.evalAndWait(gesture); } public void finishedGesture() { finishedGesture("unknown"); } public void finishedGesture(String nameOfGesture) { if (gestureAlreadyStarted) { waitTargetPos(); RobotCanMoveRandom = true; gestureAlreadyStarted = false; log.info("gesture : {} finished...", nameOfGesture); } } public void fullSpeed() { if (head != null) { head.fullSpeed(); } if (rightHand != null) { rightHand.fullSpeed(); } if (leftHand != null) { leftHand.fullSpeed(); } if (rightArm != null) { rightArm.fullSpeed(); } if (leftArm != null) { leftArm.fullSpeed(); } if (torso != null) { torso.fullSpeed(); } } public String get(String param) { if (lpVars.containsKey(param.toUpperCase())) { return lpVars.get(param.toUpperCase()); } return "not yet translated"; } public InMoov2Arm getArm(String side) { if ("left".equals(side)) { return leftArm; } else if ("right".equals(side)) { return rightArm; } else { log.error("can not get arm {}", side); } return null; } public InMoov2Hand getHand(String side) { if ("left".equals(side)) { return leftHand; } else if ("right".equals(side)) { return rightHand; } else { log.error("can not get arm {}", side); } return null; } public InMoov2Head getHead() { return head; } /** * get current language */ public String getLanguage() { return locale.getLanguage(); } /** * finds most recent activity * * @return the timestamp of the last activity time. */ public long getLastActivityTime() { long lastActivityTime = 0; if (leftHand != null) { lastActivityTime = Math.max(lastActivityTime, leftHand.getLastActivityTime()); } if (leftArm != null) { lastActivityTime = Math.max(lastActivityTime, leftArm.getLastActivityTime()); } if (rightHand != null) { lastActivityTime = Math.max(lastActivityTime, rightHand.getLastActivityTime()); } if (rightArm != null) { lastActivityTime = Math.max(lastActivityTime, rightArm.getLastActivityTime()); } if (head != null) { lastActivityTime = Math.max(lastActivityTime, head.getLastActivityTime()); } if (torso != null) { lastActivityTime = Math.max(lastActivityTime, torso.getLastActivityTime()); } if (lastPirActivityTime != null) { lastActivityTime = Math.max(lastActivityTime, lastPirActivityTime); } if (lastActivityTime == 0) { error("invalid activity time - anything connected?"); lastActivityTime = System.currentTimeMillis(); } return lastActivityTime; } public InMoov2Arm getLeftArm() { return leftArm; } public InMoov2Hand getLeftHand() { return leftHand; } @Override public Locale getLocale() { return locale; } @Override public Map<String, Locale> getLocales() { return locales; } public InMoov2Arm getRightArm() { return rightArm; } public InMoov2Hand getRightHand() { return rightHand; } public Simulator getSimulator() { return jme; } public InMoov2Torso getTorso() { return torso; } public void halfSpeed() { if (head != null) { head.setSpeed(25.0, 25.0, 25.0, 25.0, -1.0, 25.0); } if (rightHand != null) { rightHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0); } if (leftHand != null) { leftHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0); } if (rightArm != null) { rightArm.setSpeed(25.0, 25.0, 25.0, 25.0); } if (leftArm != null) { leftArm.setSpeed(25.0, 25.0, 25.0, 25.0); } if (torso != null) { torso.setSpeed(20.0, 20.0, 20.0); } } public boolean isCameraOn() { if (eye != null) { if (eye.isCapturing()) { return true; } } return false; } public boolean isEyeLidsActivated() { return isEyeLidsActivated; } public boolean isHeadActivated() { return isHeadActivated; } public boolean isLeftArmActivated() { return isLeftArmActivated; } public boolean isLeftHandActivated() { return isLeftHandActivated; } public boolean isMute() { return mute; } public boolean isNeopixelActivated() { return isNeopixelActivated; } public boolean isRightArmActivated() { return isRightArmActivated; } public boolean isRightHandActivated() { return isRightHandActivated; } public boolean isTorsoActivated() { return isTorsoActivated; } public boolean isPirActivated() { return isPirActivated; } public boolean isUltraSonicRightActivated() { return isUltraSonicRightActivated; } public boolean isUltraSonicLeftActivated() { return isUltraSonicLeftActivated; } public boolean isServoMixerActivated() { return isServoMixerActivated; } public Set<String> listConfigFiles() { configs = new HashSet<>(); // data list String configDir = getResourceDir() + fs + "config"; File f = new File(configDir); if (!f.exists()) { f.mkdirs(); } String[] files = f.list(); for (String config : files) { configs.add(config); } // data list configDir = getDataDir() + fs + "config"; f = new File(configDir); if (!f.exists()) { f.mkdirs(); } files = f.list(); for (String config : files) { configs.add(config); } return configs; } /* * iterate over each txt files in the directory */ public void load(String locale) { String extension = "lang"; File dir = Utils.makeDirectory(getResourceDir() + File.separator + "system" + File.separator + "languagePack" + File.separator + locale); if (dir.exists()) { lpVars.clear(); for (File f : dir.listFiles()) { if (f.isDirectory()) { continue; } if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) { log.info("Inmoov languagePack load : {}", f.getName()); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8")); for (String line = br.readLine(); line != null; line = br.readLine()) { String[] parts = line.split("::"); if (parts.length > 1) { lpVars.put(parts[0].toUpperCase(), parts[1]); } } } catch (IOException e) { log.error("LanguagePack : {}", e); } } else { log.warn("{} is not a {} file", f.getAbsolutePath(), extension); } } } } // FIXME - what is this for ??? public void loadGestures() { loadGestures(getResourceDir() + fs + "gestures"); } /** * This blocking method will look at all of the .py files in a directory. One by * one it will load the files into the python interpreter. A gesture python file * should contain 1 method definition that is the same as the filename. * * @param directory - the directory that contains the gesture python files. */ public boolean loadGestures(String directory) { speakBlocking(get("STARTINGGESTURES")); // iterate over each of the python files in the directory // and load them into the python interpreter. String extension = "py"; Integer totalLoaded = 0; Integer totalError = 0; File dir = new File(directory); dir.mkdirs(); if (dir.exists()) { for (File f : dir.listFiles()) { if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) { if (loadFile(f.getAbsolutePath()) == true) { totalLoaded += 1; String methodName = f.getName().substring(0, f.getName().length() - 3) + "()"; gestures.add(methodName); } else { error("could not load %s", f.getName()); totalError += 1; } } else { log.info("{} is not a {} file", f.getAbsolutePath(), extension); } } } info("%s Gestures loaded, %s Gestures with error", totalLoaded, totalError); broadcastState(); if (totalError > 0) { speakAlert(get("GESTURE_ERROR")); return false; } return true; } public void moveArm(String which, double bicep, double rotate, double shoulder, double omoplate) { InMoov2Arm arm = getArm(which); if (arm == null) { info("%s arm not started", which); return; } arm.moveTo(bicep, rotate, shoulder, omoplate); } public void moveEyelids(double eyelidleftPos, double eyelidrightPos) { if (head != null) { head.moveEyelidsTo(eyelidleftPos, eyelidrightPos); } else { log.warn("moveEyelids - I have a null head"); } } public void moveEyes(double eyeX, double eyeY) { if (head != null) { head.moveTo(null, null, eyeX, eyeY, null, null); } else { log.warn("moveEyes - I have a null head"); } } public void moveHand(String which, double thumb, double index, double majeure, double ringFinger, double pinky) { moveHand(which, thumb, index, majeure, ringFinger, pinky, null); } public void moveHand(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { InMoov2Hand hand = getHand(which); if (hand == null) { log.warn("{} hand does not exist"); return; } hand.moveTo(thumb, index, majeure, ringFinger, pinky, wrist); } public void moveHead(double neck, double rothead) { moveHead(neck, rothead, null); } public void moveHead(double neck, double rothead, double eyeX, double eyeY, double jaw) { moveHead(neck, rothead, eyeX, eyeY, jaw, null); } public void moveHead(Double neck, Double rothead, Double rollNeck) { moveHead(neck, rothead, null, null, null, rollNeck); } public void moveHead(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) { if (head != null) { head.moveTo(neck, rothead, eyeX, eyeY, jaw, rollNeck); } else { log.error("I have a null head"); } } public void moveHeadBlocking(double neck, double rothead) { moveHeadBlocking(neck, rothead, null); } public void moveHeadBlocking(double neck, double rothead, Double rollNeck) { moveHeadBlocking(neck, rothead, null, null, null, rollNeck); } public void moveHeadBlocking(double neck, double rothead, Double eyeX, Double eyeY, Double jaw) { moveHeadBlocking(neck, rothead, eyeX, eyeY, jaw, null); } public void moveHeadBlocking(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) { if (head != null) { head.moveToBlocking(neck, rothead, eyeX, eyeY, jaw, rollNeck); } else { log.error("I have a null head"); } } public void moveTorso(double topStom, double midStom, double lowStom) { if (torso != null) { torso.moveTo(topStom, midStom, lowStom); } else { log.error("moveTorso - I have a null torso"); } } public void moveTorsoBlocking(double topStom, double midStom, double lowStom) { if (torso != null) { torso.moveToBlocking(topStom, midStom, lowStom); } else { log.error("moveTorsoBlocking - I have a null torso"); } } public void onGestureStatus(Status status) { if (!status.equals(Status.success()) && !status.equals(Status.warn("Python process killed !"))) { error("I cannot execute %s, please check logs", lastGestureExecuted); } finishedGesture(lastGestureExecuted); unsubscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus"); } @Override public void onJoystickInput(JoystickData input) throws Exception { // TODO Auto-generated method stub } public OpenCVData onOpenCVData(OpenCVData data) { return data; } @Override public void onText(String text) { // FIXME - we should be able to "re"-publish text but text is coming from // different sources // some might be coming from the ear - some from the mouth ... - there has // to be a distinction log.info("onText - {}", text); invoke("publishText", text); } // TODO FIX/CHECK this, migrate from python land public void powerDown() { rest(); purgeTasks(); disable(); if (ear != null) { ear.lockOutAllGrammarExcept("power up"); } python.execMethod("power_down"); } // TODO FIX/CHECK this, migrate from python land public void powerUp() { enable(); rest(); if (ear != null) { ear.clearLock(); } beginCheckingOnInactivity(); python.execMethod("power_up"); } /** * all published text from InMoov2 - including ProgramAB */ @Override public String publishText(String text) { return text; } public void releaseService() { try { disable(); releasePeers(); super.releaseService(); } catch (Exception e) { error(e); } } // FIXME NO DIRECT REFERENCES - publishRest --> (onRest) --> rest public void rest() { log.info("InMoov2.rest()"); if (head != null) { head.rest(); } if (rightHand != null) { rightHand.rest(); } if (leftHand != null) { leftHand.rest(); } if (rightArm != null) { rightArm.rest(); } if (leftArm != null) { leftArm.rest(); } if (torso != null) { torso.rest(); } } @Deprecated public void setArmVelocity(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) { InMoov2Arm arm = getArm(which); if (arm == null) { warn("%s hand not started", which); return; } arm.setSpeed(bicep, rotate, shoulder, omoplate); } public void setAutoDisable(Boolean param) { if (head != null) { head.setAutoDisable(param); } if (rightArm != null) { rightArm.setAutoDisable(param); } if (leftArm != null) { leftArm.setAutoDisable(param); } if (leftHand != null) { leftHand.setAutoDisable(param); } if (rightHand != null) { leftHand.setAutoDisable(param); } if (torso != null) { torso.setAutoDisable(param); } /* * if (eyelids != null) { eyelids.setAutoDisable(param); } */ } public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) { setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null); } public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { InMoov2Hand hand = getHand(which); if (hand == null) { warn("%s hand not started", which); return; } hand.setSpeed(thumb, index, majeure, ringFinger, pinky, wrist); } @Deprecated public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) { setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null); } @Deprecated public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, wrist); } public void setHeadSpeed(Double rothead, Double neck) { setHeadSpeed(rothead, neck, null, null, null); } public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) { setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null); } public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) { if (head == null) { warn("setHeadSpeed - head not started"); return; } head.setSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed); } @Deprecated public void setHeadVelocity(Double rothead, Double neck) { setHeadSpeed(rothead, neck, null, null, null, null); } @Deprecated public void setHeadVelocity(Double rothead, Double neck, Double rollNeck) { setHeadSpeed(rothead, neck, null, null, null, rollNeck); } @Deprecated public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) { setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null); } @Deprecated public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) { setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed); } /** * TODO : use system locale set language for InMoov service used by chatbot + * * @param code * @return */ @Deprecated /* use setLocale */ public String setLanguage(String code) { setLocale(code); return code; } @Override public void setLocale(String code) { if (code == null) { log.warn("setLocale null"); return; } // filter of the set of supported locales if (!locales.containsKey(code)) { error("InMooov does not support %s only %s", code, locales.keySet()); return; } locale = new Locale(code); speakBlocking("setting language to %s", locale.getDisplayLanguage()); // attempt to set all other language providers to the same language as me List<String> providers = Runtime.getServiceNamesFromInterface(LocaleProvider.class); for (String provider : providers) { if (!provider.equals(getName())) { log.info("{} setting locale to %s", provider, code); send(provider, "setLocale", code); send(provider, "broadcastState"); } } load(locale.getTag()); } public void setMute(boolean mute) { info("Set mute to %s", mute); this.mute = mute; sendToPeer("mouth", "setMute", mute); broadcastState(); } public void setNeopixelAnimation(String animation, Integer red, Integer green, Integer blue, Integer speed) { if (neopixel != null /* && neopixelArduino != null */) { neopixel.setAnimation(animation, red, green, blue, speed); } else { warn("No Neopixel attached"); } } public String setSpeechType(String speechType) { speechService = speechType; setPeer("mouth", speechType); return speechType; } public void setTorsoSpeed(Double topStom, Double midStom, Double lowStom) { if (torso != null) { torso.setSpeed(topStom, midStom, lowStom); } else { log.warn("setTorsoSpeed - I have no torso"); } } @Deprecated public void setTorsoVelocity(Double topStom, Double midStom, Double lowStom) { if (torso != null) { torso.setVelocity(topStom, midStom, lowStom); } else { log.warn("setTorsoVelocity - I have no torso"); } } /** * overridden setVirtual for InMoov sets "all" services to virtual */ public boolean setVirtual(boolean virtual) { super.setVirtual(virtual); Platform.setVirtual(virtual); return virtual; } public void setVoice(String name) { if (mouth != null) { mouth.setVoice(name); voiceSelected = name; speakBlocking("setting voice to %s", name); } } public void speak(String toSpeak) { sendToPeer("mouth", "speak", toSpeak); } public void speakAlert(String toSpeak) { speakBlocking(get("ALERT")); speakBlocking(toSpeak); } public void speakBlocking(String speak) { speakBlocking(speak, null); } // FIXME - publish text regardless if mouth exists ... public void speakBlocking(String format, Object... args) { if (format == null) { return; } String toSpeak = format; if (args != null) { toSpeak = String.format(format, args); } // FIXME - publish onText when listening invoke("publishText", toSpeak); if (!mute) { // sendToPeer("mouth", "speakBlocking", toSpeak); invokePeer("mouth", "speakBlocking", toSpeak); } } public void startAll() throws Exception { startAll(null, null); } public void startAll(String leftPort, String rightPort) throws Exception { startMouth(); startBrain(); startHeadTracking(); // startEyesTracking(); // startOpenCV(); startEar(); startServos(leftPort, rightPort); // startMouthControl(head.jaw, mouth); speakBlocking("startup sequence completed"); } public ProgramAB startBrain() { try { brain = (ProgramAB) startPeer("brain"); isBrainActivated = true; speakBlocking(get("CHATBOTACTIVATED")); // GOOD EXAMPLE ! - no type, uses name - does a set of subscriptions ! // attachTextPublisher(brain.getName()); /* * not necessary - ear needs to be attached to mouth not brain if (ear != null) * { ear.attachTextListener(brain); } */ brain.attachTextPublisher(ear); // this.attach(brain); FIXME - attach as a TextPublisher - then re-publish // FIXME - deal with language // speakBlocking(get("CHATBOTACTIVATED")); brain.repetitionCount(10); brain.setPath(getResourceDir() + fs + "chatbot"); brain.startSession("default", locale.getTag()); // reset some parameters to default... brain.setPredicate("topic", "default"); brain.setPredicate("questionfirstinit", ""); brain.setPredicate("tmpname", ""); brain.setPredicate("null", ""); // load last user session if (!brain.getPredicate("name").isEmpty()) { if (brain.getPredicate("lastUsername").isEmpty() || brain.getPredicate("lastUsername").equals("unknown")) { brain.setPredicate("lastUsername", brain.getPredicate("name")); } } brain.setPredicate("parameterHowDoYouDo", ""); try { brain.savePredicates(); } catch (IOException e) { log.error("saving predicates threw", e); } // start session based on last recognized person if (!brain.getPredicate("default", "lastUsername").isEmpty() && !brain.getPredicate("default", "lastUsername").equals("unknown")) { brain.startSession(brain.getPredicate("lastUsername")); } htmlFilter = (HtmlFilter) startPeer("htmlFilter");// Runtime.start("htmlFilter", // "HtmlFilter"); brain.attachTextListener(htmlFilter); htmlFilter.attachTextListener((TextListener) getPeer("mouth")); brain.attachTextListener(this); } catch (Exception e) { speak("could not load brain"); error(e.getMessage()); speak(e.getMessage()); } broadcastState(); return brain; } public SpeechRecognizer startEar() { ear = (SpeechRecognizer) startPeer("ear"); isEarActivated = true; ear.attachSpeechSynthesis((SpeechSynthesis) getPeer("mouth")); ear.attachTextListener(brain); speakBlocking(get("STARTINGEAR")); broadcastState(); return ear; } public void startedGesture() { startedGesture("unknown"); } public void startedGesture(String nameOfGesture) { if (gestureAlreadyStarted) { warn("Warning 1 gesture already running, this can break spacetime and lot of things"); } else { log.info("Starting gesture : {}", nameOfGesture); gestureAlreadyStarted = true; RobotCanMoveRandom = false; } } // FIXME - universal (good) way of handling all exceptions - ie - reporting // back to the user the problem in a short concise way but have // expandable detail in appropriate places public OpenCV startEye() throws Exception { speakBlocking(get("STARTINGOPENCV")); eye = (OpenCV) startPeer("eye", "OpenCV"); subscribeTo(eye.getName(), "publishOpenCVData"); isEyeActivated = true; return eye; } public Tracking startEyesTracking() throws Exception { if (head == null) { startHead(); } return startHeadTracking(head.eyeX, head.eyeY); } public Tracking startEyesTracking(ServoControl eyeX, ServoControl eyeY) throws Exception { if (eye == null) { startEye(); } speakBlocking(get("TRACKINGSTARTED")); eyesTracking = (Tracking) this.startPeer("eyesTracking"); eyesTracking.connect(eye, head.eyeX, head.eyeY); return eyesTracking; } public InMoov2Head startHead() throws Exception { return startHead(null, null, null, null, null, null, null, null); } public InMoov2Head startHead(String port) throws Exception { return startHead(port, null, null, null, null, null, null, null); } // legacy inmoov head exposed pins public InMoov2Head startHead(String port, String type, Integer headYPin, Integer headXPin, Integer eyeXPin, Integer eyeYPin, Integer jawPin, Integer rollNeckPin) { // log.warn(InMoov.buildDNA(myKey, serviceClass)) // speakBlocking(get("STARTINGHEAD") + " " + port); // ??? SHOULD THERE BE REFERENCES AT ALL ??? ... probably not speakBlocking(get("STARTINGHEAD")); head = (InMoov2Head) startPeer("head"); isHeadActivated = true; if (headYPin != null) { head.setPins(headYPin, headXPin, eyeXPin, eyeYPin, jawPin, rollNeckPin); } // lame assumption - port is specified - it must be an Arduino :( if (port != null) { try { speakBlocking(get(port)); Arduino arduino = (Arduino) startPeer("left", "Arduino"); arduino.connect(port); arduino.attach(head.neck); arduino.attach(head.rothead); arduino.attach(head.eyeX); arduino.attach(head.eyeY); arduino.attach(head.jaw); arduino.attach(head.rollNeck); } catch (Exception e) { error(e); } } speakBlocking(get("STARTINGMOUTHCONTROL")); mouthControl = (MouthControl) startPeer("mouthControl"); mouthControl.attach(head.jaw); mouthControl.attach((Attachable) getPeer("mouth")); mouthControl.setmouth(10, 50);// <-- FIXME - not the right place for // config !!! return head; } public void startHeadTracking() throws Exception { if (eye == null) { startEye(); } if (head == null) { startHead(); } if (headTracking == null) { speakBlocking(get("TRACKINGSTARTED")); headTracking = (Tracking) this.startPeer("headTracking"); headTracking.connect(this.eye, head.rothead, head.neck); } } public Tracking startHeadTracking(ServoControl rothead, ServoControl neck) throws Exception { if (eye == null) { startEye(); } if (headTracking == null) { speakBlocking(get("TRACKINGSTARTED")); headTracking = (Tracking) this.startPeer("headTracking"); headTracking.connect(this.eye, rothead, neck); } return headTracking; } public InMoov2Arm startLeftArm() { return startLeftArm(null); } public InMoov2Arm startLeftArm(String port) { // log.warn(InMoov.buildDNA(myKey, serviceClass)) // speakBlocking(get("STARTINGHEAD") + " " + port); // ??? SHOULD THERE BE REFERENCES AT ALL ??? ... probably not speakBlocking(get("STARTINGLEFTARM")); leftArm = (InMoov2Arm) startPeer("leftArm"); isLeftArmActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("left", "Arduino"); arduino.connect(port); arduino.attach(leftArm.bicep); arduino.attach(leftArm.omoplate); arduino.attach(leftArm.rotate); arduino.attach(leftArm.shoulder); } catch (Exception e) { error(e); } } return leftArm; } public InMoov2Hand startLeftHand() { return startLeftHand(null); } public InMoov2Hand startLeftHand(String port) { speakBlocking(get("STARTINGLEFTHAND")); leftHand = (InMoov2Hand) startPeer("leftHand"); isLeftHandActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("left", "Arduino"); arduino.connect(port); arduino.attach(leftHand.thumb); arduino.attach(leftHand.index); arduino.attach(leftHand.majeure); arduino.attach(leftHand.ringFinger); arduino.attach(leftHand.pinky); arduino.attach(leftHand.wrist); } catch (Exception e) { error(e); } } return leftHand; } // TODO - general objective "might" be to reduce peers down to something // that does not need a reference - where type can be switched before creation // and the onnly thing needed is pubs/subs that are not handled in abstracts public SpeechSynthesis startMouth() { mouth = (SpeechSynthesis) startPeer("mouth"); voices = mouth.getVoices(); Voice voice = mouth.getVoice(); if (voice != null) { voiceSelected = voice.getName(); } isMouthActivated = true; if (mute) { mouth.setMute(true); } mouth.attachSpeechRecognizer(ear); // mouth.attach(htmlFilter); // same as brain not needed // this.attach((Attachable) mouth); // if (ear != null) .... broadcastState(); speakBlocking(get("STARTINGMOUTH")); if (Platform.isVirtual()) { speakBlocking("in virtual hardware mode"); } speakBlocking(get("WHATISTHISLANGUAGE")); return mouth; } @Deprecated /* use start eye */ public void startOpenCV() throws Exception { startEye(); } public InMoov2Arm startRightArm() { return startRightArm(null); } public InMoov2Arm startRightArm(String port) { speakBlocking(get("STARTINGRIGHTARM")); rightArm = (InMoov2Arm) startPeer("rightArm"); isRightArmActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("right", "Arduino"); arduino.connect(port); arduino.attach(rightArm.bicep); arduino.attach(rightArm.omoplate); arduino.attach(rightArm.rotate); arduino.attach(rightArm.shoulder); } catch (Exception e) { error(e); } } return rightArm; } public InMoov2Hand startRightHand() { return startRightHand(null); } public InMoov2Hand startRightHand(String port) { speakBlocking(get("STARTINGRIGHTHAND")); rightHand = (InMoov2Hand) startPeer("rightHand"); isRightHandActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("right", "Arduino"); arduino.connect(port); arduino.attach(rightHand.thumb); arduino.attach(rightHand.index); arduino.attach(rightHand.majeure); arduino.attach(rightHand.ringFinger); arduino.attach(rightHand.pinky); arduino.attach(rightHand.wrist); } catch (Exception e) { error(e); } } return rightHand; } public Double getUltraSonicRightDistance() { if (ultraSonicRight != null) { return ultraSonicRight.range(); } else { warn("No UltraSonicRight attached"); return 0.0; } } public Double getUltraSonicLeftDistance() { if (ultraSonicLeft != null) { return ultraSonicLeft.range(); } else { warn("No UltraSonicLeft attached"); return 0.0; } } public void publishPin(Pin pin) { log.info("{} - {}", pin.pin, pin.value); //if (pin.value == 1) { //lastPIRActivityTime = System.currentTimeMillis(); // if its PIR & PIR is active & was sleeping - then wake up ! //if (pirPin == pin.pin && startSleep != null && pin.value == 1) { // attach(); // good morning / evening / night... asleep for % hours //powerUp(); } public void startServos(String leftPort, String rightPort) throws Exception { startHead(leftPort); startLeftArm(leftPort); startLeftHand(leftPort); startRightArm(rightPort); startRightHand(rightPort); startTorso(leftPort); } // FIXME .. externalize in a json file included in InMoov2 public Simulator startSimulator() throws Exception { speakBlocking(get("STARTINGVIRTUAL")); if (jme != null) { log.info("start called twice - starting simulator is reentrant"); return jme; } jme = (JMonkeyEngine) startPeer("simulator"); isSimulatorActivated = true; // adding InMoov2 asset path to the jonkey simulator String assetPath = getResourceDir() + fs + JMonkeyEngine.class.getSimpleName(); File check = new File(assetPath); log.info("loading assets from {}", assetPath); if (!check.exists()) { log.warn("%s does not exist"); } // disable the frustrating servo events ... // Servo.eventsEnabledDefault(false); // jme.loadModels(assetPath); not needed - as InMoov2 unzips the model into // /resource/JMonkeyEngine/assets jme.setRotation(getName() + ".head.jaw", "x"); jme.setRotation(getName() + ".head.neck", "x"); jme.setRotation(getName() + ".head.rothead", "y"); jme.setRotation(getName() + ".head.rollNeck", "z"); jme.setRotation(getName() + ".head.eyeY", "x"); jme.setRotation(getName() + ".head.eyeX", "y"); jme.setRotation(getName() + ".torso.topStom", "z"); jme.setRotation(getName() + ".torso.midStom", "y"); jme.setRotation(getName() + ".torso.lowStom", "x"); jme.setRotation(getName() + ".rightArm.bicep", "x"); jme.setRotation(getName() + ".leftArm.bicep", "x"); jme.setRotation(getName() + ".rightArm.shoulder", "x"); jme.setRotation(getName() + ".leftArm.shoulder", "x"); jme.setRotation(getName() + ".rightArm.rotate", "y"); jme.setRotation(getName() + ".leftArm.rotate", "y"); jme.setRotation(getName() + ".rightArm.omoplate", "z"); jme.setRotation(getName() + ".leftArm.omoplate", "z"); jme.setRotation(getName() + ".rightHand.wrist", "y"); jme.setRotation(getName() + ".leftHand.wrist", "y"); jme.setMapper(getName() + ".head.jaw", 0, 180, -5, 80); jme.setMapper(getName() + ".head.neck", 0, 180, 20, -20); jme.setMapper(getName() + ".head.rollNeck", 0, 180, 30, -30); jme.setMapper(getName() + ".head.eyeY", 0, 180, 40, 140); jme.setMapper(getName() + ".head.eyeX", 0, 180, -10, 70); // HERE there need // to be // two eyeX (left and // right?) jme.setMapper(getName() + ".rightArm.bicep", 0, 180, 0, -150); jme.setMapper(getName() + ".leftArm.bicep", 0, 180, 0, -150); jme.setMapper(getName() + ".rightArm.shoulder", 0, 180, 30, -150); jme.setMapper(getName() + ".leftArm.shoulder", 0, 180, 30, -150); jme.setMapper(getName() + ".rightArm.rotate", 0, 180, 80, -80); jme.setMapper(getName() + ".leftArm.rotate", 0, 180, -80, 80); jme.setMapper(getName() + ".rightArm.omoplate", 0, 180, 10, -180); jme.setMapper(getName() + ".leftArm.omoplate", 0, 180, -10, 180); jme.setMapper(getName() + ".rightHand.wrist", 0, 180, -20, 60); jme.setMapper(getName() + ".leftHand.wrist", 0, 180, 20, -60); jme.setMapper(getName() + ".torso.topStom", 0, 180, -30, 30); jme.setMapper(getName() + ".torso.midStom", 0, 180, 50, 130); jme.setMapper(getName() + ".torso.lowStom", 0, 180, -30, 30); jme.attach(getName() + ".leftHand.thumb", getName() + ".leftHand.thumb1", getName() + ".leftHand.thumb2", getName() + ".leftHand.thumb3"); jme.setRotation(getName() + ".leftHand.thumb1", "y"); jme.setRotation(getName() + ".leftHand.thumb2", "x"); jme.setRotation(getName() + ".leftHand.thumb3", "x"); jme.attach(getName() + ".leftHand.index", getName() + ".leftHand.index", getName() + ".leftHand.index2", getName() + ".leftHand.index3"); jme.setRotation(getName() + ".leftHand.index", "x"); jme.setRotation(getName() + ".leftHand.index2", "x"); jme.setRotation(getName() + ".leftHand.index3", "x"); jme.attach(getName() + ".leftHand.majeure", getName() + ".leftHand.majeure", getName() + ".leftHand.majeure2", getName() + ".leftHand.majeure3"); jme.setRotation(getName() + ".leftHand.majeure", "x"); jme.setRotation(getName() + ".leftHand.majeure2", "x"); jme.setRotation(getName() + ".leftHand.majeure3", "x"); jme.attach(getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger2", getName() + ".leftHand.ringFinger3"); jme.setRotation(getName() + ".leftHand.ringFinger", "x"); jme.setRotation(getName() + ".leftHand.ringFinger2", "x"); jme.setRotation(getName() + ".leftHand.ringFinger3", "x"); jme.attach(getName() + ".leftHand.pinky", getName() + ".leftHand.pinky", getName() + ".leftHand.pinky2", getName() + ".leftHand.pinky3"); jme.setRotation(getName() + ".leftHand.pinky", "x"); jme.setRotation(getName() + ".leftHand.pinky2", "x"); jme.setRotation(getName() + ".leftHand.pinky3", "x"); // left hand mapping complexities of the fingers jme.setMapper(getName() + ".leftHand.index", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.index2", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.index3", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.majeure", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.majeure2", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.majeure3", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.ringFinger", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.ringFinger2", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.ringFinger3", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.pinky", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.pinky2", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.pinky3", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.thumb1", 0, 180, -30, -100); jme.setMapper(getName() + ".leftHand.thumb2", 0, 180, 80, 20); jme.setMapper(getName() + ".leftHand.thumb3", 0, 180, 80, 20); // right hand jme.attach(getName() + ".rightHand.thumb", getName() + ".rightHand.thumb1", getName() + ".rightHand.thumb2", getName() + ".rightHand.thumb3"); jme.setRotation(getName() + ".rightHand.thumb1", "y"); jme.setRotation(getName() + ".rightHand.thumb2", "x"); jme.setRotation(getName() + ".rightHand.thumb3", "x"); jme.attach(getName() + ".rightHand.index", getName() + ".rightHand.index", getName() + ".rightHand.index2", getName() + ".rightHand.index3"); jme.setRotation(getName() + ".rightHand.index", "x"); jme.setRotation(getName() + ".rightHand.index2", "x"); jme.setRotation(getName() + ".rightHand.index3", "x"); jme.attach(getName() + ".rightHand.majeure", getName() + ".rightHand.majeure", getName() + ".rightHand.majeure2", getName() + ".rightHand.majeure3"); jme.setRotation(getName() + ".rightHand.majeure", "x"); jme.setRotation(getName() + ".rightHand.majeure2", "x"); jme.setRotation(getName() + ".rightHand.majeure3", "x"); jme.attach(getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger2", getName() + ".rightHand.ringFinger3"); jme.setRotation(getName() + ".rightHand.ringFinger", "x"); jme.setRotation(getName() + ".rightHand.ringFinger2", "x"); jme.setRotation(getName() + ".rightHand.ringFinger3", "x"); jme.attach(getName() + ".rightHand.pinky", getName() + ".rightHand.pinky", getName() + ".rightHand.pinky2", getName() + ".rightHand.pinky3"); jme.setRotation(getName() + ".rightHand.pinky", "x"); jme.setRotation(getName() + ".rightHand.pinky2", "x"); jme.setRotation(getName() + ".rightHand.pinky3", "x"); jme.setMapper(getName() + ".rightHand.index", 0, 180, 65, -10); jme.setMapper(getName() + ".rightHand.index2", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.index3", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.majeure", 0, 180, 65, -10); jme.setMapper(getName() + ".rightHand.majeure2", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.majeure3", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.ringFinger", 0, 180, 65, -10); jme.setMapper(getName() + ".rightHand.ringFinger2", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.ringFinger3", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.pinky", 0, 180, 65, -10); jme.setMapper(getName() + ".rightHand.pinky2", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.pinky3", 0, 180, 60, -10); jme.setMapper(getName() + ".rightHand.thumb1", 0, 180, 30, 110); jme.setMapper(getName() + ".rightHand.thumb2", 0, 180, -100, -150); jme.setMapper(getName() + ".rightHand.thumb3", 0, 180, -100, -160); // additional experimental mappings /* * simulator.attach(getName() + ".leftHand.pinky", getName() + * ".leftHand.index2"); simulator.attach(getName() + ".leftHand.thumb", * getName() + ".leftHand.index3"); simulator.setRotation(getName() + * ".leftHand.index2", "x"); simulator.setRotation(getName() + * ".leftHand.index3", "x"); simulator.setMapper(getName() + ".leftHand.index", * 0, 180, -90, -270); simulator.setMapper(getName() + ".leftHand.index2", 0, * 180, -90, -270); simulator.setMapper(getName() + ".leftHand.index3", 0, 180, * -90, -270); */ return jme; } public InMoov2Torso startTorso() { return startTorso(null); } public InMoov2Torso startTorso(String port) { if (torso == null) { speakBlocking(get("STARTINGTORSO")); isTorsoActivated = true; torso = (InMoov2Torso) startPeer("torso"); if (port != null) { try { speakBlocking(port); Arduino left = (Arduino) startPeer("left"); left.connect(port); left.attach(torso.lowStom); left.attach(torso.midStom); left.attach(torso.topStom); } catch (Exception e) { error(e); } } } return torso; } /** * called with only port - will default with defaulted pins * @param port * @return */ public UltrasonicSensor startUltraSonicRight(String port) { return startUltraSonicRight(port, 64, 63); } /** * called explicitly with pin values * @param port * @param trigPin * @param echoPin * @return */ public UltrasonicSensor startUltraSonicRight(String port, int trigPin, int echoPin) { if (ultraSonicRight == null) { speakBlocking(get("STARTINGULTRASONIC")); isUltraSonicRightActivated = true; ultraSonicRight = (UltrasonicSensor) startPeer("ultraSonicRight"); if (port != null) { try { speakBlocking(port); Arduino right = (Arduino) startPeer("right"); right.connect(port); right.attach(ultraSonicRight, trigPin, echoPin); } catch (Exception e) { error(e); } } } return ultraSonicRight; } public UltrasonicSensor startUltraSonicLeft(String port) { return startUltraSonicLeft(port, 64, 63); } public UltrasonicSensor startUltraSonicLeft(String port, int trigPin, int echoPin) { if (ultraSonicLeft == null) { speakBlocking(get("STARTINGULTRASONIC")); isUltraSonicLeftActivated = true; ultraSonicLeft = (UltrasonicSensor) startPeer("ultraSonicLeft"); if (port != null) { try { speakBlocking(port); Arduino left = (Arduino) startPeer("left"); left.connect(port); left.attach(ultraSonicLeft, trigPin, echoPin); } catch (Exception e) { error(e); } } } return ultraSonicLeft; } public Pir startPir(String port) { return startPir(port, 23); } public Pir startPir(String port, int pin) { if (pir == null) { speakBlocking(get("STARTINGPIR")); isPirActivated = true; pir = (Pir) startPeer("pir"); if (port != null) { try { speakBlocking(port); Arduino right = (Arduino) startPeer("right"); right.connect(port); right.enablePin(pin, pirPin); pirArduino = right; pirPin = pin; right.addListener("publishPin", this.getName(), "publishPin"); } catch (Exception e) { error(e); } } } return pir; } public ServoMixer startServoMixer() { servomixer = (ServoMixer) startPeer("servomixer"); isServoMixerActivated = true; speakBlocking(get("STARTINGSERVOMIXER")); broadcastState(); return servomixer; } public void stop() { if (head != null) { head.stop(); } if (rightHand != null) { rightHand.stop(); } if (leftHand != null) { leftHand.stop(); } if (rightArm != null) { rightArm.stop(); } if (leftArm != null) { leftArm.stop(); } if (torso != null) { torso.stop(); } } public void stopBrain() { speakBlocking(get("STOPCHATBOT")); releasePeer("brain"); isBrainActivated = false; } public void stopHead() { speakBlocking(get("STOPHEAD")); releasePeer("head"); isHeadActivated = false; } public void stopEar() { speakBlocking(get("STOPEAR")); releasePeer("ear"); isEarActivated = false; broadcastState(); } public void stopEye() { speakBlocking(get("STOPOPENCV")); isEyeActivated = false; releasePeer("eye"); } public void stopGesture() { Python p = (Python) Runtime.getService("python"); p.stop(); } public void stopLeftArm() { speakBlocking(get("STOPLEFTARM")); releasePeer("leftArm"); isLeftArmActivated = false; } public void stopLeftHand() { speakBlocking(get("STOPLEFTHAND")); releasePeer("leftHand"); isLeftHandActivated = false; } public void stopMouth() { speakBlocking(get("STOPMOUTH")); releasePeer("mouth"); // TODO - potentially you could set the field to null in releasePeer mouth = null; isMouthActivated = false; } public void stopRightArm() { speakBlocking(get("STOPRIGHTARM")); releasePeer("rightArm"); isRightArmActivated = false; } public void stopRightHand() { speakBlocking(get("STOPRIGHTHAND")); releasePeer("rightHand"); isRightHandActivated = false; } public void stopTorso() { speakBlocking(get("STOPTORSO")); releasePeer("torso"); isTorsoActivated = false; } public void stopSimulator() { speakBlocking(get("STOPVIRTUAL")); releasePeer("simulator"); jme = null; isSimulatorActivated = false; } public void stopUltraSonicRight() { speakBlocking(get("STOPULTRASONIC")); releasePeer("ultraSonicRight"); isUltraSonicRightActivated = false; } public void stopUltraSonicLeft() { speakBlocking(get("STOPULTRASONIC")); releasePeer("ultraSonicLeft"); isUltraSonicLeftActivated = false; } public void stopPir() { speakBlocking(get("STOPPIR")); releasePeer("pir"); isPirActivated = false; if (pirArduino != null && pirPin != null) { pirArduino.disablePin(pirPin); pirPin = null; pirArduino = null; } } public void stopServoMixer() { speakBlocking(get("STOPSERVOMIXER")); releasePeer("servomixer"); isServoMixerActivated = false; } public void waitTargetPos() { if (head != null) { head.waitTargetPos(); } if (leftArm != null) { leftArm.waitTargetPos(); } if (rightArm != null) { rightArm.waitTargetPos(); } if (leftHand != null) { leftHand.waitTargetPos(); } if (rightHand != null) { rightHand.waitTargetPos(); } if (torso != null) { torso.waitTargetPos(); } } }
package org.myrobotlab.service; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.framework.repo.Category; import org.myrobotlab.framework.repo.ServiceData; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.interfaces.SpeechRecognizer; import org.myrobotlab.service.interfaces.SpeechSynthesis; public class InMoov2 extends Service { private static final long serialVersionUID = 1L; transient private static Runtime myRuntime = null; transient private static ServiceData serviceData = null; // = myRuntime.getServiceData(); // interfaces declaration needed by InMoov transient public SpeechSynthesis mouth; transient public SpeechRecognizer ear; /** * this is for gui combo content */ public static HashMap<Integer, String[]> languages = new HashMap<Integer, String[]>(); public static List<String> speechEngines = new ArrayList<String>(); public static List<String> earEngines = new ArrayList<String>(); // Store parameters inside json related service Integer language; boolean mute; String speechEngine; String earEngine; // end of config public InMoov2(String n) { super(n); if (myRuntime == null) { myRuntime = (Runtime) Runtime.getInstance();; } if (serviceData == null) { serviceData = myRuntime.getServiceData(); } } public static void main(String[] args) { try { LoggingFactory.init(Level.INFO); String leftPort = "COM3"; String rightPort = "COM4"; VirtualArduino vleft = (VirtualArduino) Runtime.start("vleft", "VirtualArduino"); VirtualArduino vright = (VirtualArduino) Runtime.start("vright", "VirtualArduino"); Python python = (Python) Runtime.start("python", "Python"); vleft.connect("COM3"); vright.connect("COM4"); Runtime.start("gui", "SwingGui"); InMoov2 inMoov = (InMoov2) Runtime.start("inMoov", "InMoov2"); inMoov.startMouth(); } catch (Exception e) { log.error("main threw", e); } } @Override public void startService() { super.startService(); languages.put(0, new String[] { "en", "English - United States" }); languages.put(1, new String[] { "fr", "French - France" }); languages.put(2, new String[] { "es", "Spanish - Spain" }); languages.put(3, new String[] { "nl", "Dutch - The Netherlands" }); languages.put(4, new String[] { "de", "German - Germany" }); languages.put(5, new String[] { "ru", "Russian - Russia" }); languages.put(6, new String[] { "hi", "Hindi - India" }); languages.put(7, new String[] { "it", "Italian - Italy" }); InMoov2.speechEngines = getServicesFromCategory("speech"); InMoov2.earEngines = getServicesFromCategory("speech recognition"); this.language = getLanguage(); this.speechEngine = getSpeechEngine(); this.earEngine = getEarEngine(); } static public ServiceType getMetaData() { ServiceType meta = new ServiceType(InMoov2.class); meta.setAvailable(false); return meta; } // list services from meta category (pasted from RuntimeGui.java) public List<String> getServicesFromCategory(final String filter) { List<String> servicesFromCategory = new ArrayList<String>(); Category category = serviceData.getCategory(filter); HashSet<String> filtered = null; filtered = new HashSet<String>(); ArrayList<String> f = category.serviceTypes; for (int i = 0; i < f.size(); ++i) { filtered.add(f.get(i)); } // populate with serviceData List<ServiceType> possibleService = serviceData.getServiceTypes(); for (int i = 0; i < possibleService.size(); ++i) { ServiceType serviceType = possibleService.get(i); if (filtered.contains(serviceType.getName())) { if (serviceType.isAvailable()) { // log.debug("serviceType : " + serviceType.getName()); servicesFromCategory.add(serviceType.getSimpleName()); } } } return servicesFromCategory; } // start core interfaces /** * Start InMoov speech engine also called "mouth" * * @return started SpeechSynthesis service */ public SpeechSynthesis startMouth() throws Exception { mouth = (SpeechSynthesis) Runtime.start(this.getIntanceName() + ".mouth", speechEngine); broadcastState(); // speakBlocking("starting mouth"); return mouth; } /** * Start InMoov ear engine * * @return started SpeechRecognizer service */ public SpeechRecognizer startEar() throws Exception { ear = (SpeechRecognizer) Runtime.create(this.getIntanceName() + ".ear", earEngine); // GroG says .. this broke the build .. // ear.setLanguage(languages.get(language)[0]); ear = (SpeechRecognizer) Runtime.start(this.getIntanceName() + ".ear", earEngine); broadcastState(); // speakBlocking("starting mouth"); return ear; } // end core interfaces // setters & getters public String getSpeechEngine() { if (this.speechEngine == null) { setSpeechEngine("MarySpeech"); } return speechEngine; } public void setSpeechEngine(String speechEngine) { this.speechEngine = speechEngine; info("Set InMoov speech engine : %s", speechEngine); broadcastState(); } public String getEarEngine() { if (this.earEngine == null) { setEarEngine("WebkitSpeechRecognition"); } return earEngine; } public void setEarEngine(String earEngine) { this.earEngine = earEngine; info("Set InMoov ear engine : %s", earEngine); broadcastState(); } /** * @return the mute startup state ( InMoov vocal startup actions ) */ public Boolean getMute() { return mute; } /** * @param mute * the startup mute state to set ( InMoov vocal startup actions ) */ public void setMute(Boolean mute) { this.mute = mute; info("Set InMoov to mute at startup : %s", mute); broadcastState(); } /** * set language for InMoov service used by chatbot + ear + mouth TODO : choose a * language code format instead of index * * @param i * - format : en / fr etc ... */ public void setLanguage(int i) { this.language = i; info("Set InMoov language to %s", languages.get(i)[0]); broadcastState(); } /** * get current language used by InMoov service */ public Integer getLanguage() { if (this.language == null) { setLanguage(0); } return this.language; } // end setter & getter }
package it.near.sdk.Geopolis; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.util.Log; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.loopj.android.http.JsonHttpResponseHandler; import org.altbeacon.beacon.Beacon; import org.altbeacon.beacon.Identifier; import org.altbeacon.beacon.Region; import org.altbeacon.beacon.startup.BootstrapNotifier; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import cz.msebera.android.httpclient.Header; import cz.msebera.android.httpclient.auth.AuthenticationException; import it.near.sdk.Geopolis.Beacons.AltBeaconMonitor; import it.near.sdk.Geopolis.Beacons.BeaconNode; import it.near.sdk.Geopolis.GeoFence.GeoFenceNode; import it.near.sdk.Geopolis.BeaconForest.NearBeacon; import it.near.sdk.Geopolis.Ranging.ProximityListener; import it.near.sdk.Communication.Constants; import it.near.sdk.Communication.NearAsyncHttpClient; import it.near.sdk.Communication.NearNetworkUtil; import it.near.sdk.GlobalConfig; import it.near.sdk.MorpheusNear.Morpheus; import it.near.sdk.Recipes.RecipesManager; import it.near.sdk.Utils.NearUtils; import it.near.sdk.Utils.ULog; /** * Manages a beacon forest, the plugin for monitoring regions structured in a tree. * This region structure was made up to enable background monitoring of more than 20 regions on iOS. * In this plugin every region is specified by ProximityUUID, minor and major. It the current implementation every region is a beacon. * The AltBeacon monitor is initialized with this setting: * - The background period between scans is 8 seconds. * - The background length of a scan 1 second. * - The period to wait before finalizing a region exit. * * In our current plugin representation: * - this is a "pulse" plugin * - the plugin name is: beacon-forest * - the only supported action is: enter_region * - the bundle is the id of a region * * @author cattaneostefano */ public class GeopolisManager implements BootstrapNotifier, ProximityListener { public static final String BEACON_FOREST_PATH = "beacon-forest"; public static final String BEACON_FOREST_TRACKINGS = "trackings"; public static final String BEACON_FOREST_BEACONS = "beacons"; private static final String TAG = "GeopolisManager"; private static final String PREFS_SUFFIX = "GeopolisManager"; // TODO change private static final String PLUGIN_NAME = "beacon-forest"; private static final String ENTER_REGION = "enter_region"; private static final String RADAR_ON = "radar_on"; private final RecipesManager recipesManager; private final String PREFS_NAME; private final SharedPreferences sp; private final SharedPreferences.Editor editor; private List<NearBeacon> beaconList; private List<Region> regionList; private Application mApplication; private Morpheus morpheus; private AltBeaconMonitor monitor; private NearAsyncHttpClient httpClient; public GeopolisManager(Application application, RecipesManager recipesManager) { this.mApplication = application; this.recipesManager = recipesManager; this.monitor = new AltBeaconMonitor(application); setUpMorpheusParser(); String PACK_NAME = mApplication.getApplicationContext().getPackageName(); PREFS_NAME = PACK_NAME + PREFS_SUFFIX; sp = mApplication.getSharedPreferences(PREFS_NAME, 0); editor = sp.edit(); httpClient = new NearAsyncHttpClient(); refreshConfig(); } private void setUpMorpheusParser() { morpheus = new Morpheus(); // register your resources morpheus.getFactory().getDeserializer().registerResourceClass("nodes", Node.class); morpheus.getFactory().getDeserializer().registerResourceClass("beacon_nodes", BeaconNode.class); morpheus.getFactory().getDeserializer().registerResourceClass("geofence_nodes", GeoFenceNode.class); } /** * Refresh the configuration of the component. The list of beacons to monitor will be downloaded from the APIs. * If there's an error in refreshing the configuration, a cached version will be used instead. * */ public void refreshConfig(){ Uri url = Uri.parse(Constants.API.PLUGINS_ROOT).buildUpon() .appendPath(BEACON_FOREST_PATH) .appendPath(BEACON_FOREST_BEACONS).build(); url = Uri.parse(Constants.API.PLUGINS_ROOT).buildUpon() .appendPath("geopolis") .appendPath("nodes") .appendQueryParameter("filter[app_id]",GlobalConfig.getInstance(mApplication).getAppId()) .appendQueryParameter("include", "children.*.children") .build(); try { httpClient.nearGet(mApplication, url.toString(), new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { ULog.d(TAG, response.toString()); JSONObject testNodesObj = null; try { testNodesObj = new JSONObject(testnodes); } catch (JSONException e) { e.printStackTrace(); } List<Node> nodes = NearUtils.parseList(morpheus, response, Node.class); startRadar(nodes); /*List<NearBeacon> beacons = NearUtils.parseList(morpheus, response, NearBeacon.class); beaconList = parseTree(beacons); startRadarOnBeacons(beaconList);*/ // persistList(beaconList); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { ULog.d(TAG, "Error " + statusCode); try { beaconList = loadChachedList(); if (beaconList!=null){ startRadarOnBeacons(beaconList); } } catch (JSONException e) { e.printStackTrace(); } } }); } catch (AuthenticationException e) { e.printStackTrace(); } } private void startRadar(List<Node> nodes) { monitor.setUpMonitor(nodes, this); } private void persistList(List<Node> nodes) { Gson gson = new Gson(); String listStringified = gson.toJson(nodes); editor.putString(TAG, listStringified).apply(); } private List<Node> loadList(){ Gson gson = new Gson(); Type collectionType = new TypeToken<Collection<Node>>(){}.getType(); return gson.<ArrayList<Node>>fromJson(sp.getString(TAG, ""), collectionType); } /** * Save the beacon list on disk * @param beaconList the list of beacons. */ /*private void persistList(List<NearBeacon> beaconList) { Gson gson = new Gson(); String listStringified = gson.toJson(beaconList); ULog.d(TAG , "Persist: " + listStringified); editor.putString(TAG , listStringified); editor.apply(); }*/ /** * Load the beacon list from disk * @return the beacon list * @throws JSONException if the cached list is not properly formatted */ private List<NearBeacon> loadChachedList() throws JSONException { Gson gson = new Gson(); Type collectionType = new TypeToken<Collection<NearBeacon>>(){}.getType(); return gson.<ArrayList<NearBeacon>>fromJson(sp.getString(TAG, ""), collectionType); } /** * Creates a list of AltBeacon regions from Near Regions and starts the radar. * * @param beacons the list to convert */ private void startRadarOnBeacons(List<NearBeacon> beacons) { List<Region> regionsToMonitor = new ArrayList<>(); for (NearBeacon beacon : beacons){ String uniqueId = "Region" + Integer.toString(beacon.getMajor()) + Integer.toString(beacon.getMinor()); Region region = new Region(uniqueId, Identifier.parse(beacon.getUuid()), Identifier.fromInt(beacon.getMajor()), Identifier.fromInt(beacon.getMinor())); regionsToMonitor.add(region); } regionList = regionsToMonitor; // BeaconDynamicRadar radar = new BeaconDynamicRadar(getApplicationContext(), beacons, null); // monitor.startRadar(backgroundBetweenScanPeriod, backgroundScanPeriod, regionExitPeriod, regionsToMonitor, this); if (sp.getBoolean(RADAR_ON, false)){ // monitor.startRadar(regionsToMonitor, this); } } /*public void startRadar(){ editor.putBoolean(RADAR_ON, true).commit(); monitor.startRadar(regionList, this); }*/ /** * Walk through every root beacon and returns a list of all beacons. * @param beacons the root beacons to parse * @return all beacons under any root beacon */ private List<NearBeacon> parseTree(List<NearBeacon> beacons) { List<NearBeacon> allBeacons = new ArrayList<>(); for (NearBeacon beacon : beacons){ allBeacons.addAll(parseTree(beacon)); } return allBeacons; } /** * Walk through the tree under a node and returns all beacons in the tree (including the root) * @param node the beacon from which to start parsing * @return a flattened list of the tree beacons */ private List<NearBeacon> parseTree(NearBeacon node){ List<NearBeacon> list = new ArrayList<>(); list.add(node); for (NearBeacon beacon : node.getChildren()){ list.addAll(parseTree(beacon)); } return list; } @Override public Context getApplicationContext() { return mApplication.getApplicationContext(); } @Override public void didEnterRegion(Region region) { String pulseBundle = getPulseFromRegion(region); trackRegionEnter(pulseBundle); if (pulseBundle != null){ firePulse(ENTER_REGION, pulseBundle); } } @Override public void didExitRegion(Region region) { } @Override public void didDetermineStateForRegion(int i, Region region) { Log.d(TAG, "determine region:" + region.toString() + " state: " + i); } /** * Send tracking data to the Forest beacon APIs about a region enter (every beacon is a region). * @param regionBundle the beacon identifier */ private void trackRegionEnter(String regionBundle) { try { Uri url = Uri.parse(Constants.API.PLUGINS_ROOT).buildUpon() .appendPath(BEACON_FOREST_PATH) .appendPath(BEACON_FOREST_TRACKINGS).build(); NearNetworkUtil.sendTrack(mApplication, url.toString(), buildTrackBody(regionBundle)); } catch (JSONException e) { ULog.d(TAG, "Unable to send track: " + e.toString()); } } /** * Compute the HTTP request body from the region identifier in jsonAPI format. * @param regionBundle the region identifier * @return the correctly formed body * @throws JSONException */ private String buildTrackBody(String regionBundle) throws JSONException { HashMap<String, Object> map = new HashMap<>(); map.put("beacon_id" , regionBundle); DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); Date now = new Date(System.currentTimeMillis()); String formatted = sdf.format(now); map.put("tracked_at", formatted); map.put("platform", "android"); map.put("profile_id", GlobalConfig.getInstance(mApplication).getProfileId()); map.put("installation_id", GlobalConfig.getInstance(mApplication).getInstallationId()); /*String installId = GlobalConfig.getInstance(getApplicationContext()).getInstallationId(); map.put("installation_id", installId);*/ return NearUtils.toJsonAPI("trackings", map); } /** * Return the region identifier form an AltBeacon region * @param region the AltBeacon region * @return the region identifier of the region if such region exists in the configuration, <code>null</code> otherwise */ private String getPulseFromRegion(Region region) { // TODO this needs ot be changed for (NearBeacon beacon : beaconList){ if (beacon.getUuid().equals(region.getId1().toString()) && beacon.getMajor() == region.getId2().toInt() && beacon.getMinor() == region.getId3().toInt()){ return beacon.getId(); } } return null; } /** * Notify the RECIPES_PATH manager of the occurance of a registered pulse. * @param pulseAction the action of the pulse to notify * @param pulseBundle the region identifier of the pulse */ private void firePulse(String pulseAction, String pulseBundle) { ULog.d(TAG, "firePulse!"); recipesManager.gotPulse(PLUGIN_NAME, pulseAction, pulseBundle); } @Override public void enterBeaconRange(Beacon beacon, int proximity) { ULog.wtf(TAG, "Enter in range: " + proximity + " for beacon: " + beacon.toString()); } @Override public void exitBeaconRange(Beacon beacon, int proximity) { ULog.wtf(TAG, "Exit from range: " + proximity + " for beacon: " + beacon.toString()); } @Override public void enterRegion(Region region) { String pulseBundle = getPulseFromRegion(region); trackRegionEnter(pulseBundle); if (pulseBundle != null){ firePulse(ENTER_REGION, pulseBundle); } } @Override public void exitRegion(Region region) { } /** * Returns wether the app started the location radar. * @param context * @return */ public static boolean isRadarStarted(Context context){ String PACK_NAME = context.getApplicationContext().getPackageName(); SharedPreferences sp = context.getSharedPreferences(PACK_NAME + PREFS_SUFFIX, 0); return sp.getBoolean(RADAR_ON, false); } String testnodes = "{\n" + " \"data\": [\n" + " {\n" + " \"id\": \"a27fb650-19c9-403c-8df9-e2f4e5d8fe3a\",\n" + " \"type\": \"geofence_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"a37a8543-355c-4825-857b-5624031f8d2a\",\n" + " \"latitude\": 40.78595,\n" + " \"longitude\": -73.667595,\n" + " \"radius\": 50.0\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": null\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"5618708a-5ae8-4794-8a43-95e617db3088\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"1fe492ae-3d53-4642-ba5b-7daa46378320\",\n" + " \"type\": \"geofence_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"060f7b11-5302-4440-bb46-62f1a65d612a\",\n" + " \"latitude\": 38.996207,\n" + " \"longitude\": -122.012045,\n" + " \"radius\": 50.0\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": null\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"deef15bc-fcd8-4edd-96a6-dce5b4df9f45\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"18a36337-392f-41d7-84dc-b09ba14cf09b\",\n" + " \"type\": \"geofence_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"60af1b03-e03c-4c97-9b25-23c869a8cd8f\",\n" + " \"latitude\": 37.575803,\n" + " \"longitude\": -81.611008,\n" + " \"radius\": 50.0\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": null\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"309dc29d-1899-489e-a058-bf04547c1d73\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " }\n" + " ],\n" + " \"included\": [\n" + " {\n" + " \"id\": \"5618708a-5ae8-4794-8a43-95e617db3088\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": null,\n" + " \"proximity_uuid\": \"9f1e4c18-87c6-47c3-8518-7e3269280d53\",\n" + " \"major\": null,\n" + " \"minor\": null\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"a27fb650-19c9-403c-8df9-e2f4e5d8fe3a\",\n" + " \"type\": \"geofence_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"50c2805e-6402-4d28-abd7-28faf5be2b8a\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"9363d258-aa0d-4f76-ac5e-ad1fb1ef444a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"50c2805e-6402-4d28-abd7-28faf5be2b8a\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"cb958ac8-a8a8-4308-bd32-25ce4638fe9e\",\n" + " \"proximity_uuid\": \"9f1e4c18-87c6-47c3-8518-7e3269280d53\",\n" + " \"major\": 39357,\n" + " \"minor\": null\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"5618708a-5ae8-4794-8a43-95e617db3088\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"06546666-eeef-41f7-8564-60f8d9195bef\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"6a570b4c-e751-430e-8a8d-e77f26e43554\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"fd44e515-39bc-4b98-8f8b-ba2f26c2abda\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"458f6256-d1fc-443b-b6ad-28c51c5daf0d\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"06eadb09-b858-4a61-afd2-c3c6457dff86\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"02659ecd-8ae0-4bad-8b00-96a8b97b402a\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"d92691a4-cbea-42c0-a031-1fc536d1eebf\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"9e92e24c-a4b8-417d-bf8c-e500c66a247e\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"2b655817-ecd5-4dd4-9638-7a162fb3131f\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"05492e1f-ab32-4b5a-87dc-64d16be8ff3f\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"06546666-eeef-41f7-8564-60f8d9195bef\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"8f71e8ea-078f-49e3-96b0-1ebbf520c91a\",\n" + " \"proximity_uuid\": \"9f1e4c18-87c6-47c3-8518-7e3269280d53\",\n" + " \"major\": 39357,\n" + " \"minor\": 20796\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"50c2805e-6402-4d28-abd7-28faf5be2b8a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"6a570b4c-e751-430e-8a8d-e77f26e43554\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"7a40ff3c-2d2c-4eb7-9aba-1870520d9c97\",\n" + " \"proximity_uuid\": \"9f1e4c18-87c6-47c3-8518-7e3269280d53\",\n" + " \"major\": 39357,\n" + " \"minor\": 63141\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"50c2805e-6402-4d28-abd7-28faf5be2b8a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"fd44e515-39bc-4b98-8f8b-ba2f26c2abda\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"2bfaecf1-c120-4db6-99ff-f8768600a728\",\n" + " \"proximity_uuid\": \"9f1e4c18-87c6-47c3-8518-7e3269280d53\",\n" + " \"major\": 39357,\n" + " \"minor\": 3154\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"50c2805e-6402-4d28-abd7-28faf5be2b8a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"458f6256-d1fc-443b-b6ad-28c51c5daf0d\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"e4e2eace-e8a5-41c9-8774-0c263b87cf8a\",\n" + " \"proximity_uuid\": \"9f1e4c18-87c6-47c3-8518-7e3269280d53\",\n" + " \"major\": 39357,\n" + " \"minor\": 22865\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"50c2805e-6402-4d28-abd7-28faf5be2b8a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"06eadb09-b858-4a61-afd2-c3c6457dff86\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"7f745711-d477-4290-9d62-9288459726cb\",\n" + " \"proximity_uuid\": \"9f1e4c18-87c6-47c3-8518-7e3269280d53\",\n" + " \"major\": 39357,\n" + " \"minor\": 45134\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"50c2805e-6402-4d28-abd7-28faf5be2b8a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"02659ecd-8ae0-4bad-8b00-96a8b97b402a\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"3920020b-552a-4b19-9877-be9649707692\",\n" + " \"proximity_uuid\": \"9f1e4c18-87c6-47c3-8518-7e3269280d53\",\n" + " \"major\": 39357,\n" + " \"minor\": 42819\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"50c2805e-6402-4d28-abd7-28faf5be2b8a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"d92691a4-cbea-42c0-a031-1fc536d1eebf\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"2d638ab9-db76-4530-9975-e99642d26f19\",\n" + " \"proximity_uuid\": \"9f1e4c18-87c6-47c3-8518-7e3269280d53\",\n" + " \"major\": 39357,\n" + " \"minor\": 25825\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"50c2805e-6402-4d28-abd7-28faf5be2b8a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"9e92e24c-a4b8-417d-bf8c-e500c66a247e\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"d2fa45de-5714-4f6f-ae27-abca83bc7e1c\",\n" + " \"proximity_uuid\": \"9f1e4c18-87c6-47c3-8518-7e3269280d53\",\n" + " \"major\": 39357,\n" + " \"minor\": 40075\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"50c2805e-6402-4d28-abd7-28faf5be2b8a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"2b655817-ecd5-4dd4-9638-7a162fb3131f\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"485285db-905b-49ee-a03c-d93b9775d2a7\",\n" + " \"proximity_uuid\": \"9f1e4c18-87c6-47c3-8518-7e3269280d53\",\n" + " \"major\": 39357,\n" + " \"minor\": 50243\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"50c2805e-6402-4d28-abd7-28faf5be2b8a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"05492e1f-ab32-4b5a-87dc-64d16be8ff3f\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"6ab5e674-4d8f-4abb-8aaa-e7612b1a97f6\",\n" + " \"proximity_uuid\": \"9f1e4c18-87c6-47c3-8518-7e3269280d53\",\n" + " \"major\": 39357,\n" + " \"minor\": 12090\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"50c2805e-6402-4d28-abd7-28faf5be2b8a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"9363d258-aa0d-4f76-ac5e-ad1fb1ef444a\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"f27f5530-412d-46b1-88db-88e971bde1c4\",\n" + " \"proximity_uuid\": \"9f1e4c18-87c6-47c3-8518-7e3269280d53\",\n" + " \"major\": 47147,\n" + " \"minor\": null\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"5618708a-5ae8-4794-8a43-95e617db3088\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"3cda8e2d-daf8-48e2-a903-bc8dded3c275\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"471c47c3-8d1f-4507-a9cc-6a49e948b964\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"3cda8e2d-daf8-48e2-a903-bc8dded3c275\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"1fe214cf-583c-4167-b201-b2026b28f4a9\",\n" + " \"proximity_uuid\": \"9f1e4c18-87c6-47c3-8518-7e3269280d53\",\n" + " \"major\": 47147,\n" + " \"minor\": 599\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"9363d258-aa0d-4f76-ac5e-ad1fb1ef444a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"471c47c3-8d1f-4507-a9cc-6a49e948b964\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"101a2e4f-c908-4621-b67a-0210ffed9275\",\n" + " \"proximity_uuid\": \"9f1e4c18-87c6-47c3-8518-7e3269280d53\",\n" + " \"major\": 47147,\n" + " \"minor\": 46188\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"9363d258-aa0d-4f76-ac5e-ad1fb1ef444a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"deef15bc-fcd8-4edd-96a6-dce5b4df9f45\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": null,\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": null,\n" + " \"minor\": null\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"1fe492ae-3d53-4642-ba5b-7daa46378320\",\n" + " \"type\": \"geofence_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"ae3da4dc-c89c-4b43-b49c-dbc9f14daf73\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"52698f55-00da-4517-9334-3daba5597f1a\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"6b112a5a-fcbf-4147-aa79-e35265cc9759\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"a927913a-0c20-4ee1-8628-28688392882d\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"4a51333e-4873-46e5-a4e6-45d5798ad750\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"354df2c7-0dc3-41d9-85cf-5a002a5df426\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"ae3da4dc-c89c-4b43-b49c-dbc9f14daf73\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"97f81865-04eb-4ff2-9ffb-0f4809c08edb\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 19014,\n" + " \"minor\": null\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"deef15bc-fcd8-4edd-96a6-dce5b4df9f45\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"85a190fa-676e-4793-ba7c-99b9b07d084e\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"62c9b3ae-fe65-4254-be4f-f75e76919c2d\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"cdb48b04-867c-45ac-8fef-1c3b3bc11d33\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"58181576-85ca-4280-8d56-085f265aee5a\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"5ae1506d-d63b-414f-a1a1-4c64f2061bcd\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"43e0528d-d50d-46cf-8d53-dbd5440157a6\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"d535c9b6-e4a0-4466-8811-612f4f558e7d\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"2ad73740-e860-4b2d-80f3-f5192ff6bd05\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"85a190fa-676e-4793-ba7c-99b9b07d084e\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"f5a469aa-9ce8-467a-8f60-ba69b66e4bae\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 19014,\n" + " \"minor\": 54946\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"ae3da4dc-c89c-4b43-b49c-dbc9f14daf73\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"62c9b3ae-fe65-4254-be4f-f75e76919c2d\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"67e8ba1a-4a6a-4675-a9d9-6b1990540b35\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 19014,\n" + " \"minor\": 9471\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"ae3da4dc-c89c-4b43-b49c-dbc9f14daf73\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"cdb48b04-867c-45ac-8fef-1c3b3bc11d33\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"305ac6c0-de67-46e7-9b86-8e4ebd7ff695\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 19014,\n" + " \"minor\": 41778\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"ae3da4dc-c89c-4b43-b49c-dbc9f14daf73\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"58181576-85ca-4280-8d56-085f265aee5a\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"1944883a-077a-430f-a0b7-1644b68af018\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 19014,\n" + " \"minor\": 8414\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"ae3da4dc-c89c-4b43-b49c-dbc9f14daf73\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"5ae1506d-d63b-414f-a1a1-4c64f2061bcd\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"8e395ba7-75fa-466f-a141-a5968ef269c1\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 19014,\n" + " \"minor\": 36496\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"ae3da4dc-c89c-4b43-b49c-dbc9f14daf73\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"43e0528d-d50d-46cf-8d53-dbd5440157a6\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"2948a4b4-0b2f-4612-85dc-bf5e512a4f4b\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 19014,\n" + " \"minor\": 18448\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"ae3da4dc-c89c-4b43-b49c-dbc9f14daf73\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"d535c9b6-e4a0-4466-8811-612f4f558e7d\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"05f22c1c-04c8-4766-b891-e9e8df315416\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 19014,\n" + " \"minor\": 34309\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"ae3da4dc-c89c-4b43-b49c-dbc9f14daf73\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"2ad73740-e860-4b2d-80f3-f5192ff6bd05\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"f2257451-7e13-41fa-ae63-99ab7fc955be\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 19014,\n" + " \"minor\": 16123\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"ae3da4dc-c89c-4b43-b49c-dbc9f14daf73\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"52698f55-00da-4517-9334-3daba5597f1a\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"d74ba1c3-e3a4-4327-be27-77920765d1bd\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 33773,\n" + " \"minor\": null\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"deef15bc-fcd8-4edd-96a6-dce5b4df9f45\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"57c7adaf-07f6-4efb-9e4f-125db1eaadac\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"197f024c-59aa-42ad-8d94-ead4786c2104\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"57c7adaf-07f6-4efb-9e4f-125db1eaadac\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"a933b035-71c6-4d34-b6a6-d8786a857188\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 33773,\n" + " \"minor\": 6158\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"52698f55-00da-4517-9334-3daba5597f1a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"197f024c-59aa-42ad-8d94-ead4786c2104\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"43101554-000c-45e6-a5da-52ebe9073fe6\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 33773,\n" + " \"minor\": 40481\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"52698f55-00da-4517-9334-3daba5597f1a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"6b112a5a-fcbf-4147-aa79-e35265cc9759\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"f16bb26e-e8dd-4b21-81aa-e18b0173a9b4\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 50083,\n" + " \"minor\": null\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"deef15bc-fcd8-4edd-96a6-dce5b4df9f45\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"efb60e52-3899-4bbc-a123-144929920f3a\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"40c4da06-a600-45e9-a447-fcf5e3046038\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"a34b3a19-991c-42ba-93b5-438c9f4af4f7\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"88b76860-062b-4690-b619-26b9843f2704\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"4e61205b-e1cc-4aa6-aed5-b212aa6cf755\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"9524b11f-37bc-4795-8d9b-5e484297b5ed\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"52f091a0-9faf-47cb-8ad6-f2be6515edc9\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"26092d51-d2fc-4065-8183-3521f92b850b\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"c187cf6e-e8d8-4402-8c2f-c9ac15d2febf\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"efb60e52-3899-4bbc-a123-144929920f3a\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"91c9e714-3da3-4f27-873f-3a1afe551fb9\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 50083,\n" + " \"minor\": 51149\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"6b112a5a-fcbf-4147-aa79-e35265cc9759\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"40c4da06-a600-45e9-a447-fcf5e3046038\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"877dd79e-5a6a-4a58-981c-b6d0dd2e8077\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 50083,\n" + " \"minor\": 28747\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"6b112a5a-fcbf-4147-aa79-e35265cc9759\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"a34b3a19-991c-42ba-93b5-438c9f4af4f7\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"ceaff267-d752-43fe-8c9e-afb4d9cf1ed0\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 50083,\n" + " \"minor\": 39245\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"6b112a5a-fcbf-4147-aa79-e35265cc9759\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"88b76860-062b-4690-b619-26b9843f2704\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"6b94644d-9322-42f3-b708-afbc904b7e3b\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 50083,\n" + " \"minor\": 40647\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"6b112a5a-fcbf-4147-aa79-e35265cc9759\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"4e61205b-e1cc-4aa6-aed5-b212aa6cf755\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"03d49c28-0fb2-4eb4-ae9f-3f1be48ccb26\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 50083,\n" + " \"minor\": 15616\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"6b112a5a-fcbf-4147-aa79-e35265cc9759\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"9524b11f-37bc-4795-8d9b-5e484297b5ed\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"9c09403e-2d68-4917-99bd-0210386587bf\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 50083,\n" + " \"minor\": 4471\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"6b112a5a-fcbf-4147-aa79-e35265cc9759\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"52f091a0-9faf-47cb-8ad6-f2be6515edc9\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"5c5e5d4c-724f-4ef9-9c2d-56f3e7844dbf\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 50083,\n" + " \"minor\": 11287\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"6b112a5a-fcbf-4147-aa79-e35265cc9759\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"26092d51-d2fc-4065-8183-3521f92b850b\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"c27e7e75-f858-443f-8224-794ff484a7d6\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 50083,\n" + " \"minor\": 62249\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"6b112a5a-fcbf-4147-aa79-e35265cc9759\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"c187cf6e-e8d8-4402-8c2f-c9ac15d2febf\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"fd54f25b-2a58-43b1-914b-7c8567411dd9\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 50083,\n" + " \"minor\": 31307\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"6b112a5a-fcbf-4147-aa79-e35265cc9759\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"a927913a-0c20-4ee1-8628-28688392882d\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"0b2a320d-3669-429e-ba36-14a276535f17\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 29614,\n" + " \"minor\": null\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"deef15bc-fcd8-4edd-96a6-dce5b4df9f45\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"6dd15c13-f842-4054-88f0-515144a2799d\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"e78c7e63-dc1a-4a05-8b3f-19b731cb5382\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"e194cf9a-78ef-44fe-8a0a-4a037b31d27d\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"6dd15c13-f842-4054-88f0-515144a2799d\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"d7fc36f0-1d82-4444-bd14-817cf198123c\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 29614,\n" + " \"minor\": 19532\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"a927913a-0c20-4ee1-8628-28688392882d\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"e78c7e63-dc1a-4a05-8b3f-19b731cb5382\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"8237bb95-22bc-4212-8699-a46903d28206\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 29614,\n" + " \"minor\": 17878\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"a927913a-0c20-4ee1-8628-28688392882d\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"e194cf9a-78ef-44fe-8a0a-4a037b31d27d\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"5540c06e-933d-4673-a055-82b4bdf74d65\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 29614,\n" + " \"minor\": 26425\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"a927913a-0c20-4ee1-8628-28688392882d\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"4a51333e-4873-46e5-a4e6-45d5798ad750\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"99b28063-0d3c-4f84-a280-f9a1d5569a3b\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 35025,\n" + " \"minor\": null\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"deef15bc-fcd8-4edd-96a6-dce5b4df9f45\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"c2eecad5-7929-457d-b7df-9398572fa6dc\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"cf46c7f1-8be6-483c-86e9-1e02f46df658\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"31cec406-023b-44c0-9b36-da3078d7ca2b\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"83e916a1-117b-4e59-bd64-c6d4514f9dcb\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"36c2911f-373a-4640-a187-6657a2af6f4c\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"b5c651d6-1c93-463a-b630-597e2cde1bfe\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"99467624-9ff3-49a6-8964-301190577bb7\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"94e58c51-2b30-4816-9428-0dbe1e53abb6\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"7be860c1-d42e-4cca-a0da-49611bcc1656\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"c2eecad5-7929-457d-b7df-9398572fa6dc\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"118d70cf-c2f8-49a5-8f44-f80295db91a6\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 35025,\n" + " \"minor\": 62396\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"4a51333e-4873-46e5-a4e6-45d5798ad750\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"cf46c7f1-8be6-483c-86e9-1e02f46df658\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"c5a72e85-156f-42c3-bc0f-cbe39dab79df\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 35025,\n" + " \"minor\": 42816\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"4a51333e-4873-46e5-a4e6-45d5798ad750\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"31cec406-023b-44c0-9b36-da3078d7ca2b\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"6679cd65-0cd6-43dd-b0ba-cdcdc395ba3a\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 35025,\n" + " \"minor\": 42841\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"4a51333e-4873-46e5-a4e6-45d5798ad750\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"83e916a1-117b-4e59-bd64-c6d4514f9dcb\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"a489f779-3a09-4e94-aa2a-301f889622ea\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 35025,\n" + " \"minor\": 27551\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"4a51333e-4873-46e5-a4e6-45d5798ad750\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"36c2911f-373a-4640-a187-6657a2af6f4c\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"755f9fdd-4955-44a1-b6e4-aa7c0b77f504\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 35025,\n" + " \"minor\": 13212\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"4a51333e-4873-46e5-a4e6-45d5798ad750\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"b5c651d6-1c93-463a-b630-597e2cde1bfe\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"f7a4d440-5870-4a52-b7cf-b8d9a500889f\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 35025,\n" + " \"minor\": 19816\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"4a51333e-4873-46e5-a4e6-45d5798ad750\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"99467624-9ff3-49a6-8964-301190577bb7\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"3147a591-bffc-4255-a832-0c4ce87c67c4\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 35025,\n" + " \"minor\": 5325\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"4a51333e-4873-46e5-a4e6-45d5798ad750\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"94e58c51-2b30-4816-9428-0dbe1e53abb6\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"f3954e10-c108-43f9-9e16-aa0035418f2c\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 35025,\n" + " \"minor\": 35740\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"4a51333e-4873-46e5-a4e6-45d5798ad750\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"7be860c1-d42e-4cca-a0da-49611bcc1656\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"ef5ac1c8-ec70-48f7-82c2-ad536939a569\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 35025,\n" + " \"minor\": 8660\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"4a51333e-4873-46e5-a4e6-45d5798ad750\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"354df2c7-0dc3-41d9-85cf-5a002a5df426\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"095a1b3a-742e-4a0e-9a92-f6d1ae59f2af\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 13544,\n" + " \"minor\": null\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"deef15bc-fcd8-4edd-96a6-dce5b4df9f45\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"005a6015-abe9-4333-9940-a5226eac0f4b\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"725be32e-f64f-47e1-95f7-e717beffab21\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"e45725ba-c64b-414f-8bbe-adf25545abdc\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"c777b678-2cb7-450f-9a36-0288fdbdd321\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"d674d3fa-7484-4cc6-b6e8-2ece15dd44b6\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"005a6015-abe9-4333-9940-a5226eac0f4b\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"2cfab8fc-54a8-491e-8921-2600cd462d2a\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 13544,\n" + " \"minor\": 28899\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"354df2c7-0dc3-41d9-85cf-5a002a5df426\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"725be32e-f64f-47e1-95f7-e717beffab21\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"8f927d36-2a0f-41d2-854b-3c323f78dc52\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 13544,\n" + " \"minor\": 54410\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"354df2c7-0dc3-41d9-85cf-5a002a5df426\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"e45725ba-c64b-414f-8bbe-adf25545abdc\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"ff3f85a0-5608-4caf-b8e4-59da8fca6831\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 13544,\n" + " \"minor\": 54153\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"354df2c7-0dc3-41d9-85cf-5a002a5df426\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"c777b678-2cb7-450f-9a36-0288fdbdd321\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"df7c5692-3247-4b1e-a463-81eb5868a1dd\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 13544,\n" + " \"minor\": 65203\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"354df2c7-0dc3-41d9-85cf-5a002a5df426\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"d674d3fa-7484-4cc6-b6e8-2ece15dd44b6\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"bc6e2bd0-bcca-4308-8f5f-b0c661a747a0\",\n" + " \"proximity_uuid\": \"3551a71e-015f-448a-8281-2784225d7cca\",\n" + " \"major\": 13544,\n" + " \"minor\": 50249\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"354df2c7-0dc3-41d9-85cf-5a002a5df426\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"309dc29d-1899-489e-a058-bf04547c1d73\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": null,\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": null,\n" + " \"minor\": null\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"18a36337-392f-41d7-84dc-b09ba14cf09b\",\n" + " \"type\": \"geofence_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"5cd0fee6-d8fb-4d0f-aac0-34bd23e0c11e\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"48ca1022-10e5-4335-bdc4-b8182aaeaf49\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"67ffbe39-4951-4503-ac58-51819c20a95a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"5cd0fee6-d8fb-4d0f-aac0-34bd23e0c11e\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"609a8416-b3b5-484e-8107-051f93abb801\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 3975,\n" + " \"minor\": null\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"309dc29d-1899-489e-a058-bf04547c1d73\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"f7308d22-12e1-43f4-957f-2294ab8e3cde\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"b2124ef6-5f11-4a64-8289-6f68f2bc8acc\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"f7308d22-12e1-43f4-957f-2294ab8e3cde\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"f34d4da5-7ee3-4a3c-9fd8-d65b9fac3148\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 3975,\n" + " \"minor\": 24895\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"5cd0fee6-d8fb-4d0f-aac0-34bd23e0c11e\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"b2124ef6-5f11-4a64-8289-6f68f2bc8acc\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"b8f8bac1-29ef-4574-8d3d-5b6be70c641c\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 3975,\n" + " \"minor\": 39771\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"5cd0fee6-d8fb-4d0f-aac0-34bd23e0c11e\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"48ca1022-10e5-4335-bdc4-b8182aaeaf49\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"e53f73b2-03a6-4f85-b9d6-a1e634762aa3\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 54308,\n" + " \"minor\": null\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"309dc29d-1899-489e-a058-bf04547c1d73\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"13196c7b-9fb4-4bdb-9411-a8fde1007489\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"333b3e88-b9f6-4090-b161-64672dc295bb\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"ca120aae-10b7-4ec9-846a-baa60d5311fb\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"e6e28990-50c0-48f7-8c79-2fc264d3cfa4\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"84d4af82-021f-4d5d-80e5-3ebc6ed38d27\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"34b57bb2-ad8e-4f92-8c03-01f89d92b710\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"13196c7b-9fb4-4bdb-9411-a8fde1007489\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"3b8b81b1-5a04-4571-99fa-9e28e15e1c70\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 54308,\n" + " \"minor\": 8044\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"48ca1022-10e5-4335-bdc4-b8182aaeaf49\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"333b3e88-b9f6-4090-b161-64672dc295bb\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"26e698a4-b874-4c79-9d71-0872916047aa\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 54308,\n" + " \"minor\": 36635\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"48ca1022-10e5-4335-bdc4-b8182aaeaf49\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"ca120aae-10b7-4ec9-846a-baa60d5311fb\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"df03f07e-2238-4def-b4ad-6737b72cc46f\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 54308,\n" + " \"minor\": 54720\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"48ca1022-10e5-4335-bdc4-b8182aaeaf49\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"e6e28990-50c0-48f7-8c79-2fc264d3cfa4\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"2a208227-6f2d-478e-bf81-4cf1db7e934d\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 54308,\n" + " \"minor\": 20756\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"48ca1022-10e5-4335-bdc4-b8182aaeaf49\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"84d4af82-021f-4d5d-80e5-3ebc6ed38d27\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"800f78f4-aefc-4107-af90-7c6b4b056820\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 54308,\n" + " \"minor\": 48166\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"48ca1022-10e5-4335-bdc4-b8182aaeaf49\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"34b57bb2-ad8e-4f92-8c03-01f89d92b710\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"0f6fac1c-03a1-4623-97a3-666ae7b53843\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 54308,\n" + " \"minor\": 19222\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"48ca1022-10e5-4335-bdc4-b8182aaeaf49\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"67ffbe39-4951-4503-ac58-51819c20a95a\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"6d0a0563-7e2e-4211-bfdf-1c1f4dc8618b\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 47400,\n" + " \"minor\": null\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"309dc29d-1899-489e-a058-bf04547c1d73\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + " {\n" + " \"id\": \"a24d0cd3-1cd6-4de3-9fc5-1e5597b77a13\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"dd8c6a7c-52ef-4e3f-a40e-f5b0b8b292c7\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"808c30c1-66bc-43f1-a4ae-bdde485d374e\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"41b2602d-d718-4d22-9e98-97bed31eeb20\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"5b6b01bd-0026-405c-a58d-98c20b3db962\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"726a57b0-e814-4073-b79c-6152b3548275\",\n" + " \"type\": \"beacon_nodes\"\n" + " },\n" + " {\n" + " \"id\": \"ddcd2bb2-7944-4f37-bb1e-1c5b8ee8dbf4\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"a24d0cd3-1cd6-4de3-9fc5-1e5597b77a13\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"14415859-cd0a-46e5-8829-64da2d8398e6\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 47400,\n" + " \"minor\": 46116\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"67ffbe39-4951-4503-ac58-51819c20a95a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"dd8c6a7c-52ef-4e3f-a40e-f5b0b8b292c7\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"836c92c3-b84a-48e4-8405-e5824af6210e\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 47400,\n" + " \"minor\": 6481\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"67ffbe39-4951-4503-ac58-51819c20a95a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"808c30c1-66bc-43f1-a4ae-bdde485d374e\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"806c4547-eee5-4207-bf7e-14034bbeec0e\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 47400,\n" + " \"minor\": 64270\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"67ffbe39-4951-4503-ac58-51819c20a95a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"41b2602d-d718-4d22-9e98-97bed31eeb20\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"b6177a90-5f05-4bc4-9e1c-b4d2e54e2b8e\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 47400,\n" + " \"minor\": 7491\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"67ffbe39-4951-4503-ac58-51819c20a95a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"5b6b01bd-0026-405c-a58d-98c20b3db962\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"f3ac303c-715e-47b8-99e4-bae395dfc67e\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 47400,\n" + " \"minor\": 57438\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"67ffbe39-4951-4503-ac58-51819c20a95a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"726a57b0-e814-4073-b79c-6152b3548275\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"1789c68d-a166-4024-986d-b4cca3a71e1f\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 47400,\n" + " \"minor\": 33217\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"67ffbe39-4951-4503-ac58-51819c20a95a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"ddcd2bb2-7944-4f37-bb1e-1c5b8ee8dbf4\",\n" + " \"type\": \"beacon_nodes\",\n" + " \"attributes\": {\n" + " \"app_id\": \"1d464fa3-a915-434f-8925-bcb5388f559d\",\n" + " \"identifier\": \"9a74370e-902e-496c-9f32-d47b596c2a27\",\n" + " \"proximity_uuid\": \"2b3d915a-fe41-4d32-9c11-d7460cf11351\",\n" + " \"major\": 47400,\n" + " \"minor\": 45075\n" + " },\n" + " \"relationships\": {\n" + " \"parent\": {\n" + " \"data\": {\n" + " \"id\": \"67ffbe39-4951-4503-ac58-51819c20a95a\",\n" + " \"type\": \"beacon_nodes\"\n" + " }\n" + " },\n" + " \"children\": {\n" + " \"data\": [\n" + "\n" + " ]\n" + " }\n" + " }\n" + " }\n" + " ]\n" + "}"; }
package org.ndexbio.rest; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import javax.naming.InitialContext; import javax.naming.NamingException; import org.ndexbio.common.importexport.ImporterExporterEntry; import org.ndexbio.common.models.dao.postgresql.UserDAO; import org.ndexbio.model.exceptions.NdexException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import ch.qos.logback.classic.Level; public class Configuration { public static final String UPLOADED_NETWORKS_PATH_PROPERTY = "Uploaded-Networks-Path"; private static final String PROP_USE_AD_AUTHENTICATION = "USE_AD_AUTHENTICATION"; private static final String SOLR_URL = "SolrURL"; private static Configuration INSTANCE = null; private static final Logger _logger = LoggerFactory.getLogger(Configuration.class); private Properties _configurationProperties; private String dbURL; private static final String dbUserPropName = "NdexDBUsername"; private static final String dbPasswordPropName = "NdexDBDBPassword"; public static final String networkPostEdgeLimit = "NETWORK_POST_ELEMENT_LIMIT"; private static final String defaultSolrURL = "http://localhost:8983/solr"; private String solrURL; private String ndexSystemUser ; private String ndexSystemUserPassword; private String ndexRoot; private String hostURI ; private String restAPIPrefix ; private String networkStorePath; private String ndexNetworkCachePath; private boolean useADAuthentication ; private long serverElementLimit; private Map<String,ImporterExporterEntry> impExpTable; // Possible values for Log-Level are: // trace, debug, info, warn, error, all, off // If no Log-Level config parameter specified in /opt/ndex/conf/ndex.properties, or the value is // invalid/unrecognized, we set loglevel to 'info'. private Level logLevel; private Configuration(final String configPath) throws NamingException, NdexException, FileNotFoundException, IOException { // try { String configFilePath = configPath; if ( configFilePath == null) { InitialContext ic = new InitialContext(); configFilePath = (String) ic.lookup("java:comp/env/ndexConfigurationPath"); } if ( configFilePath == null) { _logger.error("ndexConfigurationPath is not defined in environement."); throw new NdexException("ndexConfigurationPath is not defined in environement."); } _logger.info("Loading ndex configuration from " + configFilePath); _configurationProperties = new Properties(); try (FileReader reader = new FileReader(configFilePath)) { _configurationProperties.load(reader); } dbURL = getRequiredProperty("NdexDBURL"); solrURL = getProperty(SOLR_URL); if ( solrURL == null) solrURL = defaultSolrURL; this.ndexSystemUser = getRequiredProperty("NdexSystemUser"); this.ndexSystemUserPassword = getRequiredProperty("NdexSystemUserPassword"); this.ndexRoot = getRequiredProperty("NdexRoot"); hostURI = getRequiredProperty("HostURI"); this.networkStorePath = this.ndexRoot + "/data/"; File file = new File (this.networkStorePath ); if (!file.exists()) { if ( ! file.mkdirs()) { throw new NdexException ("Server failed to create data store on path " + this.networkStorePath); } } String edgeLimit = getProperty(Configuration.networkPostEdgeLimit); if ( edgeLimit != null ) { try { serverElementLimit = Long.parseLong(edgeLimit); } catch( NumberFormatException e) { _logger.warn("[Invalid value in server property {}. Error: {}]", Configuration.networkPostEdgeLimit, e.getMessage()); // props.put("ServerPostEdgeLimit", "-1"); //defaultPostEdgeLimit); } } else serverElementLimit = -1; restAPIPrefix = getProperty("RESTAPIPrefix"); if ( restAPIPrefix == null) { restAPIPrefix = "/v2"; } setLogLevel(); // get AD authentication flag String useAd = getProperty(PROP_USE_AD_AUTHENTICATION); if (useAd != null && Boolean.parseBoolean(useAd)) { setUseADAuthentication(true); } else { setUseADAuthentication(false); } String userDefaultStorageQuota = getProperty("NETWORK_POST_ELEMENT_LIMIT"); if ( userDefaultStorageQuota != null) { Float limit = Float.valueOf(userDefaultStorageQuota); UserDAO.default_disk_quota = limit.floatValue() > 0 ? (limit.intValue() * 1000000000l) : -1; } // initialize the importer exporter table this.impExpTable = new HashMap<>(); String impExpConfigFile = this.ndexRoot + "/conf/ndex_importer_exporter.json"; try (FileInputStream i = new FileInputStream(impExpConfigFile)) { Iterator<ImporterExporterEntry> it = new ObjectMapper().readerFor(ImporterExporterEntry.class).readValues(i); while (it.hasNext()) { ImporterExporterEntry entry = it.next(); entry.setDirectoryName(this.ndexRoot + "/importer_exporter/" + entry.getDirectoryName()); List<String> cmdList = entry.getImporterCmd(); if (cmdList != null && !cmdList.isEmpty()) { String cmd = cmdList.get(0); if (!cmd.startsWith("/")) { cmd = entry.getDirectoryName() + "/" + cmd; cmdList.set(0, cmd); } } cmdList = entry.getExporterCmd(); if (cmdList != null && !cmdList.isEmpty()) { String cmd = cmdList.get(0); if (!cmd.startsWith("/")) { cmd = entry.getDirectoryName() + "/" + cmd; cmdList.set(0, cmd); } } impExpTable.put(entry.getName(), entry); } } catch (FileNotFoundException nfe) { _logger.warn("Importer/Exporter configuration not found at \"" + impExpConfigFile + "\". No import export function will be supported in this server." + "\nError: " + nfe.getMessage() ); } /* } catch (Exception e) { _logger.error("Failed to load the configuration file.", e); throw new NdexException ("Failed to load the configuration file. " + e.getMessage()); } */ } /* * This method reads Log-Level configuration parameter from /opt/ndex/conf/ndex.properties * and sets the log level. * In case Log-Level is not found in ndex.properties or value of Log-Level is invalid/unrecognized, * we set log level to 'info'. */ private void setLogLevel() { ch.qos.logback.classic.Logger rootLog = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); String result = _configurationProperties.getProperty("Log-Level"); if (result == null) { // if no Log-Level is specified in /opt/ndex/conf/ndex.properties, we set loglevel to info this.logLevel = Level.INFO; _logger.info("No 'Log-Level' parameter found in config ndex.properties file. Log level set to 'info'."); } else { this.logLevel = Level.toLevel(result.toUpperCase(), Level.INFO); } rootLog.setLevel(this.logLevel); } public String getRequiredProperty (String propertyName ) throws NdexException { String result = _configurationProperties.getProperty(propertyName); if ( result == null) { throw new NdexException ("Required property " + propertyName + " not found in configuration."); } return result; } public ImporterExporterEntry getImpExpEntry(String name){ return impExpTable.get(name); } public Collection<ImporterExporterEntry> getImporterExporters () { return impExpTable.values(); } public static Configuration getInstance() //throws NdexException { /*if ( INSTANCE == null) { try { INSTANCE = new Configuration(); } catch ( NamingException | IOException e) { throw new NdexException ( "Failed to get Configurtion Instance: " + e.getMessage(), e); } } */ return INSTANCE; } public static Configuration createInstance() throws NdexException { if ( INSTANCE == null) { try { INSTANCE = new Configuration(System.getenv("ndexConfigurationPath")); } catch ( NamingException | IOException e) { throw new NdexException ( "Failed to get Configurtion Instance: " + e.getMessage(), e); } } return INSTANCE; } /** * Added to enable testing. * @deprecated Dont use this is for testing only * @param configFilePath * @return Instance of {@link org.ndexbio.rest.Configuration} object * @throws NdexException */ public static Configuration reCreateInstance(final String configFilePath) throws NdexException{ try { INSTANCE = new Configuration(configFilePath); } catch ( NamingException | IOException e) { throw new NdexException ( "Failed to get Configurtion Instance: " + e.getMessage(), e); } return INSTANCE; } public String getProperty(String propertyName) { return _configurationProperties.getProperty(propertyName); } public void setProperty(String propertyName, String propertyValue) { _configurationProperties.setProperty(propertyName, propertyValue); } public String getDBURL () { return dbURL; } public String getDBUser() { return _configurationProperties.getProperty(dbUserPropName); } public String getDBPasswd () { return _configurationProperties.getProperty(dbPasswordPropName); } public String getSystmUserName() {return this.ndexSystemUser;} public String getSystemUserPassword () {return this.ndexSystemUserPassword;} public String getNdexRoot() {return this.ndexRoot;} public String getSolrURL() {return this.solrURL; } public Level getLogLevel() {return this.logLevel;} public String getHostURI () { return hostURI; } public long getServerElementLimit() { return serverElementLimit;} public String getRestAPIPrefix() {return restAPIPrefix;} public boolean getUseADAuthentication() { return useADAuthentication; } public void setUseADAuthentication(boolean useADAuthentication) { this.useADAuthentication = useADAuthentication; } public String getNdexNetworkCachePath() { return ndexNetworkCachePath; } }
package jenkins.plugins.git; import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.EnvVars; import hudson.Extension; import hudson.model.Item; import hudson.model.TaskListener; import hudson.plugins.git.BranchSpec; import hudson.plugins.git.GitException; import hudson.plugins.git.GitSCM; import hudson.plugins.git.GitTool; import hudson.plugins.git.UserRemoteConfig; import hudson.remoting.VirtualChannel; import hudson.scm.SCM; import hudson.security.ACL; import hudson.util.LogTaskListener; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.URISyntaxException; import java.util.Arrays; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.logging.Level; import java.util.logging.Logger; import jenkins.scm.api.SCMFile; import jenkins.scm.api.SCMFileSystem; import jenkins.scm.api.SCMHead; import jenkins.scm.api.SCMRevision; import jenkins.scm.api.SCMSource; import org.apache.commons.lang.StringUtils; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.URIish; import org.jenkinsci.plugins.gitclient.ChangelogCommand; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.gitclient.RepositoryCallback; /** * Base implementation of {@link SCMFileSystem}. * * @since 3.0.2 */ public class GitSCMFileSystem extends SCMFileSystem { /** * Our logger. */ private static final Logger LOGGER = Logger.getLogger(GitSCMFileSystem.class.getName()); private final String cacheEntry; private final TaskListener listener; private final String remote; private final String head; private final GitClient client; private final ObjectId commitId; /** * Constructor. * * @param client the client * @param remote the remote GIT URL * @param head identifier for the head commit to be referenced * @param rev the revision. * @throws IOException on I/O error * @throws InterruptedException on thread interruption */ protected GitSCMFileSystem(GitClient client, String remote, final String head, @CheckForNull AbstractGitSCMSource.SCMRevisionImpl rev) throws IOException, InterruptedException { super(rev); this.remote = remote; this.head = head; cacheEntry = AbstractGitSCMSource.getCacheEntry(remote); listener = new LogTaskListener(LOGGER, Level.FINER); this.client = client; commitId = rev == null ? invoke((Repository repository) -> repository.findRef(head).getObjectId()) : ObjectId.fromString(rev.getHash()); } @Override public AbstractGitSCMSource.SCMRevisionImpl getRevision() { return (AbstractGitSCMSource.SCMRevisionImpl) super.getRevision(); } @Override public long lastModified() throws IOException, InterruptedException { return invoke((Repository repository) -> { try (RevWalk walk = new RevWalk(repository)) { RevCommit commit = walk.parseCommit(commitId); return TimeUnit.SECONDS.toMillis(commit.getCommitTime()); } }); } @NonNull @Override public SCMFile getRoot() { return new GitSCMFile(this); } /*package*/ ObjectId getCommitId() { return commitId; } /** * Called with an {@link FSFunction} callback with a singleton repository * cache lock. * * An example usage might be: * * <pre>{@code * return fs.invoke(new GitSCMFileSystem.FSFunction<byte[]>() { * public byte[] invoke(Repository repository) throws IOException, InterruptedException { * Git activeRepo = getClonedRepository(repository); * File repoDir = activeRepo.getRepository().getDirectory().getParentFile(); * System.out.println("Repo cloned to: " + repoDir.getCanonicalPath()); * try { * File f = new File(repoDir, filePath); * if (f.canRead()) { * return IOUtils.toByteArray(new FileInputStream(f)); * } * return null; * } finally { * FileUtils.deleteDirectory(repoDir); * } * } * }); * }</pre> * * @param <V> return type * @param function callback executed with a locked repository * @return whatever you return from the provided function * @throws IOException if there is an I/O error * @throws InterruptedException if interrupted */ public <V> V invoke(final FSFunction<V> function) throws IOException, InterruptedException { Lock cacheLock = AbstractGitSCMSource.getCacheLock(cacheEntry); cacheLock.lock(); try { File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry); if (cacheDir == null || !cacheDir.isDirectory()) { throw new IOException("Closed"); } return client.withRepository((Repository repository, VirtualChannel virtualChannel) -> function.invoke(repository)); } finally { cacheLock.unlock(); } } @Override public boolean changesSince(@CheckForNull SCMRevision revision, @NonNull OutputStream changeLogStream) throws UnsupportedOperationException, IOException, InterruptedException { AbstractGitSCMSource.SCMRevisionImpl rev = getRevision(); if (rev == null ? revision == null : rev.equals(revision)) { // special case where somebody is asking one of two stupid questions: // 1. what has changed between the latest and the latest // 2. what has changed between the current revision and the current revision return false; } Lock cacheLock = AbstractGitSCMSource.getCacheLock(cacheEntry); cacheLock.lock(); try { File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry); if (cacheDir == null || !cacheDir.isDirectory()) { throw new IOException("Closed"); } boolean executed = false; ChangelogCommand changelog = client.changelog(); try (Writer out = new OutputStreamWriter(changeLogStream, "UTF-8")) { changelog.includes(commitId); ObjectId fromCommitId; if (revision instanceof AbstractGitSCMSource.SCMRevisionImpl) { fromCommitId = ObjectId.fromString(((AbstractGitSCMSource.SCMRevisionImpl) revision).getHash()); changelog.excludes(fromCommitId); } else { fromCommitId = null; } changelog.to(out).max(GitSCM.MAX_CHANGELOG).execute(); executed = true; return !commitId.equals(fromCommitId); } catch (GitException ge) { throw new IOException("Unable to retrieve changes", ge); } finally { if (!executed) { changelog.abort(); } changeLogStream.close(); } } finally { cacheLock.unlock(); } } /** * Simple callback that is used with * {@link #invoke(jenkins.plugins.git.GitSCMFileSystem.FSFunction)} * in order to provide a locked view of the Git repository * @param <V> the return type */ public interface FSFunction<V> { /** * Called with a lock on the repository in order to perform some * operations that might result in changes and necessary re-indexing * @param repository the bare git repository * @return value to return from {@link #invoke(jenkins.plugins.git.GitSCMFileSystem.FSFunction)} * @throws IOException if there is an I/O error * @throws InterruptedException if interrupted */ V invoke(Repository repository) throws IOException, InterruptedException; } @Extension(ordinal = Short.MIN_VALUE) public static class BuilderImpl extends SCMFileSystem.Builder { @Override public boolean supports(SCM source) { return source instanceof GitSCM && ((GitSCM) source).getUserRemoteConfigs().size() == 1 && ((GitSCM) source).getBranches().size() == 1 && ( ((GitSCM) source).getBranches().get(0).getName().matches( "^((\\Q" + Constants.R_HEADS + "\\E.*)|([^/]+)|(\\*/[^/*]+(/[^/*]+)*))$" ) || ((GitSCM) source).getBranches().get(0).getName().matches( "^((\\Q" + Constants.R_TAGS + "\\E.*)|([^/]+)|(\\*/[^/*]+(/[^/*]+)*))$" ) ); // we only support where the branch spec is obvious } @Override public boolean supports(SCMSource source) { return source instanceof AbstractGitSCMSource; } @Override public SCMFileSystem build(@NonNull Item owner, @NonNull SCM scm, @CheckForNull SCMRevision rev) throws IOException, InterruptedException { if (rev != null && !(rev instanceof AbstractGitSCMSource.SCMRevisionImpl)) { return null; } TaskListener listener = new LogTaskListener(LOGGER, Level.FINE); GitSCM gitSCM = (GitSCM) scm; UserRemoteConfig config = gitSCM.getUserRemoteConfigs().get(0); BranchSpec branchSpec = gitSCM.getBranches().get(0); String remote = config.getUrl(); String cacheEntry = AbstractGitSCMSource.getCacheEntry(remote); Lock cacheLock = AbstractGitSCMSource.getCacheLock(cacheEntry); cacheLock.lock(); try { File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry); Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir); GitTool tool = gitSCM.resolveGitTool(listener); if (tool != null) { git.using(tool.getGitExe()); } GitClient client = git.getClient(); String credentialsId = config.getCredentialsId(); if (credentialsId != null) { StandardCredentials credential = CredentialsMatchers.firstOrNull( CredentialsProvider.lookupCredentials( StandardUsernameCredentials.class, owner, ACL.SYSTEM, URIRequirementBuilder.fromUri(remote).build() ), CredentialsMatchers.allOf( CredentialsMatchers.withId(credentialsId), GitClient.CREDENTIALS_MATCHER ) ); client.addDefaultCredentials(credential); CredentialsProvider.track(owner, credential); } if (!client.hasGitRepo()) { listener.getLogger().println("Creating git repository in " + cacheDir); client.init(); } String remoteName = StringUtils.defaultIfBlank(config.getName(), Constants.DEFAULT_REMOTE_NAME); listener.getLogger().println("Setting " + remoteName + " to " + remote); client.setRemoteUrl(remoteName, remote); listener.getLogger().println("Fetching & pruning " + remoteName + "..."); URIish remoteURI = null; try { remoteURI = new URIish(remoteName); } catch (URISyntaxException ex) { listener.getLogger().println("URI syntax exception for '" + remoteName + "' " + ex); } String prefix = Constants.R_HEADS; if(branchSpec.getName().startsWith(Constants.R_TAGS)){ prefix = Constants.R_TAGS; } String headName; if (rev != null) { headName = rev.getHead().getName(); } else { if (branchSpec.getName().startsWith(prefix)){ headName = branchSpec.getName().substring(prefix.length()); } else if (branchSpec.getName().startsWith("*/")) { headName = branchSpec.getName().substring(2); } else { headName = branchSpec.getName(); } } client.fetch_().prune().from(remoteURI, Arrays .asList(new RefSpec( "+" + prefix + headName + ":" + Constants.R_REMOTES + remoteName + "/" + headName))).execute(); listener.getLogger().println("Done."); return new GitSCMFileSystem(client, remote, Constants.R_REMOTES + remoteName + "/" +headName, (AbstractGitSCMSource.SCMRevisionImpl) rev); } finally { cacheLock.unlock(); } } @Override public SCMFileSystem build(@NonNull SCMSource source, @NonNull SCMHead head, @CheckForNull SCMRevision rev) throws IOException, InterruptedException { if (rev != null && !(rev instanceof AbstractGitSCMSource.SCMRevisionImpl)) { return null; } TaskListener listener = new LogTaskListener(LOGGER, Level.FINE); AbstractGitSCMSource gitSCMSource = (AbstractGitSCMSource) source; GitSCMBuilder<?> builder = gitSCMSource.newBuilder(head, rev); String cacheEntry = gitSCMSource.getCacheEntry(); Lock cacheLock = AbstractGitSCMSource.getCacheLock(cacheEntry); cacheLock.lock(); try { File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry); Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir); GitTool tool = gitSCMSource.resolveGitTool(builder.gitTool(), listener); if (tool != null) { git.using(tool.getGitExe()); } GitClient client = git.getClient(); client.addDefaultCredentials(gitSCMSource.getCredentials()); if (!client.hasGitRepo()) { listener.getLogger().println("Creating git repository in " + cacheDir); client.init(); } String remoteName = builder.remoteName(); listener.getLogger().println("Setting " + remoteName + " to " + gitSCMSource.getRemote()); client.setRemoteUrl(remoteName, gitSCMSource.getRemote()); listener.getLogger().println("Fetching & pruning " + remoteName + "..."); URIish remoteURI = null; try { remoteURI = new URIish(remoteName); } catch (URISyntaxException ex) { listener.getLogger().println("URI syntax exception for '" + remoteName + "' " + ex); } client.fetch_().prune().from(remoteURI, builder.asRefSpecs()).execute(); listener.getLogger().println("Done."); return new GitSCMFileSystem(client, gitSCMSource.getRemote(), Constants.R_REMOTES+remoteName+"/"+head.getName(), (AbstractGitSCMSource.SCMRevisionImpl) rev); } finally { cacheLock.unlock(); } } } }
package org.oakgp.mutate; import org.oakgp.NodeEvolver; import org.oakgp.PrimitiveSet; import org.oakgp.function.Function; import org.oakgp.node.FunctionNode; import org.oakgp.node.Node; import org.oakgp.selector.NodeSelector; import org.oakgp.util.Random; /** Performs mutation (also known as node replacement mutation). */ public final class PointMutation implements NodeEvolver { private final Random random; private final PrimitiveSet primitiveSet; public PointMutation(Random random, PrimitiveSet primitiveSet) { this.random = random; this.primitiveSet = primitiveSet; } @Override public Node evolve(NodeSelector selector) { Node root = selector.next(); int mutationPoint = random.nextInt(root.getNodeCount()); // TODO avoid selecting root node? return root.replaceAt(mutationPoint, node -> { if (node instanceof FunctionNode) { FunctionNode functionNode = (FunctionNode) node; Function function = primitiveSet.nextAlternativeFunction(functionNode.getFunction()); return new FunctionNode(function, functionNode.getArguments()); } else { return primitiveSet.nextAlternativeTerminal(node); } }); } }
package me.unrealization.jeeves.modules; import java.io.IOException; import java.text.DecimalFormat; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.xml.sax.SAXException; import me.unrealization.jeeves.bot.Jeeves; import me.unrealization.jeeves.bot.MessageQueue; import me.unrealization.jeeves.dataLists.EdsmUserList; import me.unrealization.jeeves.jsonModels.EdsmModels; import me.unrealization.jeeves.apis.EdsmApi; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.handle.obj.IUser; import sx.blah.discord.handle.obj.Permissions; import me.unrealization.jeeves.interfaces.BotCommand; import me.unrealization.jeeves.interfaces.BotModule; public class Edsm extends BotModule { private static EdsmUserList edsmUserList = null; public Edsm() throws ParserConfigurationException, SAXException { this.version = "0.10.0"; this.commandList = new String[18]; this.commandList[0] = "GetUseEdsmBetaServer"; this.commandList[1] = "SetUseEdsmBetaServer"; this.commandList[2] = "Register"; this.commandList[3] = "Unregister"; this.commandList[4] = "EdsmUser"; this.commandList[5] = "EDStatus"; this.commandList[6] = "Locate"; this.commandList[7] = "SysCoords"; this.commandList[8] = "CmdrCoords"; this.commandList[9] = "Distance"; this.commandList[10] = "SystemSphere"; this.commandList[11] = "SystemCube"; this.commandList[12] = "Route"; this.commandList[13] = "NextJump"; this.commandList[14] = "SystemInfo"; this.commandList[15] = "BodyInfo"; this.commandList[16] = "StationInfo"; this.commandList[17] = "FactionInfo"; this.defaultConfig.put("edsmUseBetaServer", "1"); Edsm.edsmUserList = new EdsmUserList(); } private static String sanitizeString(String input) { String output = input.replace(" ", "%20").replace("+", "%2B").replace("'", "%27"); return output; } /*private static String desanitizeString(String input) { String output = input.replace("%20", " ").replace("%2B", "+").replace("%27", "'"); return output; }*/ private static String calculateDistance(EdsmModels.SystemInfo.Coordinates leftCoords, EdsmModels.SystemInfo.Coordinates rightCoords) { double xDistSqr = Math.pow(Double.parseDouble(leftCoords.x) - Double.parseDouble(rightCoords.x), 2); double yDistSqr = Math.pow(Double.parseDouble(leftCoords.y) - Double.parseDouble(rightCoords.y), 2); double zDistSqr = Math.pow(Double.parseDouble(leftCoords.z) - Double.parseDouble(rightCoords.z), 2); double distance = Math.sqrt(xDistSqr + yDistSqr + zDistSqr); String distanceString = new DecimalFormat("#.##").format(distance); return distanceString; } private static EdsmApi getApiObject(long serverId) { String useBetaServer = (String)Jeeves.serverConfig.getValue(serverId, "edsmUseBetaServer"); boolean useBeta = useBetaServer.equals("1"); EdsmApi edsmApi = new EdsmApi(); edsmApi.setUseBetaServer(useBeta); return edsmApi; } public static class GetUseEdsmBetaServer extends BotCommand { @Override public String getHelp() { String output = "Check if the bot uses the EDSM beta server."; return output; } @Override public String getParameters() { return null; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String argumentString) { String useBetaServer = (String)Jeeves.serverConfig.getValue(message.getGuild().getLongID(), "edsmUseBetaServer"); if (useBetaServer.equals("0") == true) { MessageQueue.sendMessage(message.getChannel(), "The bot uses the EDSM live server."); } else { MessageQueue.sendMessage(message.getChannel(), "The bot uses the EDSM beta server."); } } } public static class SetUseEdsmBetaServer extends BotCommand { @Override public String getHelp() { String output = "Set whether or not the bot should use the EDSM beta server."; return output; } @Override public String getParameters() { String output = "<1|0>"; return output; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String useBetaServer) { if ((useBetaServer.equals("0") == false) && (useBetaServer.equals("1") == false)) { MessageQueue.sendMessage(message.getChannel(), "Invalid value"); return; } Jeeves.serverConfig.setValue(message.getGuild().getLongID(), "edsmUseBetaServer", useBetaServer); try { Jeeves.serverConfig.saveConfig(); } catch (ParserConfigurationException | TransformerException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "Cannot store the setting."); return; } if (useBetaServer.equals("0") == true) { MessageQueue.sendMessage(message.getChannel(), "The bot will now use the EDSM live server."); } else { MessageQueue.sendMessage(message.getChannel(), "The bot will now use the EDSM beta server."); } } } public static class Register extends BotCommand { @Override public String getHelp() { String output = "Register your EDSM-username with the bot for convenience on some EDSM commands."; return output; } @Override public String getParameters() { String output = "<edsmUserName>"; return output; } @Override public void execute(IMessage message, String edsmUserName) { if (edsmUserName.isEmpty() == true) { MessageQueue.sendMessage(message.getChannel(), "You need to provide an EDSM username"); return; } String userIdString = Long.toString(message.getAuthor().getLongID()); Edsm.edsmUserList.setValue(userIdString, edsmUserName); try { Edsm.edsmUserList.saveConfig(); } catch (ParserConfigurationException | TransformerException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "Cannot store the setting."); return; } MessageQueue.sendMessage(message.getChannel(), "Your EDSM username has been set to: " + edsmUserName); } } public static class Unregister extends BotCommand { @Override public String getHelp() { String output = "Clear your EDSM username from the bots register."; return output; } @Override public String getParameters() { return null; } @Override public void execute(IMessage message, String argumentString) { String userIdString = Long.toString(message.getAuthor().getLongID()); if (Edsm.edsmUserList.hasKey(userIdString) == false) { MessageQueue.sendMessage(message.getChannel(), "You have not registered an EDSM username."); return; } Edsm.edsmUserList.removeValue(userIdString); MessageQueue.sendMessage(message.getChannel(), "Your EDSM username has been removed."); } } public static class EdsmUser extends BotCommand { @Override public String getHelp() { String output = "Get the EDSM username of the given user or yourself."; return output; } @Override public String getParameters() { String output = "[username]"; return output; } @Override public void execute(IMessage message, String userName) { IUser user; if (userName.isEmpty() == true) { user = message.getAuthor(); } else { user = Jeeves.findUser(message.getGuild(), userName); if (user == null) { MessageQueue.sendMessage(message.getChannel(), "Cannot find the user " + userName); return; } } String userIdString = Long.toString(user.getLongID()); if (Edsm.edsmUserList.hasKey(userIdString) == false) { if (userName.isEmpty() == true) { MessageQueue.sendMessage(message.getChannel(), "You have not registered an EDSM username."); } else { MessageQueue.sendMessage(message.getChannel(), user.getName() + " has not registered an EDSM username."); } return; } String edsmUserName = (String)Edsm.edsmUserList.getValue(userIdString); if (userName.isEmpty() == true) { MessageQueue.sendMessage(message.getChannel(), "Your EDSM username is: " + edsmUserName); } else { MessageQueue.sendMessage(message.getChannel(), "The EDSM username for " + user.getName() + " is: " + edsmUserName); } } } public static class EDStatus extends BotCommand { @Override public String getHelp() { String output = "Check the Elite: Dangerous server status."; return output; } @Override public String getParameters() { return null; } @Override public void execute(IMessage message, String argumentString) { EdsmApi edsmApi = Edsm.getApiObject(message.getGuild().getLongID()); EdsmModels.EDStatus data; try { data = edsmApi.getEDStatus(); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } MessageQueue.sendMessage(message.getChannel(), "Elite: Dangerous Server Status: " + data.message + "\nLast Update: " + data.lastUpdate); } } public static class Locate extends BotCommand { @Override public String getHelp() { String output = "Locate the given commander, or yourself."; return output; } @Override public String getParameters() { String output = "[commander]"; return output; } @Override public void execute(IMessage message, String commanderName) { if (commanderName.isEmpty() == true) { String userIdString = Long.toString(message.getAuthor().getLongID()); if (Edsm.edsmUserList.hasKey(userIdString) == false) { MessageQueue.sendMessage(message.getChannel(), "You need to provide a commander name or register your EDSM username."); return; } commanderName = (String)Edsm.edsmUserList.getValue(userIdString); } EdsmApi edsmApi = Edsm.getApiObject(message.getGuild().getLongID()); EdsmModels.CommanderLocation data; try { data = edsmApi.getCommanderLocation(Edsm.sanitizeString(commanderName)); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } String output; if (data.system != null) { output = commanderName + " was last seen in " + data.system; if (data.date != null) { output += " at " + data.date; } } else { switch (data.msgnum) { case "100": output = commanderName + " cannot be located."; break; case "203": output = commanderName + " does not seem to be using EDSM."; break; default: output = data.msg; break; } } MessageQueue.sendMessage(message.getChannel(), output); } } public static class SysCoords extends BotCommand { @Override public String getHelp() { String output = "Get the coordinates of the given system."; return output; } @Override public String getParameters() { String output = "<system>"; return output; } @Override public void execute(IMessage message, String systemName) { if (systemName.isEmpty() == true) { MessageQueue.sendMessage(message.getChannel(), "You need to provide a system name."); return; } EdsmApi edsmApi = Edsm.getApiObject(message.getGuild().getLongID()); EdsmModels.SystemInfo data; try { data = edsmApi.getSystemInfo(Edsm.sanitizeString(systemName)); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (data == null) { MessageQueue.sendMessage(message.getChannel(), systemName + " cannot be found on EDSM."); return; } String output = "System: " + data.name + " [ " + data.coords.x + " : " + data.coords.y + " : " + data.coords.z + " ]"; MessageQueue.sendMessage(message.getChannel(), output); } } public static class CmdrCoords extends BotCommand { @Override public String getHelp() { String output = "Get the coordinates of the system the given commander is in."; return output; } @Override public String getParameters() { String output = "[commander]"; return output; } @Override public void execute(IMessage message, String commanderName) { if (commanderName.isEmpty() == true) { String userIdString = Long.toString(message.getAuthor().getLongID()); if (Edsm.edsmUserList.hasKey(userIdString) == false) { MessageQueue.sendMessage(message.getChannel(), "You need to provide a commander name or register your ESDM username."); return; } commanderName = (String)Edsm.edsmUserList.getValue(userIdString); } EdsmApi edsmApi = Edsm.getApiObject(message.getGuild().getLongID()); EdsmModels.CommanderLocation data; try { data = edsmApi.getCommanderLocation(Edsm.sanitizeString(commanderName)); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } String output; if (data.system != null) { output = "System: " + data.system + " [ " + data.coordinates.x + " : " + data.coordinates.y + " : " + data.coordinates.z + " ]"; } else { switch (data.msgnum) { case "100": output = commanderName + " cannot be located."; break; case "203": output = commanderName + " does not seem to be using EDSM."; break; default: output = data.msg; break; } } MessageQueue.sendMessage(message.getChannel(), output); } } public static class Distance extends BotCommand { @Override public String getHelp() { String output = "Calculate the distance between two systems or commanders."; return output; } @Override public String getParameters() { String output = "[commander|system] : [commander|system]"; return output; } @Override public void execute(IMessage message, String argumentString) { String[] arguments = Jeeves.splitArguments(argumentString); String[] searchNames = new String[2]; for (int index = 0; index < searchNames.length; index++) { try { searchNames[index] = arguments[index]; } catch (ArrayIndexOutOfBoundsException e) { //Jeeves.debugException(e); searchNames[index] = ""; } if (searchNames[index].isEmpty() == true) { String userIdString = Long.toString(message.getAuthor().getLongID()); if (Edsm.edsmUserList.hasKey(userIdString) == false) { MessageQueue.sendMessage(message.getChannel(), "You need to provide a commander or system name or register your EDSM username."); return; } searchNames[index] = (String)Edsm.edsmUserList.getValue(userIdString); } } EdsmApi edsmApi = Edsm.getApiObject(message.getGuild().getLongID()); EdsmModels.SystemInfo systemInfo[] = new EdsmModels.SystemInfo[2]; for (int index = 0; index < searchNames.length; index++) { EdsmModels.SystemInfo systemData; try { systemData = edsmApi.getSystemInfo(Edsm.sanitizeString(searchNames[index])); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (systemData != null) { systemInfo[index] = systemData; continue; } EdsmModels.CommanderLocation cmdrData; try { cmdrData = edsmApi.getCommanderLocation(searchNames[index]); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (cmdrData == null) { MessageQueue.sendMessage(message.getChannel(), searchNames[index] + " cannot be found on EDSM."); return; } if (cmdrData.system == null) { switch (cmdrData.msgnum) { case "100": MessageQueue.sendMessage(message.getChannel(), searchNames[index] + " cannot be located."); return; case "203": MessageQueue.sendMessage(message.getChannel(), searchNames[index] + " does not seem to be using EDSM."); return; default: MessageQueue.sendMessage(message.getChannel(), cmdrData.msg); return; } } systemInfo[index] = new EdsmModels.SystemInfo(); systemInfo[index].name = cmdrData.system; systemInfo[index].coords = cmdrData.coordinates; } String distance = Edsm.calculateDistance(systemInfo[0].coords, systemInfo[1].coords); String output = "The distance between " + systemInfo[0].name + " and " + systemInfo[1].name + " is " + distance + " ly."; MessageQueue.sendMessage(message.getChannel(), output); } } public static class SystemSphere extends BotCommand { @Override public String getHelp() { String output = "Get a list of systems in a sphere centered around the given system."; return output; } @Override public String getParameters() { String output = "<system> [ : <radius> ]"; return output; } @Override public void execute(IMessage message, String argumentString) { String[] arguments = Jeeves.splitArguments(argumentString); if ((arguments.length == 0) || (arguments[0].isEmpty() == true)) { MessageQueue.sendMessage(message.getChannel(), "You need to provide a system name."); return; } String systemName = arguments[0]; String radius = null; if (arguments.length == 2) { radius = arguments[1]; try { Float.parseFloat(radius); } catch (NumberFormatException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "Invalid value for radius."); return; } } EdsmApi edsmApi = Edsm.getApiObject(message.getGuild().getLongID()); EdsmModels.SystemInfo centerData; try { centerData = edsmApi.getSystemInfo(Edsm.sanitizeString(systemName)); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (centerData == null) { MessageQueue.sendMessage(message.getChannel(), systemName + " cannot be found on EDSM."); } EdsmModels.SystemInfo[] data; try { data = edsmApi.getSystemSphere(Edsm.sanitizeString(systemName), radius); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (data.length == 1) { MessageQueue.sendMessage(message.getChannel(), "No systems found near " + systemName); return; } String output = ""; for (int index = 0; index < data.length; index++) { if (data[index].name.toLowerCase().equals(systemName.toLowerCase())) { continue; } output += data[index].name + " (Distance: " + Edsm.calculateDistance(centerData.coords, data[index].coords) + " ly)\n"; } MessageQueue.sendMessage(message.getChannel(), output); } } public static class SystemCube extends BotCommand { @Override public String getHelp() { String output = "Get a list of systems in a cube centered around the given system."; return output; } @Override public String getParameters() { String output = "<system> [ : <size> ]"; return output; } @Override public void execute(IMessage message, String argumentString) { String[] arguments = Jeeves.splitArguments(argumentString); if ((arguments.length == 0) || (arguments[0].isEmpty() == true)) { MessageQueue.sendMessage(message.getChannel(), "You need to provide a system name."); return; } String systemName = arguments[0]; String size = null; if (arguments.length == 2) { size = arguments[1]; try { Float.parseFloat(size); } catch (NumberFormatException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "Invalid value for size."); return; } } EdsmApi edsmApi = Edsm.getApiObject(message.getGuild().getLongID()); EdsmModels.SystemInfo centerData; try { centerData = edsmApi.getSystemInfo(Edsm.sanitizeString(systemName)); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (centerData == null) { MessageQueue.sendMessage(message.getChannel(), systemName + " cannot be found on EDSM."); } EdsmModels.SystemInfo[] data; try { data = edsmApi.getSystemCube(Edsm.sanitizeString(systemName), size); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (data.length == 1) { MessageQueue.sendMessage(message.getChannel(), "No systems found near " + systemName); return; } String output = ""; for (int index = 0; index < data.length; index++) { if (data[index].name.toLowerCase().equals(systemName.toLowerCase())) { continue; } output += data[index].name + " (Distance: " + Edsm.calculateDistance(centerData.coords, data[index].coords) + " ly)\n"; } MessageQueue.sendMessage(message.getChannel(), output); } } public static class Route extends BotCommand { @Override public String getHelp() { String output = "Calculate the route from origin to destination at the given jumprange."; return output; } @Override public String getParameters() { String output = "<origin> : <destination> : <jumprange>"; return output; } @Override public void execute(IMessage message, String argumentString) { String[] arguments = Jeeves.splitArguments(argumentString); if (arguments.length < 3) { MessageQueue.sendMessage(message.getChannel(), "Insufficient amount of parameters.\n" + this.getParameters()); return; } String origin = arguments[0]; String destination = arguments[1]; String jumpRange = arguments[2]; try { Float.parseFloat(jumpRange); } catch (NumberFormatException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "Invalid value for jump range."); return; } EdsmApi edsmApi = Edsm.getApiObject(message.getGuild().getLongID()); EdsmModels.SystemInfo originInfo; try { originInfo = edsmApi.getSystemInfo(Edsm.sanitizeString(origin)); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (originInfo == null) { MessageQueue.sendMessage(message.getChannel(), origin + " cannot be found on EDSM."); return; } EdsmModels.SystemInfo destinationInfo; try { destinationInfo = edsmApi.getSystemInfo(Edsm.sanitizeString(destination)); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (destinationInfo == null) { MessageQueue.sendMessage(message.getChannel(), destination + " cannot be found on EDSM."); } EdsmModels.SystemInfo currentOriginInfo = originInfo; String currentDistanceString = Edsm.calculateDistance(originInfo.coords, destinationInfo.coords); float currentDistance = Float.parseFloat(currentDistanceString); int jumpNo = 0; String output = Integer.toString(jumpNo) + ": " + originInfo.name + " (Jump Distance: 0 ly) (Distance to " + destinationInfo.name + ": " + currentDistanceString + " ly)\n"; boolean abortRouting = false; while ((currentOriginInfo.name.equals(destinationInfo.name) == false) && (abortRouting == false)) { EdsmModels.SystemInfo[] systemBubble; try { systemBubble = edsmApi.getSystemSphere(Edsm.sanitizeString(currentOriginInfo.name), jumpRange); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (systemBubble == null) { output += "EDSM communication error.\n"; abortRouting = true; continue; } EdsmModels.SystemInfo nextJump = null; float nextJumpDistance = Float.POSITIVE_INFINITY; for (int index = 0; index < systemBubble.length; index++) { if (currentOriginInfo.name.equals(systemBubble[index].name) == true) { continue; } String distanceString = Edsm.calculateDistance(systemBubble[index].coords, destinationInfo.coords); float distance = Float.parseFloat(distanceString); if (distance >= currentDistance) { continue; } if ((nextJump != null) && (distance >= nextJumpDistance)) { continue; } nextJump = systemBubble[index]; nextJumpDistance = distance; } if (nextJump == null) { output += "Unable to find the next jump.\n"; abortRouting = true; continue; } String jumpDistance = Edsm.calculateDistance(currentOriginInfo.coords, nextJump.coords); currentOriginInfo = nextJump; currentDistance = nextJumpDistance; jumpNo++; output += Integer.toString(jumpNo) + ": " + currentOriginInfo.name + " (Jump Distance: " + jumpDistance + " ly) (Distance to " + destinationInfo.name + ": " + Float.toString(currentDistance) + " ly)\n"; } if (abortRouting == false) { output = "Total number of jumps: " + jumpNo + "\n" + output; } MessageQueue.sendMessage(message.getChannel(), output); } } public static class NextJump extends BotCommand { @Override public String getHelp() { String output = "Find the next jump from one system to another for the given jump range."; return output; } @Override public String getParameters() { String output = "<origin> : <destination> : <jumprange>"; return output; } @Override public void execute(IMessage message, String argumentString) { String[] arguments = Jeeves.splitArguments(argumentString); if (arguments.length < 3) { MessageQueue.sendMessage(message.getChannel(), "Insufficient amount of parameters.\n" + this.getParameters()); return; } String origin = arguments[0]; String destination = arguments[1]; String jumpRange = arguments[2]; try { Float.parseFloat(jumpRange); } catch (NumberFormatException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "Invalid value for jump range."); return; } EdsmApi edsmApi = Edsm.getApiObject(message.getGuild().getLongID()); EdsmModels.SystemInfo originInfo; try { originInfo = edsmApi.getSystemInfo(Edsm.sanitizeString(origin)); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (originInfo == null) { MessageQueue.sendMessage(message.getChannel(), origin + " cannot be found on EDSM."); return; } EdsmModels.SystemInfo destinationInfo; try { destinationInfo = edsmApi.getSystemInfo(Edsm.sanitizeString(destination)); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (destinationInfo == null) { MessageQueue.sendMessage(message.getChannel(), destination + " cannot be found on EDSM."); } EdsmModels.SystemInfo[] systemBubble; try { systemBubble = edsmApi.getSystemSphere(Edsm.sanitizeString(originInfo.name), jumpRange); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (systemBubble == null) { MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } String distanceString = Edsm.calculateDistance(originInfo.coords, destinationInfo.coords); float originDistance = Float.parseFloat(distanceString); EdsmModels.SystemInfo nextJump = null; float nextJumpDistance = Float.POSITIVE_INFINITY; for (int index = 0; index < systemBubble.length; index++) { if (originInfo.name.equals(systemBubble[index].name) == true) { continue; } distanceString = Edsm.calculateDistance(systemBubble[index].coords, destinationInfo.coords); float distance = Float.parseFloat(distanceString); if ((distance >= originDistance) || ((nextJump != null) && (distance >= nextJumpDistance))) { continue; } nextJump = systemBubble[index]; nextJumpDistance = distance; } if (nextJump == null) { MessageQueue.sendMessage(message.getChannel(), "Unable to find the next jump."); return; } String jumpDistance = Edsm.calculateDistance(originInfo.coords, nextJump.coords); String output = nextJump.name + " (Jump Distance: " + jumpDistance + " ly) (Distance to " + destinationInfo.name + ": " + Float.toString(nextJumpDistance) + " ly)\n"; MessageQueue.sendMessage(message.getChannel(), output); } } public static class SystemInfo extends BotCommand { @Override public String getHelp() { String output = "Get information about the given system."; return output; } @Override public String getParameters() { String output = "<system>"; return output; } @Override public void execute(IMessage message, String systemName) { if (systemName.isEmpty() == true) { MessageQueue.sendMessage(message.getChannel(), "You need to supply as system name."); return; } EdsmApi edsmApi = Edsm.getApiObject(message.getGuild().getLongID()); EdsmModels.SystemInfo data; try { data = edsmApi.getSystemInfo(Edsm.sanitizeString(systemName)); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (data == null) { MessageQueue.sendMessage(message.getChannel(), systemName + " cannot be found on EDSM."); } String output = "System: " + data.name + "\n"; output += "Galactic Coordinates: X: " + data.coords.x + " Y: " + data.coords.y + " Z: " + data.coords.z + "\n"; if (data.requirePermit.equals("true") == true) { output += "Required Permit: " + data.permitName + "\n"; } if (data.primaryStar != null) { output += "\n"; output += "Primary Star\n"; output += "Name: " + data.primaryStar.name + "\n"; output += "Type: " + data.primaryStar.type + "\n"; output += "Is Scoopable: "; if (data.primaryStar.isScoopable.equals("true") == true) { output += "yes"; } else { output += "no"; } } MessageQueue.sendMessage(message.getChannel(), output); } } public static class BodyInfo extends BotCommand { @Override public String getHelp() { String output = "Get information on the bodies, or a specific body, in the given system."; return output; } @Override public String getParameters() { String output = "<system> [ : <body> ]"; return output; } @Override public void execute(IMessage message, String argumentString) { String[] arguments = Jeeves.splitArguments(argumentString); if ((arguments.length == 0) || (arguments[0].isEmpty() == true)) { MessageQueue.sendMessage(message.getChannel(), "You need to provide a system name."); return; } EdsmApi edsmApi = Edsm.getApiObject(message.getGuild().getLongID()); String systemName = arguments[0]; String bodyName = null; if (arguments.length == 2) { bodyName = arguments[1]; } EdsmModels.SystemBodies data; try { data = edsmApi.getSystemBodies(Edsm.sanitizeString(systemName)); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (data == null) { MessageQueue.sendMessage(message.getChannel(), systemName + " cannot be found on EDSM."); return; } String output = "System: " + data.name + "\n"; boolean bodyNotFound = true; for (int index = 0; index < data.bodies.length; index++) { if (bodyName != null) { if ((data.bodies[index].name.toLowerCase().equals(bodyName.toLowerCase()) == false) && (data.bodies[index].name.toLowerCase().equals(systemName.toLowerCase() + " " + bodyName.toLowerCase()) == false)) { continue; } else { bodyNotFound = false; } } output += "\n"; output += "Body: " + data.bodies[index].name + "\n"; if (data.bodies[index].type.equals("Star")) { output += "Type: " + data.bodies[index].subType + "\n"; } else { output += "Type: " + data.bodies[index].type + " (" + data.bodies[index].subType + ")\n"; } output += "Distance from Arrival: " + data.bodies[index].distanceToArrival + " ls\n"; if (bodyName != null) { //add all the details! } } if ((bodyName != null) && (bodyNotFound == true)) { MessageQueue.sendMessage(message.getChannel(), "Cannot find the body " + bodyName); return; } MessageQueue.sendMessage(message.getChannel(), output); } } public static class StationInfo extends BotCommand { @Override public String getHelp() { String output = "Get information on the stations, or a specific station, in the given system."; return output; } @Override public String getParameters() { String output = "<system> [ : <station> ]"; return output; } @Override public void execute(IMessage message, String argumentString) { String[] arguments = Jeeves.splitArguments(argumentString); if ((arguments.length == 0) || (arguments[0].isEmpty() == true)) { MessageQueue.sendMessage(message.getChannel(), "You need to provide a system name."); return; } EdsmApi edsmApi = Edsm.getApiObject(message.getGuild().getLongID()); String systemName = arguments[0]; String stationName = null; if (arguments.length == 2) { stationName = arguments[1]; } EdsmModels.SystemStations data; try { data = edsmApi.getSystemStations(Edsm.sanitizeString(systemName)); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (data == null) { MessageQueue.sendMessage(message.getChannel(), systemName + " cannot be found on EDSM."); return; } String output = "System: " + data.name + "\n"; boolean stationNotFound = true; for (int index = 0; index < data.stations.length; index++) { if (stationName != null) { if (data.stations[index].name.toLowerCase().equals(stationName.toLowerCase()) == false) { continue; } else { stationNotFound = false; } } output += "\n"; output += "Station: " + data.stations[index].name + "\n"; output += "Type: " + data.stations[index].type + "\n"; if (stationName != null) { //add all the details! } } if ((stationName != null) && (stationNotFound == true)) { MessageQueue.sendMessage(message.getChannel(), "Cannot find the station " + stationName); return; } MessageQueue.sendMessage(message.getChannel(), output); } } public static class FactionInfo extends BotCommand { @Override public String getHelp() { String output = "Get information about the factions, or a specific faction, in the given system."; return output; } @Override public String getParameters() { String output = "<system> [ : <faction> ]"; return output; } @Override public void execute(IMessage message, String argumentString) { String[] arguments = Jeeves.splitArguments(argumentString); if ((arguments.length == 0) || (arguments[0].isEmpty() == true)) { MessageQueue.sendMessage(message.getChannel(), "You need to provide a system name."); return; } EdsmApi edsmApi = Edsm.getApiObject(message.getGuild().getLongID()); String systemName = arguments[0]; String factionName = null; if (arguments.length == 2) { factionName = arguments[1]; } EdsmModels.SystemFactions data; try { data = edsmApi.getSystemFactions(Edsm.sanitizeString(systemName)); } catch (IOException e) { Jeeves.debugException(e); MessageQueue.sendMessage(message.getChannel(), "EDSM communication error."); return; } if (data == null) { MessageQueue.sendMessage(message.getChannel(), systemName + " cannot be found on EDSM."); return; } String output = "System: " + data.name + "\n"; boolean factionNotFound = true; for (int index = 0; index < data.factions.length; index++) { if (factionName != null) { if (data.factions[index].name.toLowerCase().equals(factionName.toLowerCase()) == false) { continue; } else { factionNotFound = false; } } output += "\n"; output += "Faction: " + data.factions[index].name + "\n"; try { float influence = Float.parseFloat(data.factions[index].influence) * 100; String influenceString = new DecimalFormat("#.##").format(influence); output += "Influence: " + influenceString + " %\n"; } catch (NumberFormatException e) { Jeeves.debugException(e); } output += "State: " + data.factions[index].state + "\n"; if (factionName != null) { //add all the details! } } if ((factionName != null) && (factionNotFound == true)) { MessageQueue.sendMessage(message.getChannel(), "Cannot find the faction " + factionName); return; } MessageQueue.sendMessage(message.getChannel(), output); } } }
package org.openforis.users.web; import static spark.Spark.get; import static spark.Spark.post; import static spark.Spark.staticFileLocation; import org.openforis.users.manager.EntityManagerFactory; import org.openforis.users.model.User; import spark.Request; import spark.Response; import spark.Route; import spark.servlet.SparkApplication; /** * * @author R. Fontanarosa * @author S. Ricci * */ public class Server implements SparkApplication { private static final String JSON_CONTENT_TYPE = "application/json"; @Override public void init() { staticFileLocation("/public"); get("/hello/:name", Views.home); get("/users/all", listAllUsers, new JsonTransformer()); post("/users/", addUser, new JsonTransformer()); } private Route listAllUsers = (Request req, Response rsp) -> { return EntityManagerFactory.getUserManager().listAll(); }; private Route addUser = (Request req, Response rsp) -> { String username = req.queryParams("username"); String password = req.queryParams("password"); User user = new User(); user.setUsername(username); user.setPassword(password); EntityManagerFactory.getUserManager().save(user); return user; }; }
package mil.dds.anet.resources; import com.codahale.metrics.annotation.Timed; import io.leangen.graphql.annotations.GraphQLArgument; import io.leangen.graphql.annotations.GraphQLMutation; import io.leangen.graphql.annotations.GraphQLQuery; import io.leangen.graphql.annotations.GraphQLRootContext; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import javax.cache.Cache; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import mil.dds.anet.AnetObjectEngine; import mil.dds.anet.beans.AdminSetting; import mil.dds.anet.beans.Person; import mil.dds.anet.config.AnetConfiguration; import mil.dds.anet.database.AdminDao; import mil.dds.anet.utils.AnetAuditLogger; import mil.dds.anet.utils.AnetConstants; import mil.dds.anet.utils.AuthUtils; import mil.dds.anet.utils.DaoUtils; @Path("/api/admin") public class AdminResource { private final AdminDao dao; private final AnetConfiguration config; public AdminResource(AnetObjectEngine engine, AnetConfiguration config) { this.dao = engine.getAdminDao(); this.config = config; } @GraphQLQuery(name = "adminSettings") public List<AdminSetting> getAll() { return dao.getAllSettings(); } @GraphQLMutation(name = "saveAdminSettings") public Integer saveAdminSettings(@GraphQLRootContext Map<String, Object> context, @GraphQLArgument(name = "settings") List<AdminSetting> settings) { final Person user = DaoUtils.getUserFromContext(context); AuthUtils.assertAdministrator(user); int numRows = 0; for (AdminSetting setting : settings) { numRows += dao.saveSetting(setting); } AnetAuditLogger.log("Admin settings updated by {}", user); return numRows; } @GET @Timed @Path("/dictionary") @Produces(MediaType.APPLICATION_JSON) public Map<String, Object> getDictionary() { return config.getDictionary(); } /** * If anet-dictionary.yml file is changed manually while ANET is up and running ,this method can * be used to reload the dictionary with new values without restarting the server */ @GraphQLMutation(name = "reloadDictionary") public String reloadDictionary(@GraphQLRootContext Map<String, Object> context) throws IOException { final Person user = DaoUtils.getUserFromContext(context); AuthUtils.assertAdministrator(user); config.loadDictionary(); AnetAuditLogger.log("Dictionary updated by {}", user); return AnetConstants.DICTIONARY_RELOAD_MESSAGE; } /** * Returns the project version which is saved during project build (See project.version definition * in build.gradle file) Right after project information is written into version.properties file * on startup,it is read and set with AnetConfiguration loadVersion method */ @GraphQLQuery(name = "projectVersion") public String getProjectVersion() { return config.getVersion(); } /** * Clears Domain Users Cache */ @GraphQLMutation(name = "clearCache") public String clearCache(@GraphQLRootContext Map<String, Object> context) { final Person user = DaoUtils.getUserFromContext(context); AuthUtils.assertAdministrator(user); return AnetObjectEngine.getInstance().getPersonDao().clearCache(); } /** * Returns user logs in descending order of time */ @GraphQLQuery(name = "userActivities") public HashMap<String, Object> userActivities(@GraphQLRootContext Map<String, Object> context) { final Person user = DaoUtils.getUserFromContext(context); AuthUtils.assertAdministrator(user); final HashMap<String, LinkedHashSet<Map<String, String>>> recentCalls = new HashMap<>(); final Cache<String, Person> domainUsersCache = AnetObjectEngine.getInstance().getPersonDao().getDomainUsersCache(); for (final Cache.Entry<String, Person> entry : domainUsersCache) { entry.getValue().getUserActivities().removeAll(Collections.singleton(null)); entry.getValue().getUserActivities().forEach(k -> { // Group all entries with recentCalls key recentCalls.computeIfAbsent("recentCalls", l -> new LinkedHashSet<>()).add(k); }); } if (recentCalls.size() == 0) return new HashMap<>(); final HashMap<String, Object> allActivities = new HashMap<>(); final HashMap<String, LinkedHashSet<Map<String, String>>> recentActivities = new HashMap<String, LinkedHashSet<Map<String, String>>>() { { // Sort recentCalls by time in descending order put("recentCalls", recentCalls.values().stream().map(s -> { final ArrayList<Map<String, String>> activities = new ArrayList<>(s); return activities.stream() .sorted((o1, o2) -> o2.get("time").compareTo(o1.get("time"))) .collect(Collectors.toCollection(LinkedHashSet::new)); }).collect( Collectors.toMap(k -> k.iterator().next().get("activity"), Function.identity())) .get("activity")); } }; allActivities.put("recentCalls", recentActivities.get("recentCalls")); // Sort recentActivities grouping by user final LinkedHashMap<String, List<Map<String, String>>> recentUsers = recentActivities .get("recentCalls").stream().collect(Collectors.groupingBy(item -> item.get("user"), LinkedHashMap::new, Collectors.mapping(Function.identity(), Collectors.toList()))); // Put sorted users to the list allActivities.put("users", recentUsers); return allActivities; } }
package minigamemanager.api.items; import java.util.Random; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; /** * Helper class to parse Strings into {@link ItemStack ItemStacks} * * @author DonkeyCore */ public class ItemParser { public static ItemStack parseItem(String item) { // Format: // material[,amount][,durability][;enchantment[:level]...] try { String material = item.replaceAll(",.*", "").replaceAll(";.*", ""); ItemStackBuilder b = ItemStackBuilder.fromMaterial(Material.matchMaterial(material)); String[] properties = item.split(","); /* * properties[0] = material <-- ignore * properties[1] = amount (+ maybe junk) * properties[2] = durability (+ maybe junk) * replaceAll(";.*", "") -> get rid of possible junk */ if (properties.length > 1) b.amount(parseInteger(properties[1].replaceAll(";.*", ""))); if (properties.length > 2) b.durability((short) parseInteger(properties[2].replaceAll(";.*", ""))); String[] enchants = item.split(";"); /** * enchants[0] = material (+ maybe amount, durability) * enchants[1...n] = enchants */ // skip everything below if there aren't any enchants if (enchants.length <= 1) return b.build(); for (int i = 1 /* skip first entry */; i < enchants.length; i++) { String e = enchants[i]; // reuse older variable because convenient name properties = e.split(":"); String enchantName = enchantAliases(properties[0]).toUpperCase().replace(' ', '_'); if (properties.length == 1) b.unsafeEnchantment(Enchantment.getByName(enchantName), 1); else b.unsafeEnchantment(Enchantment.getByName(enchantName), parseInteger(properties[1])); } return b.build(); } catch (Throwable t) { throw new ItemFormatException(t); } } public static ItemStack[] parseItems(String... items) { ItemStack[] is = new ItemStack[items.length]; for (int i = 0; i < items.length; i++) is[i] = parseItem(items[i]); return is; } private static int parseInteger(String str) { if (str.contains("-")) { String[] bounds = str.split("-"); int min = Integer.parseInt(bounds[0]); int max = Integer.parseInt(bounds[1]); // random number between min and max, inclusive return new Random().nextInt(max - min + 1) + min; } else return Integer.parseInt(str); } /** * Replaces common enchantment names with their Bukkit versions * * @param e An enchantment string containing common names of enchantments * * @return The string with the common names replaced with their Bukkit * versions */ private static String enchantAliases(String e) { return e.toLowerCase().replaceAll("protection$", "protection environmental").replaceAll("protection(\\S)", "protection environmental").replace("feather falling", "protection fall").replace("blast protection", "protection explosions").replace("sharpness", "damage all").replace("smite", "damage undead").replace("bane of arthropods", "damage arthropods").replace("respiration", "oxygen").replace("aqua affinity", "water worker").replace("looting", "loot bonus mobs").replace("efficiency", "dig speed").replace("unbreaking", "durability").replace("power", "arrow damage").replace("punch", "arrow knockback").replace("infinity", "arrow infinite").replace("flame", "arrow fire"); } public static class ItemFormatException extends IllegalArgumentException { private static final long serialVersionUID = -2936619347545826060L; public ItemFormatException() { super(); } public ItemFormatException(String message) { super(message); } public ItemFormatException(String message, Throwable cause) { super(message, cause); } public ItemFormatException(Throwable cause) { super(cause); } } }
package net.fortytwo.twitlogic; import net.fortytwo.twitlogic.flow.Handler; import net.fortytwo.twitlogic.model.Tweet; import net.fortytwo.twitlogic.model.User; import net.fortytwo.twitlogic.persistence.TweetPersister; import net.fortytwo.twitlogic.persistence.TweetStore; import net.fortytwo.twitlogic.persistence.TweetStoreConnection; import net.fortytwo.twitlogic.persistence.TweetStoreException; import net.fortytwo.twitlogic.server.TwitLogicServer; import net.fortytwo.twitlogic.services.twitter.TweetHandlerException; import net.fortytwo.twitlogic.services.twitter.TwitterClient; import net.fortytwo.twitlogic.services.twitter.TwitterClientException; import net.fortytwo.twitlogic.syntax.Matcher; import net.fortytwo.twitlogic.syntax.MultiMatcher; import net.fortytwo.twitlogic.syntax.TopicSniffer; import net.fortytwo.twitlogic.syntax.TweetAnnotator; import net.fortytwo.twitlogic.syntax.afterthought.DemoAfterthoughtMatcher; import java.io.File; import java.io.FileInputStream; import java.util.Date; import java.util.Properties; import java.util.Set; import java.util.logging.Logger; public class TwitLogicDemo { private static final Logger LOGGER = TwitLogic.getLogger(TwitLogicDemo.class); public static void main(final String[] args) { try { if (1 == args.length) { File configFile = new File(args[0]); Properties p = new Properties(); p.load(new FileInputStream(configFile)); TwitLogic.setConfiguration(p); runDemo(); } else { printUsage(); System.exit(1); } } catch (Throwable t) { t.printStackTrace(); } } private static void printUsage() { System.out.println("Usage: twitlogic [configuration file]"); System.out.println("For more information, please see:\n" + " <URL:http://wiki.github.com/joshsh/twitlogic/configuring-and-running-twitlogic>."); } private static void runDemo() throws Exception { // Create a persistent store. TweetStore store = new TweetStore(); store.initialize(); try { // Launch linked data server. new TwitLogicServer(store); // Create a client for communication with Twitter. TwitterClient client = new TwitterClient(); TweetStoreConnection c = store.createConnection(); try { Handler<Tweet, TweetHandlerException> annotator = createAnnotator(store, c, client); // Create an agent to listen for commands. // Also take the opportunity to memoize users we're following. /* TwitLogicAgent agent = new TwitLogicAgent(client); UserRegistry userRegistry = new UserRegistry(client); Handler<Tweet, TweetHandlerException> realtimeStatusHandler = userRegistry.createUserRegistryFilter( new CommandListener(agent, annotator)); */ Set<User> users = TwitLogic.findFollowList(client); Set<String> terms = TwitLogic.findTrackTerms(); //GregorianCalendar cal = new GregorianCalendar(2010, GregorianCalendar.MAY, 1); //gatherHistoricalTweets(store, client, users, cal.getTime()); client.processFollowFilterStream(users, terms, annotator, 0); } finally { c.close(); } } finally { store.shutDown(); } } private static void gatherHistoricalTweets(final TweetStore store, final TwitterClient client, final Set<User> users, final Date startTime) throws TweetStoreException, TwitterClientException, TweetHandlerException { Thread t = new Thread(new Runnable() { public void run() { try { TweetStoreConnection c = store.createConnection(); try { // Note: don't run old tweets through the command listener, or // TwitLogic will respond, annoyingly, to old commands. client.processTimelineFrom(users, startTime, new Date(), createAnnotator(store, c, client)); } finally { c.close(); } } catch (Throwable t) { LOGGER.severe("historical tweets thread died with error: " + t); t.printStackTrace(); } } }); t.start(); } private static Handler<Tweet, TweetHandlerException> createAnnotator(final TweetStore store, final TweetStoreConnection c, final TwitterClient client) throws TweetStoreException { // Create the tweet persister. boolean persistUnannotatedTweets = true; TweetPersister persister = new TweetPersister(store, c, client, persistUnannotatedTweets); // Add a "topic sniffer". TopicSniffer topicSniffer = new TopicSniffer(persister); // Add a tweet annotator. Matcher matcher = new MultiMatcher( new DemoAfterthoughtMatcher()); return new TweetAnnotator(matcher, topicSniffer); } }
package net.jselby.escapists; import net.jselby.escapists.editor.elements.RenderView; import net.jselby.escapists.mapping.Map; import net.jselby.escapists.mapping.MapRenderer; import net.jselby.escapists.objects.ObjectRegistry; import net.jselby.escapists.utils.BlowfishCompatEncryption; import net.jselby.escapists.utils.IOUtils; import net.jselby.escapists.utils.logging.LoggingDebugPrintStream; import net.jselby.escapists.utils.SteamFinder; import net.jselby.escapists.utils.logging.Rollbar; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.image.BufferedImage; import java.io.*; import java.net.URL; import java.util.ArrayList; /** * The main entry point for the EscapistsEditor. * * @author j_selbys */ public class EscapistsEditor { public static final String VERSION = "1.5.4"; public static final boolean DEBUG = false; // -- Arguments private String decryptFile; private String encryptFile; private String encryptAndInstallFile; private String renderMap; private String editMap; private boolean showHelp; private boolean renderAll; private String escapistsPathUser; // -- Internal vars /** * The root directory of Escapists */ public File escapistsPath; /** * Create a new default registry for objects */ public ObjectRegistry registry; public static boolean showGUI; private RenderView view; public static String updateMessage; private void start() { System.out.println("========================="); System.out.println("Operating system: " + System.getProperty("os.name")); System.out.println("Java version: " + System.getProperty("java.version")); registry = new ObjectRegistry("net.jselby.escapists.objects"); // Discover Escapists directory if (escapistsPathUser == null) { File steamPath = SteamFinder.getSteamPath(this); if (steamPath == null) { fatalError("Failed to discover Steam installation with Escapists."); } // Check that Escapists is installed escapistsPath = steamPath; } else { escapistsPath = new File(escapistsPathUser); } if (!escapistsPath.exists()) { fatalError("Escapists is not installed @ " + escapistsPath.getPath()); } // I don't support piracy, in terms of obtaining support for such. // This hashes the steam_api.dll, checking for bad stuff there. File file = new File(escapistsPath, "steam_api.dll"); if (file.exists()) { try { String hash = IOUtils.hash(file); System.out.println("Hash: " + hash); } catch (Exception ignored) {} } else { System.out.println("Warning: No Steam API in Escapists dir!"); } System.out.println("========================="); // Parse arguments System.out.println("Discovered Escapists @ " + escapistsPath.getPath()); // Check for update Thread updateThread = new Thread(new Runnable() { @Override public void run() { if (!showGUI) { return; } try { String newVersion = IOUtils.toString(new URL("http://escapists.jselby.net/version.txt")).trim(); String message = ""; if (newVersion.contains("\n")) { message = newVersion.split("\n")[1]; newVersion = newVersion.split("\n")[0].trim(); } if (!newVersion.equalsIgnoreCase(VERSION) && newVersion.length() != 0) { updateMessage = newVersion + "\n" + message; dialog("New version found (" + newVersion + "). " + "Download it at http://escapists.jselby.net\n" + message); } } catch (IOException e) { e.printStackTrace(); } } }); updateThread.start(); } private static void fatalError(String s) { System.err.println(s); if (showGUI) { JOptionPane.showMessageDialog(null, s); } System.exit(1); } public void dialog(String s) { System.out.println(" - Dialog: "); for (String split : s.split("\n")) { System.out.println(" > " + split); } if (showGUI) { JOptionPane.showMessageDialog(null, s); } } public String[] getMaps() { File mapsDir = new File(escapistsPath, "Data" + File.separator + "Maps"); ArrayList<String> maps = new ArrayList<>(); for (File file : mapsDir.listFiles()) { if (file.isFile()) { maps.add(file.getName()); } } System.out.println("Listing " + maps.size() + " maps."); return maps.toArray(new String[maps.size()]); } public void dump(String name) throws IOException { File mapPath = new File(name); String fileExtension = mapPath.getName().contains(".") ? ("." + mapPath.getName().split("\\.")[1]) : ""; if (!mapPath.exists()) { mapPath = new File(escapistsPath, "Data" + File.separator + "Maps" + File.separator + name); if (!mapPath.exists()) { dialog("Map \"" + name.trim() + "\" not found."); return; } } // Decrypt it byte[] content = BlowfishCompatEncryption.decrypt(mapPath); File decryptedMap = new File(name.split("\\.")[0] + ".decrypted" + fileExtension); System.out.println("Decrypting \"" + name + " to \"" + decryptedMap.getPath() + "\"..."); IOUtils.write(decryptedMap, content); } public void render(String name) throws IOException { String rawName = new File(name).getName().split("\\.")[0]; File mapPath = new File(name); if (!mapPath.exists()) { mapPath = new File(escapistsPath, "Data" + File.separator + "Maps" + File.separator + name); if (!mapPath.exists()) { dialog("Map \"" + name.trim() + "\" not found."); return; } } // Decrypt it String content = new String(BlowfishCompatEncryption.decrypt(mapPath)); // Decode it Map map = new Map(this, registry, mapPath.getPath(), content); BufferedImage image = new MapRenderer().render(map, "World"); File parent = new File("renders"); if (!parent.exists()) { if (!parent.mkdir()) { fatalError("Failed to create output directory: \"" + parent.getPath() + "\"."); } } File outputfile = new File(parent, rawName.toLowerCase() + ".png"); ImageIO.write(image, "png", outputfile); System.out.println("Successfully rendered \"" + outputfile.getPath() + "\"."); } private void encrypt(String name, boolean install) throws IOException { File mapPath = new File(name); String fileExtension = mapPath.getName().contains(".") ? ("." + mapPath.getName().split("\\.")[1]) : ""; if (!mapPath.exists()) { mapPath = new File(escapistsPath, "Data" + File.separator + "Maps" + File.separator + name); if (!mapPath.exists()) { dialog("Map \"" + name.trim() + "\" not found."); return; } } // Decrypt it byte[] content = BlowfishCompatEncryption.encrypt(mapPath); File decryptedMap; if (install) { decryptedMap = new File(escapistsPath, "Data" + File.separator + "Maps" + File.separator + name.split("\\.")[0] + ".map"); } else { decryptedMap = new File(name.split("\\.")[0] + ".encrypted" + fileExtension); } System.out.println("Encrypting \"" + name + " to \"" + decryptedMap.getPath() + "\"..."); IOUtils.write(decryptedMap, content); } public void edit(byte[] decryptedBytes) throws IOException { String contents = new String(decryptedBytes); Map map = new Map(this, registry, "", contents); if (map.getTilesImage() == null && showGUI) { JOptionPane.showMessageDialog(null, "Failed to load resources."); System.exit(1); } if (view != null) { view.setEnabled(true); view.setMap(map); } else { view = new RenderView(this, map); } } public void edit(String name) throws IOException { File mapPath = new File(name); if (!mapPath.exists()) { mapPath = new File(escapistsPath, "Data" + File.separator + "Maps" + File.separator + name); if (!mapPath.exists()) { dialog("Map \"" + name.trim() + "\" not found."); return; } } String contents = new String(BlowfishCompatEncryption.decrypt(mapPath)); Map map = new Map(this, registry, mapPath.getPath(), contents); if (map.getTilesImage() == null && showGUI) { JOptionPane.showMessageDialog(null, "Failed to load resources."); System.exit(1); } if (view != null) { view.setEnabled(true); view.setMap(map); } else { view = new RenderView(this, map); } } public static void main(String[] args) { try { Rollbar.init(); // Redirect SysOut try { OutputStream fileOut = new FileOutputStream(new File("escapistseditor.log")); System.setOut(new LoggingDebugPrintStream(fileOut, System.out)); System.setErr(new LoggingDebugPrintStream(fileOut, System.err)); } catch (Exception e) { System.err.println("Failed to start logging."); e.printStackTrace(); } System.out.println("The Escapists Editor v" + VERSION); System.out.println("By jselby"); // Parse EscapistsEditor editor = new EscapistsEditor(); if (args.length == 0) { showGUI = true; } else if (args.length > 0) { // Check for a command int pos = 0; while(pos < args.length) { if (args[pos].startsWith("-")) { // Sure is. Get its name String name = args[pos].substring(1).toLowerCase(); while (name.startsWith("-")) { name = name.substring(1); } if (name.startsWith("help") && args.length == 1) { editor.showHelp = true; } else if (name.startsWith("render-all") && args.length == 1) { editor.renderAll = true; } else if (args.length > 1) { String val = args[pos + 1]; if (args[pos + 1].startsWith("\"")) { // Multi-space arg val = val.substring(1); for (int i = pos + 2; i < args.length; i++) { pos = i; String str = args[i]; val += " " + str; if (str.endsWith("\"")) { val = val.substring(0, val.length() - 1); break; } } } else { pos++; } // Parse if (name.equalsIgnoreCase("decrypt")) { editor.decryptFile = val; } else if (name.equalsIgnoreCase("encrypt")) { editor.encryptFile = val; } else if (name.equalsIgnoreCase("encrypt-and-install")) { editor.encryptAndInstallFile = val; } else if (name.equalsIgnoreCase("render")) { editor.renderMap = val; } else if (name.equalsIgnoreCase("edit")) { editor.editMap = val; } else if (name.equalsIgnoreCase("escapists-path")) { editor.escapistsPathUser = val; } } else { editor.showHelp = true; } } else { System.out.println(args[pos]); editor.showHelp = true; } pos++; } } if (editor.showHelp) { System.out.println("Usage:"); System.out.println(" --decrypt\tDecrypts the passed file."); System.out.println(" --encrypt\tEncrypts the passed file."); System.out.println(" --encrypt-and-install\tEncrypts and installs the passed file."); System.out.println(" --render\tRenders the passed file."); System.out.println(" --edit\tEdits the passed unencrypted map."); System.out.println(" --render-all\tRenders all maps."); System.out.println(" --escapists-path\tForces a path for The Escapists install directory."); return; } editor.start(); // Check what we need to do if (editor.decryptFile == null && editor.encryptFile == null && editor.renderMap == null && editor.encryptAndInstallFile == null && editor.editMap == null && !editor.renderAll) { // Select a map through a GUI first showGUI = true; editor.view = new RenderView(editor, null); } if (editor.decryptFile != null) { editor.dump(editor.decryptFile); } if (editor.encryptFile != null) { editor.encrypt(editor.encryptFile, false); } if (editor.encryptAndInstallFile != null) { editor.encrypt(editor.encryptAndInstallFile, true); } if (editor.renderMap != null) { editor.render(editor.renderMap); } if (editor.renderAll) { for (String map : editor.getMaps()) { editor.render(map); } } if (editor.editMap != null) { editor.edit(editor.editMap); } } catch (Exception e) { fatalError(e, Rollbar.fatal(e)); } } public static void fatalError(Exception e, Thread fatal) { String s = "Error: "; ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(out); e.printStackTrace(stream); s += out.toString(); System.err.println(s); if (showGUI) { JOptionPane.showMessageDialog(null, s); } try { fatal.join(); } catch (InterruptedException e1) { e1.printStackTrace(); } System.exit(1); } public static void fatalError(Exception e) { String string = "Error: "; ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(out); e.printStackTrace(stream); string += out.toString(); fatalError(string); } }
package org.qommons.collect; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Spliterator; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import org.qommons.IterableUtils; import org.qommons.Transaction; import org.qommons.collect.MultiMap.MultiEntry; import org.qommons.collect.Quiterator.CollectionElement; import org.qommons.collect.Quiterator.WrappingElement; import org.qommons.collect.Quiterator.WrappingQuiterator; import org.qommons.value.Settable; import org.qommons.value.Value; import com.google.common.reflect.TypeParameter; import com.google.common.reflect.TypeToken; /** * An enhanced collection. * * The biggest differences between Qollection and Collection are: * <ul> * <li><b>Dynamic Transformation</b> The stream api allows transforming of the content of one collection into another, but the * transformation is done once for all, creating a new collection independent of the source. Sometimes it is desirable to make a transformed * collection that does its transformation dynamically, keeping the same data source, so that when the source is modified, the transformed * collection is also updated accordingly. #map(Function), #filter(Function), #groupBy(Function), and others allow this. In addition, the * syntax of creating these dynamic transformations is much simpler and cleaner: e.g.<br /> * &nbsp;&nbsp;&nbsp;&nbsp; <code>coll.{@link #map(Function) map}(Function)</code><br /> * instead of<br /> * &nbsp;&nbsp;&nbsp;&nbsp;<code>coll.stream().map(Function).collect(Collectors.toList())</code>.</li> * <li><b>Modification Control</b> The {@link #filterAdd(Function)} and {@link #filterRemove(Function)} methods create collections that * forbid certain types of modifications to a collection. The {@link #immutable(String)} prevents any API modification at all.</li> * <li><b>Quiterator</b> Qollections must implement {@link #spliterator()}, which returns a {@link Quiterator}, which is an enhanced * {@link Spliterator}. This had potential for the improved performance associated with using {@link Spliterator} instead of * {@link Iterator} as well as the utility added by {@link Quiterator}.</li> * <li><b>Transactionality</b> Qollections support the {@link org.qommons.Transactable} interface, allowing callers to reserve a collection * for write or to ensure that the collection is not written to during an operation (for implementations that support this. See * {@link org.qommons.Transactable#isLockSupported() isLockSupported()}).</li> * <li><b>Run-time type safety</b> Qollections have a {@link #getType() type} associated with them, allowing them to enforce type-safety at * run time. How strictly this type-safety is enforced is implementation-dependent.</li> * </ul> * * @param <E> The type of elements in this collection */ public interface Qollection<E> extends TransactableCollection<E> { /** Standard messages returned by this class */ interface StdMsg { static String BAD_TYPE = "Object is the wrong type for this collection"; static String UNSUPPORTED_OPERATION = "Unsupported Operation"; static String NULL_DISALLOWED = "Null is not allowed"; static String GROUP_EXISTS = "Group already exists"; static String WRONG_GROUP = "Item does not belong to this group"; static String NOT_FOUND = "No such item found"; } /** @return The run-time type of elements in this collection */ TypeToken<E> getType(); @Override abstract Quiterator<E> spliterator(); @Override default Iterator<E> iterator() { return new QuiteratorIterator<>(spliterator()); } @Override default boolean isEmpty() { return size() == 0; } @Override default boolean contains(Object o) { try (Transaction t = lock(false, null)) { Quiterator<E> iter = spliterator(); boolean[] found = new boolean[1]; while (!found[0] && iter.tryAdvance(v -> { if (Objects.equals(v, o)) found[0] = true; })) { } return found[0]; } } @Override default boolean containsAll(Collection<?> c) { if (c.isEmpty()) return true; ArrayList<Object> copy = new ArrayList<>(c); BitSet found = new BitSet(copy.size()); try (Transaction t = lock(false, null)) { Quiterator<E> iter = spliterator(); boolean[] foundOne = new boolean[1]; while (iter.tryAdvance(next -> { int stop = found.previousClearBit(copy.size()); for (int i = found.nextClearBit(0); i < stop; i = found.nextClearBit(i + 1)) if (Objects.equals(next, copy.get(i))) { found.set(i); foundOne[0] = true; } })) { if (foundOne[0] && found.cardinality() == copy.size()) { break; } foundOne[0] = false; } return found.cardinality() == copy.size(); } } @Override default E[] toArray() { ArrayList<E> ret; try (Transaction t = lock(false, null)) { ret = new ArrayList<>(size()); spliterator().forEachRemaining(v -> ret.add(v)); } return ret.toArray((E[]) java.lang.reflect.Array.newInstance(getType().wrap().getRawType(), ret.size())); } @Override default <T> T[] toArray(T[] a) { ArrayList<E> ret; try (Transaction t = lock(false, null)) { ret = new ArrayList<>(); spliterator().forEachRemaining(v -> ret.add(v)); } return ret.toArray(a); } /** * @param values The values to add to the collection * @return This collection */ public default Qollection<E> addValues(E... values) { try (Transaction t = lock(true, null)) { for (E value : values) add(value); } return this; } /** @return A value for the size of this collection */ default Value<Integer> sizeValue() { return new Value<Integer>() { private final TypeToken<Integer> intType = TypeToken.of(Integer.TYPE); @Override public TypeToken<Integer> getType() { return intType; } @Override public Integer get() { return size(); } @Override public String toString() { return Qollection.this + ".size()"; } }; } /** * Searches in this collection for an element. * * @param filter The filter function * @return A value in this list passing the filter, or null if none of this collection's elements pass. */ default Value<E> find(Predicate<E> filter) { return new Value<E>() { private final TypeToken<E> type = Qollection.this.getType().wrap(); @Override public TypeToken<E> getType() { return type; } @Override public E get() { for (E element : Qollection.this) { if (filter.test(element)) return element; } return null; } @Override public String toString() { return "find in " + Qollection.this; } }; } /** * @param <T> The type of values to map to * @param type The run-time type of values to map to * @return A builder to customize the filter/mapped collection */ default <T> MappedQollectionBuilder<E, E, T> buildMap(TypeToken<T> type) { return new MappedQollectionBuilder<>(this, null, type); } /** * Creates a collection using the results of a {@link MappedQollectionBuilder} * * @param <T> The type of values to map to * @param filterMap The definition for the filter/mapping * @return The filter/mapped collection */ default <T> Qollection<T> filterMap(FilterMapDef<E, ?, T> filterMap) { return new FilterMappedQollection<>(this, filterMap); } /** * @param <T> The type of the new collection * @param map The mapping function * @return An observable collection of a new type backed by this collection and the mapping function */ default <T> Qollection<T> map(Function<? super E, T> map) { return buildMap(MappedQollectionBuilder.returnType(map)).map(map, false).build(); } /** * @param filter The filter function * @return A collection containing all non-null elements passing the given test */ default Qollection<E> filter(Function<? super E, String> filter) { return this.<E> buildMap(getType()).filter(filter, false).build(); } /** * @param <T> The type for the new collection * @param type The type to filter this collection by * @return A collection backed by this collection, consisting only of elements in this collection whose values are instances of the * given class */ default <T> Qollection<T> filter(Class<T> type) { return buildMap(TypeToken.of(type)).filter(value -> { if (type == null || type.isInstance(value)) return null; else return StdMsg.BAD_TYPE; }, true).build(); } /** * Shorthand for {@link #flatten(Qollection) flatten}({@link #map(Function) map}(Function)) * * @param <T> The type of the values produced * @param type The type of the values produced * @param map The value producer * @return A qollection whose values are the accumulation of all those produced by applying the given function to all of this * collection's values */ default <T> Qollection<T> flatMap(TypeToken<T> type, Function<? super E, ? extends Qollection<? extends T>> map) { TypeToken<Qollection<? extends T>> qollectionType; if (type == null) { qollectionType = (TypeToken<Qollection<? extends T>>) TypeToken.of(map.getClass()) .resolveType(Function.class.getTypeParameters()[1]); if (!qollectionType.isAssignableFrom(new TypeToken<Qollection<T>>() {})) qollectionType = new TypeToken<Qollection<? extends T>>() {}; } else qollectionType = new TypeToken<Qollection<? extends T>>() {}.where(new TypeParameter<T>() {}, type); return flatten(this.<Qollection<? extends T>> buildMap(qollectionType).map(map, false).build()); } /** * @param <T> The type of the argument value * @param <V> The type of the new observable collection * @param arg The value to combine with each of this collection's elements * @param func The combination function to apply to this collection's elements and the given value * @return An observable collection containing this collection's elements combined with the given argument */ default <T, V> Qollection<V> combine(Value<T> arg, BiFunction<? super E, ? super T, V> func) { return combine(arg, (TypeToken<V>) TypeToken.of(func.getClass()).resolveType(BiFunction.class.getTypeParameters()[2]), func); } /** * @param <T> The type of the argument value * @param <V> The type of the new observable collection * @param arg The value to combine with each of this collection's elements * @param type The type for the new collection * @param func The combination function to apply to this collection's elements and the given value * @return An observable collection containing this collection's elements combined with the given argument */ default <T, V> Qollection<V> combine(Value<T> arg, TypeToken<V> type, BiFunction<? super E, ? super T, V> func) { return combine(arg, type, func, null); } /** * @param <T> The type of the argument value * @param <V> The type of the new observable collection * @param arg The value to combine with each of this collection's elements * @param type The type for the new collection * @param func The combination function to apply to this collection's elements and the given value * @param reverse The reverse function if addition support is desired for the combined collection * @return An observable collection containing this collection's elements combined with the given argument */ default <T, V> Qollection<V> combine(Value<T> arg, TypeToken<V> type, BiFunction<? super E, ? super T, V> func, BiFunction<? super V, ? super T, E> reverse) { return new CombinedQollection<>(this, type, arg, func, reverse); } /** * Equivalent to {@link #reduce(Object, BiFunction, BiFunction)} with null for the remove function * * @param <T> The type of the reduced value * @param init The seed value before the reduction * @param reducer The reducer function to accumulate the values. Must be associative. * @return The reduced value */ default <T> Value<T> reduce(T init, BiFunction<? super T, ? super E, T> reducer) { return reduce(init, reducer, null); } /** * Equivalent to {@link #reduce(TypeToken, Object, BiFunction, BiFunction)} using the type derived from the reducer's return type * * @param <T> The type of the reduced value * @param init The seed value before the reduction * @param add The reducer function to accumulate the values. Must be associative. * @param remove The de-reducer function to handle removal or replacement of values. This may be null, in which case removal or * replacement of values will result in the entire collection being iterated over for each subscription. Null here will have no * consequence if the result is never observed. Must be associative. * @return The reduced value */ default <T> Value<T> reduce(T init, BiFunction<? super T, ? super E, T> add, BiFunction<? super T, ? super E, T> remove) { return reduce((TypeToken<T>) TypeToken.of(add.getClass()).resolveType(BiFunction.class.getTypeParameters()[2]), init, add, remove); } /** * Reduces all values in this collection to a single value * * @param <T> The compile-time type of the reduced value * @param type The run-time type of the reduced value * @param init The seed value before the reduction * @param add The reducer function to accumulate the values. Must be associative. * @param remove The de-reducer function to handle removal or replacement of values. This may be null, in which case removal or * replacement of values will result in the entire collection being iterated over for each subscription. Null here will have no * consequence if the result is never observed. Must be associative. * @return The reduced value */ default <T> Value<T> reduce(TypeToken<T> type, T init, BiFunction<? super T, ? super E, T> add, BiFunction<? super T, ? super E, T> remove) { return new Value<T>() { @Override public TypeToken<T> getType() { return type; } @Override public T get() { T ret = init; for (E element : Qollection.this) ret = add.apply(ret, element); return ret; } @Override public String toString() { return "reduce " + Qollection.this; } }; } /** * @param compare The comparator to use to compare this collection's values * @return An observable value containing the minimum of the values, by the given comparator */ default Value<E> minBy(Comparator<? super E> compare) { return reduce(getType(), null, (v1, v2) -> { if (v1 == null) return v2; else if (v2 == null) return v1; else if (compare.compare(v1, v2) <= 0) return v1; else return v2; }, null); } /** * @param compare The comparator to use to compare this collection's values * @return An observable value containing the maximum of the values, by the given comparator */ default Value<E> maxBy(Comparator<? super E> compare) { return reduce(getType(), null, (v1, v2) -> { if (v1 == null) return v2; else if (v2 == null) return v1; else if (compare.compare(v1, v2) >= 0) return v1; else return v2; }, null); } /** * @param <K> The type of the key * @param keyMap The mapping function to group this collection's values by * @return A multi-map containing each of this collection's elements, each in the collection of the value mapped by the given function * applied to the element */ default <K> MultiQMap<K, E> groupBy(Function<E, K> keyMap) { return groupBy((TypeToken<K>) TypeToken.of(keyMap.getClass()).resolveType(Function.class.getTypeParameters()[1]), keyMap); } /** * @param <K> The type of the key * @param keyType The type of the key * @param keyMap The mapping function to group this collection's values by * @param equalizer The equalizer to use to group the keys * @return A multi-map containing each of this collection's elements, each in the collection of the value mapped by the given function * applied to the element */ default <K> MultiQMap<K, E> groupBy(TypeToken<K> keyType, Function<E, K> keyMap) { return new GroupedMultiMap<>(this, keyMap, keyType); } /** * @param <K> The type of the key * @param keyMap The mapping function to group this collection's values by * @param compare The comparator to use to sort the keys * @return A sorted multi-map containing each of this collection's elements, each in the collection of the value mapped by the given * function applied to the element */ default <K> SortedMultiQMap<K, E> groupBy(Function<E, K> keyMap, Comparator<? super K> compare) { return groupBy(null, keyMap, compare); } /** * @param compare The comparator to use to group the value * @return A sorted multi-map containing each of this collection's elements, each in the collection of one value that it matches * according to the comparator */ default SortedMultiQMap<E, E> groupBy(Comparator<? super E> compare) { return groupBy(getType(), null, compare); } /** * TODO TEST ME! * * @param <K> The type of the key * @param keyType The type of the key * @param keyMap The mapping function to group this collection's values by * @param compare The comparator to use to sort the keys * @return A sorted multi-map containing each of this collection's elements, each in the collection of the value mapped by the given * function applied to the element */ default <K> SortedMultiQMap<K, E> groupBy(TypeToken<K> keyType, Function<E, K> keyMap, Comparator<? super K> compare) { return new GroupedSortedMultiMap<>(this, keyMap, keyType, compare); } /** * @param modMsg The message to return when modification is requested * @return An observable collection that cannot be modified directly but reflects the value of this collection as it changes */ default Qollection<E> immutable(String modMsg) { return new ImmutableQollection<>(this, modMsg); } /** * Creates a wrapper collection for which removals are filtered * * @param filter The filter to check removals with * @return The removal-filtered collection */ default Qollection<E> filterRemove(Function<? super E, String> filter) { return filterModification(filter, null); } default Qollection<E> noRemove(String removeMsg) { return filterModification(value -> removeMsg, null); } /** * Creates a wrapper collection for which additions are filtered * * @param filter The filter to check additions with * @return The addition-filtered collection */ default Qollection<E> filterAdd(Function<? super E, String> filter) { return filterModification(null, filter); } default Qollection<E> noAdd(String addMsg) { return filterModification(null, value -> addMsg); } /** * Creates a wrapper around this collection that can filter items that are attempted to be added or removed from it. If the filter * returns true, the addition/removal is allowed. If it returns false, the addition/removal is silently rejected. The filter is also * allowed to throw an exception, in which case the operation as a whole will fail. In the case of batch operations like * {@link #addAll(Collection) addAll} or {@link #removeAll(Collection) removeAll}, if the filter throws an exception on any item, the * collection will not be changed. Note that for filters that can return false, silently failing to add or remove items may break the * contract for the collection type. * * @param removeFilter The filter to test items being removed from the collection. If null, removals will not be filtered and will all * pass. * @param addFilter The filter to test items being added to the collection. If null, additions will not be filtered and will all pass * @return The controlled collection */ default Qollection<E> filterModification(Function<? super E, String> removeFilter, Function<? super E, String> addFilter) { return new ModFilteredQollection<>(this, removeFilter, addFilter); } /** * Tests the removability of an element from this collection. This method exposes a "best guess" on whether an element in the collection * could be removed, but does not provide any guarantee. This method should return true for any object for which {@link #remove(Object)} * is successful, but the fact that an object passes this test does not guarantee that it would be removed successfully. E.g. the * position of the element in the collection may be a factor, but may not be tested for here. * * @param value The value to test removability for * @return Null if given value could possibly be removed from this collection, or a message why it can't */ String canRemove(Object value); /** * Tests the compatibility of an object with this collection. This method exposes a "best guess" on whether an element could be added to * the collection , but does not provide any guarantee. This method should return true for any object for which {@link #add(Object)} is * successful, but the fact that an object passes this test does not guarantee that it would be removed successfully. E.g. the position * of the element in the collection may be a factor, but is tested for here. * * @param value The value to test compatibility for * @return Null if given value could possibly be added to this collection, or a message why it can't */ String canAdd(E value); /** * @param <E> The type of the values * @param type The type of the collection * @param collection The collection * @return An immutable collection with the same values as those in the given collection */ public static <E> Qollection<E> constant(TypeToken<E> type, Collection<E> collection) { return new ConstantQollection<>(type, collection); } /** * @param <E> The type of the values * @param type The type of the collection * @param values The values for the new collection * @return An immutable collection with the same values as those in the given collection */ public static <E> Qollection<E> constant(TypeToken<E> type, E... values) { return constant(type, java.util.Arrays.asList(values)); } /** * Turns a collection of observable values into a collection composed of those holders' values * * @param <T> The type of elements held in the values * @param collection The collection to flatten * @return The flattened collection */ public static <T> Qollection<T> flattenValues(Qollection<? extends Value<T>> collection) { return new FlattenedValuesQollection<>(collection); } /** * Turns an observable value containing an observable collection into the contents of the value * * @param <E> The type of values in the collection * @param collectionObservable The observable value * @return A collection representing the contents of the value, or a zero-length collection when null */ public static <E> Qollection<E> flattenValue(Value<? extends Qollection<E>> collectionObservable) { return new FlattenedValueQollection<>(collectionObservable); } /** * @param <E> The super-type of elements in the inner collections * @param coll The collection to flatten * @return A collection containing all elements of all collections in the outer collection */ public static <E> Qollection<E> flatten(Qollection<? extends Qollection<? extends E>> coll) { return new FlattenedQollection<>(coll); } /** * @param <T> An observable collection that contains all elements the given collections * @param colls The collections to flatten * @return A collection containing all elements of the given collections */ public static <T> Qollection<T> flattenCollections(Qollection<? extends T>... colls) { return flatten(constant(new TypeToken<Qollection<? extends T>>() {}, colls)); } /** * A simple toString implementation for collections * * @param coll The collection to print * @return The string representation of the collection's contents */ public static String toString(TransactableCollection<?> coll) { StringBuilder ret = new StringBuilder("("); boolean first = true; try (Transaction t = coll.lock(false, null)) { for (Object value : coll) { if (!first) { ret.append(", "); } else first = false; ret.append(value); } } ret.append(')'); return ret.toString(); } /** * An iterator backed by a Quiterator * * @param <E> The type of elements to iterate over */ class QuiteratorIterator<E> implements Iterator<E> { private final Quiterator<E> theQuiterator; private boolean isNextCached; private boolean isDone; private CollectionElement<? extends E> cachedNext; public QuiteratorIterator(Quiterator<E> quiterator) { theQuiterator = quiterator; } @Override public boolean hasNext() { cachedNext = null; if (!isNextCached && !isDone) { if (theQuiterator.tryAdvanceElement(element -> { cachedNext = element; })) isNextCached = true; else isDone = true; } return isNextCached; } @Override public E next() { if (!hasNext()) throw new java.util.NoSuchElementException(); isNextCached = false; return cachedNext.get(); } @Override public void remove() { if (cachedNext == null) throw new IllegalStateException( "First element has not been read, element has already been removed, or iterator has finished"); if (isNextCached) throw new IllegalStateException("remove() must be called after next() and before the next call to hasNext()"); cachedNext.remove(); cachedNext = null; } @Override public void forEachRemaining(Consumer<? super E> action) { if (isNextCached) action.accept(next()); cachedNext = null; isDone = true; theQuiterator.forEachRemaining(action); } } /** * An extension of Qollection that implements some of the redundant methods and throws UnsupportedOperationExceptions for modifications. * Mostly copied from {@link java.util.AbstractCollection}. * * @param <E> The type of element in the collection */ interface PartialQollectionImpl<E> extends Qollection<E> { @Override default boolean add(E e) { throw new UnsupportedOperationException(getClass().getName() + " does not implement add(value)"); } @Override default boolean addAll(Collection<? extends E> c) { try (Transaction t = lock(true, null)) { boolean modified = false; for (E e : c) if (add(e)) modified = true; return modified; } } @Override default boolean remove(Object o) { try (Transaction t = lock(true, null)) { Iterator<E> it = iterator(); while (it.hasNext()) { if (Objects.equals(it.next(), o)) { it.remove(); return true; } } return false; } } @Override default boolean removeAll(Collection<?> c) { if (c.isEmpty()) return false; try (Transaction t = lock(true, null)) { boolean modified = false; Iterator<?> it = iterator(); while (it.hasNext()) { if (c.contains(it.next())) { it.remove(); modified = true; } } return modified; } } @Override default boolean retainAll(Collection<?> c) { if (c.isEmpty()) { clear(); return false; } try (Transaction t = lock(true, null)) { boolean modified = false; Iterator<E> it = iterator(); while (it.hasNext()) { if (!c.contains(it.next())) { it.remove(); modified = true; } } return modified; } } @Override default void clear() { try (Transaction t = lock(true, null)) { Iterator<E> it = iterator(); while (it.hasNext()) { it.next(); it.remove(); } } } } /** * Builds a filtered and/or mapped collection * * @param <E> The type of values in the source collection * @param <I> Intermediate type * @param <T> The type of values in the mapped collection */ class MappedQollectionBuilder<E, I, T> { private final Qollection<E> theWrapped; private final MappedQollectionBuilder<E, ?, I> theParent; private final TypeToken<T> theType; private Function<? super I, String> theFilter; private boolean areNullsFiltered; private Function<? super I, ? extends T> theMap; private boolean areNullsMapped; private Function<? super T, ? extends I> theReverse; private boolean areNullsReversed; protected MappedQollectionBuilder(Qollection<E> wrapped, MappedQollectionBuilder<E, ?, I> parent, TypeToken<T> type) { theWrapped = wrapped; theParent = parent; theType = type; } static <T> TypeToken<T> returnType(Function<?, ? extends T> fn) { return (TypeToken<T>) TypeToken.of(fn.getClass()).resolveType(Function.class.getTypeParameters()[1]); } public MappedQollectionBuilder<E, I, T> filter(Function<? super I, String> filter, boolean filterNulls) { theFilter = filter; areNullsFiltered = filterNulls; return this; } public MappedQollectionBuilder<E, I, T> map(Function<? super I, ? extends T> map, boolean mapNulls) { theMap = map; areNullsMapped = mapNulls; return this; } public MappedQollectionBuilder<E, I, T> withReverse(Function<? super T, ? extends I> reverse, boolean reverseNulls) { theReverse = reverse; areNullsReversed = reverseNulls; return this; } public FilterMapDef<E, I, T> toDef() { FilterMapDef<E, ?, I> parent = theParent == null ? null : theParent.toDef(); TypeToken<I> intermediate = parent == null ? (TypeToken<I>) theWrapped.getType() : parent.destType; return new FilterMapDef<>(theWrapped.getType(), intermediate, theType, parent, theFilter, areNullsFiltered, theMap, areNullsMapped, theReverse, areNullsReversed); } public Qollection<T> build() { if (theMap == null && !theWrapped.getType().equals(theType)) throw new IllegalStateException("Building a type-mapped collection with no map defined"); return theWrapped.filterMap(toDef()); } public <X> MappedQollectionBuilder<E, T, X> andThen(TypeToken<X> nextType) { return new MappedQollectionBuilder<>(theWrapped, this, nextType); } } /** * A definition for a filter/mapped collection * * @param <E> The type of values in the source collection * @param <I> Intermediate type, not exposed * @param <T> The type of values for the mapped collection */ class FilterMapDef<E, I, T> { public final TypeToken<E> sourceType; private final TypeToken<I> intermediateType; public final TypeToken<T> destType; private final FilterMapDef<E, ?, I> parent; private final Function<? super I, String> filter; private final boolean filterNulls; private final Function<? super I, ? extends T> map; private final boolean mapNulls; private final Function<? super T, ? extends I> reverse; private final boolean reverseNulls; public FilterMapDef(TypeToken<E> sourceType, TypeToken<I> intermediateType, TypeToken<T> type, FilterMapDef<E, ?, I> parent, Function<? super I, String> filter, boolean filterNulls, Function<? super I, ? extends T> map, boolean mapNulls, Function<? super T, ? extends I> reverse, boolean reverseNulls) { this.sourceType = sourceType; this.intermediateType = intermediateType; this.destType = type; this.parent = parent; this.filter = filter; this.filterNulls = filterNulls; this.map = map; this.mapNulls = mapNulls; this.reverse = reverse; this.reverseNulls = reverseNulls; if (parent == null && !sourceType.equals(intermediateType)) throw new IllegalArgumentException("A " + getClass().getName() + " with no parent must have identical source and intermediate types: " + sourceType + ", " + intermediateType); } public boolean checkSourceType(Object value) { return value == null || sourceType.getRawType().isInstance(value); } private boolean checkIntermediateType(I value) { return value == null || intermediateType.getRawType().isInstance(value); } public boolean checkDestType(Object value) { return value == null || destType.getRawType().isInstance(value); } public FilterMapResult<E, ?> checkSourceValue(FilterMapResult<E, ?> result) { return internalCheckSourceValue((FilterMapResult<E, I>) result); } private FilterMapResult<E, I> internalCheckSourceValue(FilterMapResult<E, I> result) { result.error = null; // Get the starting point for this def I interm; if (parent != null) { interm = parent.map(result).result; result.result = null; if (result.error != null) return result; if (!checkIntermediateType(interm)) throw new IllegalStateException( "Implementation error: intermediate value " + interm + " is not an instance of " + intermediateType); } else { interm = (I) result.source; if (!checkIntermediateType(interm)) throw new IllegalStateException("Source value " + interm + " is not an instance of " + intermediateType); } if (result.error != null) { return result; } // Filter if (filter != null) { if (!filterNulls && interm == null) result.error = StdMsg.NULL_DISALLOWED; else result.error = filter.apply(interm); } return result; } public FilterMapResult<E, T> map(FilterMapResult<E, T> result) { internalCheckSourceValue((FilterMapResult<E, I>) result); I interm = ((FilterMapResult<E, I>) result).result; // Map if (map == null) result.result = (T) interm; else if (interm == null && !mapNulls) result.result = null; else result.result = map.apply(interm); if (result.result != null && !destType.getRawType().isInstance(result.result)) throw new IllegalStateException("Result value " + result.result + " is not an instance of " + destType); return result; } public boolean isReversible() { return map == null || reverse != null; } public FilterMapResult<T, E> reverse(FilterMapResult<T, E> result) { if (!isReversible()) throw new IllegalStateException("This filter map is not reversible"); result.error = null; if (!checkDestType(result.source)) throw new IllegalStateException("Value to reverse " + result.source + " is not an instance of " + destType); // reverse map I interm; if (map == null) interm = (I) result.source; else if (result.source != null || reverseNulls) interm = reverse.apply(result.source); else interm = null; if (!checkIntermediateType(interm)) throw new IllegalStateException("Reversed value " + interm + " is not an instance of " + intermediateType); // Filter if (filter != null) { if (!filterNulls && interm == null) result.error = StdMsg.NULL_DISALLOWED; else result.error = filter.apply(interm); } if (result.error != null) return result; if (parent != null) { ((FilterMapResult<I, E>) result).source = interm; parent.reverse((FilterMapResult<I, E>) result); } else result.result = (E) interm; return result; } } /** * Used to query {@link Qollection.FilterMapDef} * * @see Qollection.FilterMapDef#checkSourceValue(FilterMapResult) * @see Qollection.FilterMapDef#map(FilterMapResult) * @see Qollection.FilterMapDef#reverse(FilterMapResult) * * @param <E> The source type * @param <T> The destination type */ class FilterMapResult<E, T> { public E source; public T result; public String error; public FilterMapResult() {} public FilterMapResult(E src) { source = src; } } /** * Implements {@link Qollection#buildMap(TypeToken)} * * @param <E> The type of the collection to filter/map * @param <T> The type of the filter/mapped collection */ class FilterMappedQollection<E, T> implements PartialQollectionImpl<T> { private final Qollection<E> theWrapped; private final FilterMapDef<E, ?, T> theDef; FilterMappedQollection(Qollection<E> wrap, FilterMapDef<E, ?, T> filterMapDef) { theWrapped = wrap; theDef = filterMapDef; } protected Qollection<E> getWrapped() { return theWrapped; } protected FilterMapDef<E, ?, T> getDef() { return theDef; } @Override public TypeToken<T> getType() { return theDef.destType; } @Override public Transaction lock(boolean write, Object cause) { return theWrapped.lock(write, cause); } @Override public int size() { if (theDef.filter == null) return theWrapped.size(); int[] size = new int[1]; FilterMapResult<E, T> result = new FilterMapResult<>(); theWrapped.spliterator().forEachRemaining(v -> { result.source = v; theDef.checkSourceValue(result); if (result.error == null) size[0]++; }); return size[0]; } @Override public Quiterator<T> spliterator() { return map(theWrapped.spliterator()); } @Override public boolean add(T e) { if (!theDef.isReversible() || !theDef.checkDestType(e)) return false; FilterMapResult<T, E> reversed = theDef.reverse(new FilterMapResult<>(e)); if (reversed.error != null) return false; return theWrapped.add(reversed.result); } @Override public boolean addAll(Collection<? extends T> c) { if (!theDef.isReversible()) return false; FilterMapResult<T, E> reversed = new FilterMapResult<>(); List<E> toAdd = c.stream().flatMap(v -> { if (!theDef.checkDestType(v)) return Stream.empty(); reversed.source = v; theDef.reverse(reversed); if (reversed.error == null) return Stream.of(reversed.result); else return Stream.empty(); }).collect(Collectors.toList()); if (toAdd.isEmpty()) return false; return theWrapped.addAll(toAdd); } @Override public boolean remove(Object o) { if (o != null && !theDef.checkDestType(o)) return false; boolean[] found = new boolean[1]; if (theDef.isReversible()) { FilterMapResult<T, E> reversed = theDef.reverse(new FilterMapResult<>((T) o)); if (reversed.error != null) return false; try (Transaction t = lock(true, null)) { while (!found[0] && theWrapped.spliterator().tryAdvanceElement(el -> { if (Objects.equals(el.get(), reversed.result)) { found[0] = true; el.remove(); } })) { } } } else { try (Transaction t = lock(true, null)) { FilterMapResult<E, T> result = new FilterMapResult<>(); while (!found[0] && theWrapped.spliterator().tryAdvanceElement(el -> { result.source = el.get(); theDef.map(result); if (result.error == null && Objects.equals(result.result, o)) { found[0] = true; el.remove(); } })) { } } } return found[0]; } @Override public boolean removeAll(Collection<?> c) { boolean[] removed = new boolean[1]; try (Transaction t = lock(true, null)) { FilterMapResult<E, T> result = new FilterMapResult<>(); theWrapped.spliterator().forEachElement(el -> { result.source = el.get(); theDef.map(result); if (result.error == null && c.contains(result.result)) { el.remove(); removed[0] = true; } }); } return removed[0]; } @Override public boolean retainAll(Collection<?> c) { boolean[] removed = new boolean[1]; try (Transaction t = lock(true, null)) { FilterMapResult<E, T> result = new FilterMapResult<>(); theWrapped.spliterator().forEachElement(el -> { result.source = el.get(); theDef.map(result); if (result.error == null && !c.contains(result.result)) { el.remove(); removed[0] = true; } }); } return removed[0]; } @Override public void clear() { try (Transaction t = lock(true, null)) { FilterMapResult<E, T> result = new FilterMapResult<>(); theWrapped.spliterator().forEachElement(el -> { result.source = el.get(); theDef.checkSourceValue(result); if (result.error == null) el.remove(); }); } } @Override public String canRemove(Object value) { if (!theDef.isReversible()) return StdMsg.UNSUPPORTED_OPERATION; else if (!theDef.checkDestType(value)) return StdMsg.BAD_TYPE; FilterMapResult<T, E> reversed = theDef.reverse(new FilterMapResult<>((T) value)); if (reversed.error != null) return reversed.error; return theWrapped.canRemove(reversed.result); } @Override public String canAdd(T value) { if (!theDef.isReversible()) return StdMsg.UNSUPPORTED_OPERATION; else if (!theDef.checkDestType(value)) return StdMsg.BAD_TYPE; FilterMapResult<T, E> reversed = theDef.reverse(new FilterMapResult<>(value)); if (reversed.error != null) return reversed.error; return theWrapped.canAdd(reversed.result); } protected Quiterator<T> map(Quiterator<E> iter) { return new WrappingQuiterator<>(iter, () -> { CollectionElement<? extends E>[] container = new CollectionElement[1]; FilterMapResult<E, T> mapped = new FilterMapResult<>(); WrappingElement<E, T> wrapperEl = new WrappingElement<E, T>(getType(), container) { @Override public T get() { return mapped.result; } @Override public <V extends T> String isAcceptable(V value) { if (!theDef.isReversible()) return StdMsg.UNSUPPORTED_OPERATION; else if (!theDef.checkDestType(value)) return StdMsg.BAD_TYPE; FilterMapResult<T, E> reversed = theDef.reverse(new FilterMapResult<>(value)); if (reversed.error != null) return reversed.error; return ((CollectionElement<E>) getWrapped()).isAcceptable(reversed.result); } @Override public <V extends T> T set(V value, Object cause) throws IllegalArgumentException { if (!theDef.isReversible()) throw new IllegalArgumentException(StdMsg.UNSUPPORTED_OPERATION); else if (!theDef.checkDestType(value)) throw new IllegalArgumentException(StdMsg.BAD_TYPE); FilterMapResult<T, E> reversed = theDef.reverse(new FilterMapResult<>(value)); if (reversed.error != null) throw new IllegalArgumentException(reversed.error); ((CollectionElement<E>) getWrapped()).set(reversed.result, cause); T old = mapped.result; mapped.source = reversed.result; mapped.result = value; return old; } }; return el -> { mapped.source = el.get(); theDef.map(mapped); if (mapped.error != null) return null; container[0] = el; return wrapperEl; }; }); } @Override public String toString() { return Qollection.toString(this); } } /** * Implements {@link Qollection#combine(Value, BiFunction)} * * @param <E> The type of the collection to be combined * @param <T> The type of the value to combine the collection elements with * @param <V> The type of the combined collection */ class CombinedQollection<E, T, V> implements PartialQollectionImpl<V> { private final Qollection<E> theWrapped; private final TypeToken<V> theType; private final Value<T> theValue; private final BiFunction<? super E, ? super T, V> theMap; private final BiFunction<? super V, ? super T, E> theReverse; protected CombinedQollection(Qollection<E> wrap, TypeToken<V> type, Value<T> value, BiFunction<? super E, ? super T, V> map, BiFunction<? super V, ? super T, E> reverse) { theWrapped = wrap; theType = type; theValue = value; theMap = map; theReverse = reverse; } protected Qollection<E> getWrapped() { return theWrapped; } protected Value<T> getValue() { return theValue; } protected BiFunction<? super E, ? super T, V> getMap() { return theMap; } protected BiFunction<? super V, ? super T, E> getReverse() { return theReverse; } @Override public Transaction lock(boolean write, Object cause) { return theWrapped.lock(write, cause); } @Override public TypeToken<V> getType() { return theType; } @Override public int size() { return theWrapped.size(); } @Override public boolean add(V e) { if (theReverse == null) throw new UnsupportedOperationException(StdMsg.UNSUPPORTED_OPERATION); else return theWrapped.add(theReverse.apply(e, theValue.get())); } @Override public boolean addAll(Collection<? extends V> c) { if (theReverse == null) throw new UnsupportedOperationException(StdMsg.UNSUPPORTED_OPERATION); else { T combineValue = theValue.get(); return theWrapped.addAll(c.stream().map(o -> theReverse.apply(o, combineValue)).collect(Collectors.toList())); } } @Override public boolean remove(Object o) { try (Transaction t = lock(true, null)) { T combineValue = theValue.get(); Iterator<E> iter = theWrapped.iterator(); while (iter.hasNext()) { E el = iter.next(); if (Objects.equals(getMap().apply(el, combineValue), o)) { iter.remove(); return true; } } } return false; } @Override public boolean removeAll(Collection<?> c) { boolean ret = false; try (Transaction t = lock(true, null)) { T combineValue = theValue.get(); Iterator<E> iter = theWrapped.iterator(); while (iter.hasNext()) { E el = iter.next(); if (c.contains(getMap().apply(el, combineValue))) { iter.remove(); ret = true; } } } return ret; } @Override public boolean retainAll(Collection<?> c) { boolean ret = false; try (Transaction t = lock(true, null)) { T combineValue = theValue.get(); Iterator<E> iter = theWrapped.iterator(); while (iter.hasNext()) { E el = iter.next(); if (!c.contains(getMap().apply(el, combineValue))) { iter.remove(); ret = true; } } } return ret; } @Override public void clear() { getWrapped().clear(); } @Override public String canRemove(Object value) { if (theReverse != null && (value == null || theType.getRawType().isInstance(value))) return theWrapped.canRemove(theReverse.apply((V) value, theValue.get())); else return StdMsg.UNSUPPORTED_OPERATION; } @Override public String canAdd(V value) { if (theReverse != null) return theWrapped.canAdd(theReverse.apply(value, theValue.get())); else return StdMsg.UNSUPPORTED_OPERATION; } @Override public Quiterator<V> spliterator() { Supplier<Function<CollectionElement<? extends E>, CollectionElement<V>>> elementMap = () -> { CollectionElement<? extends E>[] container = new CollectionElement[1]; WrappingElement<E, V> wrapper = new WrappingElement<E, V>(getType(), container) { @Override public V get() { return theMap.apply(getWrapped().get(), theValue.get()); } @Override public <V2 extends V> String isAcceptable(V2 value) { if (theReverse == null) return StdMsg.UNSUPPORTED_OPERATION; E reverse = theReverse.apply(value, theValue.get()); return ((CollectionElement<E>) getWrapped()).isAcceptable(reverse); } @Override public <V2 extends V> V set(V2 value, Object cause) throws IllegalArgumentException { if (theReverse == null) throw new IllegalArgumentException(StdMsg.UNSUPPORTED_OPERATION); E reverse = theReverse.apply(value, theValue.get()); return theMap.apply(((CollectionElement<E>) getWrapped()).set(reverse, cause), theValue.get()); } }; return el -> { container[0] = el; return wrapper; }; }; return new WrappingQuiterator<>(theWrapped.spliterator(), elementMap); } @Override public String toString() { return Qollection.toString(this); } } /** * Implements {@link Qollection#groupBy(Function)} * * @param <K> The key type of the map * @param <E> The value type of the map */ class GroupedMultiMap<K, E> implements MultiQMap<K, E> { private final Qollection<E> theWrapped; private final Function<E, K> theKeyMap; private final TypeToken<K> theKeyType; private final QSet<K> theKeySet; GroupedMultiMap(Qollection<E> wrap, Function<E, K> keyMap, TypeToken<K> keyType) { theWrapped = wrap; theKeyMap = keyMap; theKeyType = keyType != null ? keyType : (TypeToken<K>) TypeToken.of(keyMap.getClass()).resolveType(Function.class.getTypeParameters()[1]); Qollection<K> mapped; if (theKeyMap != null) mapped = theWrapped.map(theKeyMap); else mapped = (Qollection<K>) theWrapped; theKeySet = unique(mapped); } protected QSet<K> unique(Qollection<K> keyCollection) { return QSet.unique(keyCollection); } @Override public TypeToken<K> getKeyType() { return theKeyType; } @Override public TypeToken<E> getValueType() { return theWrapped.getType(); } @Override public Transaction lock(boolean write, Object cause) { return theWrapped.lock(write, cause); } @Override public QSet<K> keySet() { return theKeySet; } @Override public Qollection<E> get(Object key) { return theWrapped.filter(el -> Objects.equals(theKeyMap.apply(el), key) ? null : StdMsg.GROUP_EXISTS); } @Override public QSet<? extends MultiQEntry<K, E>> entrySet() { return MultiQMap.defaultEntrySet(this); } @Override public String toString() { return entrySet().toString(); } } /** * An entry in a {@link Qollection.GroupedMultiMap} * * @param <K> The key type of the entry * @param <E> The value type of the entry */ class GroupedMultiEntry<K, E> implements MultiQMap.MultiQEntry<K, E> { private final K theKey; private final Function<E, K> theKeyMap; private final Qollection<E> theElements; GroupedMultiEntry(K key, Qollection<E> wrap, Function<E, K> keyMap) { theKey = key; theKeyMap = keyMap; theElements = wrap.filter(el -> Objects.equals(theKey, theKeyMap.apply(el)) ? null : StdMsg.WRONG_GROUP); } @Override public K getKey() { return theKey; } @Override public TypeToken<E> getType() { return theElements.getType(); } @Override public Transaction lock(boolean write, Object cause) { return theElements.lock(write, cause); } @Override public int size() { return theElements.size(); } @Override public Iterator<E> iterator() { return theElements.iterator(); } @Override public boolean add(E e) { return theElements.add(e); } @Override public boolean remove(Object o) { return theElements.remove(o); } @Override public boolean addAll(Collection<? extends E> c) { return theElements.addAll(c); } @Override public boolean removeAll(Collection<?> c) { return theElements.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return theElements.retainAll(c); } @Override public void clear() { theElements.clear(); } @Override public String canRemove(Object value) { return theElements.canRemove(value); } @Override public String canAdd(E value) { return theElements.canAdd(value); } @Override public Quiterator<E> spliterator() { return theElements.spliterator(); } @Override public boolean equals(Object o) { if (this == o) return true; return o instanceof MultiEntry && Objects.equals(theKey, ((MultiEntry<?, ?>) o).getKey()); } @Override public int hashCode() { return Objects.hashCode(theKey); } @Override public String toString() { return getKey() + "=" + Qollection.toString(this); } } /** * Implements {@link Qollection#groupBy(Function, Comparator)} * * @param <K> The key type of the map * @param <E> The value type of the map */ class GroupedSortedMultiMap<K, E> implements SortedMultiQMap<K, E> { private final Qollection<E> theWrapped; private final Function<E, K> theKeyMap; private final TypeToken<K> theKeyType; private final Comparator<? super K> theCompare; private final SortedQSet<K> theKeySet; GroupedSortedMultiMap(Qollection<E> wrap, Function<E, K> keyMap, TypeToken<K> keyType, Comparator<? super K> compare) { theWrapped = wrap; theKeyMap = keyMap; theKeyType = keyType != null ? keyType : (TypeToken<K>) TypeToken.of(keyMap.getClass()).resolveType(Function.class.getTypeParameters()[1]); theCompare = compare; Qollection<K> mapped; if (theKeyMap != null) mapped = theWrapped.map(theKeyMap); else mapped = (Qollection<K>) theWrapped; theKeySet = SortedQSet.unique(mapped, theCompare); } @Override public Comparator<? super K> comparator() { return theCompare; } @Override public TypeToken<K> getKeyType() { return theKeyType; } @Override public TypeToken<E> getValueType() { return theWrapped.getType(); } @Override public Transaction lock(boolean write, Object cause) { return theWrapped.lock(write, cause); } @Override public SortedQSet<K> keySet() { return theKeySet; } @Override public Qollection<E> get(Object key) { if (!theKeyType.getRawType().isInstance(key)) return QList.constant(getValueType()); return theWrapped.filter(el -> theCompare.compare(theKeyMap.apply(el), (K) key) == 0 ? null : StdMsg.WRONG_GROUP); } @Override public SortedQSet<? extends SortedMultiQEntry<K, E>> entrySet() { return SortedMultiQMap.defaultEntrySet(this); } @Override public String toString() { return entrySet().toString(); } } /** * A collection that cannot be modified directly, but reflects the values in a wrapped collection * * @param <E> The type of elements in the collection */ class ImmutableQollection<E> implements PartialQollectionImpl<E> { private final Qollection<E> theWrapped; private final String theModificationMessage; /** * @param wrap The collection to wrap * @param modMsg The message to return when modifications are requested */ protected ImmutableQollection(Qollection<E> wrap, String modMsg) { theWrapped = wrap; theModificationMessage = modMsg; } protected Qollection<E> getWrapped() { return theWrapped; } protected String getModMessage() { return theModificationMessage; } @Override public Transaction lock(boolean write, Object cause) { if (write) throw new IllegalArgumentException(theModificationMessage); return theWrapped.lock(false, cause); } @Override public Quiterator<E> spliterator() { return new WrappingQuiterator<>(theWrapped.spliterator(), () -> { CollectionElement<E>[] container = new CollectionElement[1]; WrappingElement<E, E> wrapperEl = new WrappingElement<E, E>(getType(), container) { @Override public E get() { return getWrapped().get(); } @Override public <V extends E> E set(V value, Object cause) throws IllegalArgumentException { throw new IllegalArgumentException(theModificationMessage); } @Override public <V extends E> String isAcceptable(V value) { return theModificationMessage; } @Override public Value<String> isEnabled() { return Value.constant(theModificationMessage); } @Override public String canRemove() { return theModificationMessage; } @Override public void remove() { throw new IllegalArgumentException(canRemove()); } }; return el -> { container[0] = (CollectionElement<E>) el; return wrapperEl; }; }); } @Override public TypeToken<E> getType() { return theWrapped.getType(); } @Override public int size() { return theWrapped.size(); } @Override public String canRemove(Object value) { return theModificationMessage; } @Override public String canAdd(E value) { return theModificationMessage; } @Override public Qollection<E> immutable(String modMsg) { if (modMsg.equals(theModificationMessage)) return this; else return theWrapped.immutable(modMsg); } @Override public String toString() { return theWrapped.toString(); } } /** * Implements {@link Qollection#filterModification(Function, Function)} * * @param <E> The type of the collection to control */ class ModFilteredQollection<E> implements PartialQollectionImpl<E> { private final Qollection<E> theWrapped; private final Function<? super E, String> theRemoveFilter; private final Function<? super E, String> theAddFilter; public ModFilteredQollection(Qollection<E> wrapped, Function<? super E, String> removeFilter, Function<? super E, String> addFilter) { theWrapped = wrapped; theRemoveFilter = removeFilter; theAddFilter = addFilter; } protected Qollection<E> getWrapped() { return theWrapped; } protected Function<? super E, String> getRemoveFilter() { return theRemoveFilter; } protected Function<? super E, String> getAddFilter() { return theAddFilter; } @Override public TypeToken<E> getType() { return theWrapped.getType(); } @Override public Quiterator<E> spliterator() { return new WrappingQuiterator<>(theWrapped.spliterator(), () -> { CollectionElement<E>[] container = new CollectionElement[1]; WrappingElement<E, E> wrapperEl = new WrappingElement<E, E>(getType(), container) { @Override public E get() { return getWrapped().get(); } @Override public <V extends E> String isAcceptable(V value) { String s = null; if (theAddFilter != null) s = theAddFilter.apply(value); if (s == null) s = ((CollectionElement<E>) getWrapped()).isAcceptable(value); return s; } @Override public <V extends E> E set(V value, Object cause) throws IllegalArgumentException { if (theAddFilter != null) { String s = theAddFilter.apply(value); if (s != null) throw new IllegalArgumentException(s); } return ((CollectionElement<E>) getWrapped()).set(value, cause); } @Override public String canRemove() { String s = null; if (theRemoveFilter != null) s = theRemoveFilter.apply(get()); if (s == null) s = getWrapped().canRemove(); return s; } @Override public void remove() { if (theRemoveFilter != null) { String s = theRemoveFilter.apply(get()); if (s != null) throw new IllegalArgumentException(s); } getWrapped().remove(); } }; return el -> { container[0] = (CollectionElement<E>) el; return wrapperEl; }; }); } @Override public Transaction lock(boolean write, Object cause) { return theWrapped.lock(write, cause); } @Override public int size() { return theWrapped.size(); } @Override public boolean add(E value) { if (theAddFilter == null || theAddFilter.apply(value) == null) return theWrapped.add(value); else return false; } @Override public boolean addAll(Collection<? extends E> values) { if (theAddFilter != null) return theWrapped.addAll(values.stream().filter(v -> theAddFilter.apply(v) == null).collect(Collectors.toList())); else return theWrapped.addAll(values); } @Override public boolean remove(Object value) { if (theRemoveFilter == null) return theWrapped.remove(value); try (Transaction t = lock(true, null)) { Iterator<E> iter = theWrapped.iterator(); while (iter.hasNext()) { E next = iter.next(); if (!Objects.equals(next, value)) continue; if (theRemoveFilter.apply(next) == null) { iter.remove(); return true; } else return false; } } return false; } @Override public boolean removeAll(Collection<?> values) { if (theRemoveFilter == null) return theWrapped.removeAll(values); BitSet remove = new BitSet(); int i = 0; try (Transaction t = lock(true, null)) { Iterator<E> iter = theWrapped.iterator(); while (iter.hasNext()) { E next = iter.next(); if (!values.contains(next)) continue; if (theRemoveFilter.apply(next) == null) remove.set(i); i++; } if (!remove.isEmpty()) { i = 0; iter = theWrapped.iterator(); while (iter.hasNext()) { iter.next(); if (remove.get(i)) iter.remove(); i++; } } } return !remove.isEmpty(); } @Override public boolean retainAll(Collection<?> values) { if (theRemoveFilter == null) return theWrapped.retainAll(values); BitSet remove = new BitSet(); int i = 0; try (Transaction t = lock(true, null)) { Iterator<E> iter = theWrapped.iterator(); while (iter.hasNext()) { E next = iter.next(); if (values.contains(next)) continue; if (theRemoveFilter.apply(next) == null) remove.set(i); i++; } if (!remove.isEmpty()) { i = 0; iter = theWrapped.iterator(); while (iter.hasNext()) { iter.next(); if (remove.get(i)) iter.remove(); i++; } } } return !remove.isEmpty(); } @Override public void clear() { if (theRemoveFilter == null) { theWrapped.clear(); return; } BitSet remove = new BitSet(); int i = 0; Iterator<E> iter = theWrapped.iterator(); while (iter.hasNext()) { E next = iter.next(); if (theRemoveFilter.apply(next) == null) remove.set(i); i++; } i = 0; iter = theWrapped.iterator(); while (iter.hasNext()) { iter.next(); if (remove.get(i)) iter.remove(); i++; } } @Override public String canRemove(Object value) { String s = null; if (theRemoveFilter != null) { if (value != null && !theWrapped.getType().getRawType().isInstance(value)) s = StdMsg.BAD_TYPE; if (s == null) s = theRemoveFilter.apply((E) value); } if (s == null) s = theWrapped.canRemove(value); return s; } @Override public String canAdd(E value) { String s = null; if (theAddFilter != null) s = theAddFilter.apply(value); if (s == null) s = theWrapped.canAdd(value); return s; } @Override public String toString() { return theWrapped.toString(); } } /** * Implements {@link Qollection#constant(TypeToken, Collection)} * * @param <E> The type of elements in the collection */ class ConstantQollection<E> implements PartialQollectionImpl<E> { private final TypeToken<E> theType; private final Collection<E> theCollection; public ConstantQollection(TypeToken<E> type, Collection<E> collection) { theType = type; theCollection = collection; } @Override public TypeToken<E> getType() { return theType; } @Override public Quiterator<E> spliterator() { Supplier<? extends Function<? super E, ? extends CollectionElement<E>>> fn; fn = () -> { Object[] elementValue = new Object[1]; CollectionElement<E> el = new CollectionElement<E>() { @Override public <V extends E> E set(V value, Object cause) throws IllegalArgumentException { throw new IllegalArgumentException(StdMsg.UNSUPPORTED_OPERATION); } @Override public <V extends E> String isAcceptable(V value) { return StdMsg.UNSUPPORTED_OPERATION; } @Override public Value<String> isEnabled() { return Value.constant(StdMsg.UNSUPPORTED_OPERATION); } @Override public TypeToken<E> getType() { return ConstantQollection.this.getType(); } @Override public E get() { return (E) elementValue[0]; } @Override public String canRemove() { return StdMsg.UNSUPPORTED_OPERATION; } @Override public void remove() { throw new IllegalArgumentException(canRemove()); } }; return v -> { elementValue[0] = v; return el; }; }; return new Quiterator.SimpleQuiterator<>(theCollection.spliterator(), fn); } @Override public String canRemove(Object value) { return StdMsg.UNSUPPORTED_OPERATION; } @Override public String canAdd(E value) { return StdMsg.UNSUPPORTED_OPERATION; } @Override public int size() { return theCollection.size(); } @Override public Iterator<E> iterator() { return IterableUtils.immutableIterator(theCollection.iterator()); } @Override public Transaction lock(boolean write, Object cause) { return Transaction.NONE; } } /** * Implements {@link Qollection#flattenValues(Qollection)} * * @param <E> The type of elements in the collection */ class FlattenedValuesQollection<E> implements PartialQollectionImpl<E> { private Qollection<? extends Value<? extends E>> theCollection; private final TypeToken<E> theType; protected FlattenedValuesQollection(Qollection<? extends Value<? extends E>> collection) { theCollection = collection; theType = (TypeToken<E>) theCollection.getType().resolveType(Value.class.getTypeParameters()[0]); } /** @return The collection of values that this collection flattens */ protected Qollection<? extends Value<? extends E>> getWrapped() { return theCollection; } @Override public Transaction lock(boolean write, Object cause) { return theCollection.lock(write, cause); } @Override public TypeToken<E> getType() { return theType; } @Override public Quiterator<E> spliterator() { Supplier<Function<CollectionElement<? extends Value<? extends E>>, CollectionElement<E>>> fn; fn = () -> { CollectionElement<Value<? extends E>>[] container = new CollectionElement[1]; WrappingElement<Value<? extends E>, E> wrapper = new WrappingElement<Value<? extends E>, E>(getType(), container) { @Override public <V extends E> E set(V value, Object cause) throws IllegalArgumentException { Value<? extends E> element = getWrapped().get(); if (!(element instanceof Settable)) throw new IllegalArgumentException(StdMsg.UNSUPPORTED_OPERATION); if (value != null && !element.getType().getRawType().isInstance(value)) throw new IllegalArgumentException(StdMsg.BAD_TYPE); return ((Settable<E>) element).set(value, cause); } @Override public <V extends E> String isAcceptable(V value) { Value<? extends E> element = getWrapped().get(); if (!(element instanceof Settable)) return StdMsg.UNSUPPORTED_OPERATION; if (value != null && !element.getType().getRawType().isInstance(value)) return StdMsg.BAD_TYPE; return ((Settable<E>) element).isAcceptable(value); } @Override public E get() { return getWrapped().get().get(); } @Override public Value<String> isEnabled() { Value<? extends E> element = getWrapped().get(); return new Value<String>() { @Override public TypeToken<String> getType() { return TypeToken.of(String.class); } @Override public String get() { if (!(element instanceof Settable)) return StdMsg.UNSUPPORTED_OPERATION; return ((Settable<? extends E>) element).isEnabled().get(); } }; } }; return el -> { container[0] = (CollectionElement<Value<? extends E>>) el; return wrapper; }; }; return new WrappingQuiterator<Value<? extends E>, E>(theCollection.spliterator(), fn); } @Override public String canRemove(Object value) { boolean[] found = new boolean[1]; String[] msg = new String[1]; Quiterator<? extends Value<? extends E>> iter = theCollection.spliterator(); while (!found[0] && iter.tryAdvance(v -> { if (Objects.equals(v.get(), value)) { found[0] = true; msg[0] = ((Qollection<Value<? extends E>>) theCollection).canRemove(v); } })) { } if (!found[0]) return StdMsg.NOT_FOUND; return msg[0]; } @Override public String canAdd(E value) { return StdMsg.UNSUPPORTED_OPERATION; } @Override public int size() { return theCollection.size(); } @Override public String toString() { return Qollection.toString(this); } } /** * Implements {@link Qollection#flattenValue(Value)} * * @param <E> The type of elements in the collection */ class FlattenedValueQollection<E> implements PartialQollectionImpl<E> { private final Value<? extends Qollection<E>> theCollectionObservable; private final TypeToken<E> theType; protected FlattenedValueQollection(Value<? extends Qollection<E>> collectionObservable) { theCollectionObservable = collectionObservable; theType = (TypeToken<E>) theCollectionObservable.getType().resolveType(Qollection.class.getTypeParameters()[0]); } protected Value<? extends Qollection<E>> getWrapped() { return theCollectionObservable; } @Override public TypeToken<E> getType() { return theType; } @Override public int size() { Qollection<? extends E> coll = theCollectionObservable.get(); return coll == null ? 0 : coll.size(); } @Override public Iterator<E> iterator() { Qollection<? extends E> coll = theCollectionObservable.get(); return coll == null ? Collections.EMPTY_LIST.iterator() : (Iterator<E>) coll.iterator(); } @Override public String canRemove(Object value) { Qollection<E> current = theCollectionObservable.get(); if (current == null) return StdMsg.UNSUPPORTED_OPERATION; return current.canRemove(value); } @Override public String canAdd(E value) { Qollection<E> current = theCollectionObservable.get(); if (current == null) return StdMsg.UNSUPPORTED_OPERATION; return current.canAdd(value); } @Override public Transaction lock(boolean write, Object cause) { Qollection<? extends E> coll = theCollectionObservable.get(); return coll == null ? Transaction.NONE : coll.lock(write, cause); } @Override public Quiterator<E> spliterator() { Qollection<? extends E> coll = theCollectionObservable.get(); if (coll == null) { return new Quiterator<E>() { @Override public long estimateSize() { return 0; } @Override public int characteristics() { return Spliterator.IMMUTABLE | Spliterator.SIZED; } @Override public boolean tryAdvanceElement(Consumer<? super CollectionElement<E>> action) { return false; } @Override public Quiterator<E> trySplit() { return null; } }; } Supplier<Function<CollectionElement<? extends E>, CollectionElement<E>>> fn; fn = () -> { CollectionElement<? extends E>[] container = new CollectionElement[1]; WrappingElement<E, E> wrappingEl = new WrappingElement<E, E>(getType(), container) { @Override public <V extends E> E set(V value, Object cause) throws IllegalArgumentException { if (!getWrapped().getType().getRawType().isInstance(value)) throw new IllegalArgumentException(StdMsg.BAD_TYPE); return ((CollectionElement<E>) getWrapped()).set(value, cause); } @Override public <V extends E> String isAcceptable(V value) { if (!getWrapped().getType().getRawType().isInstance(value)) return StdMsg.BAD_TYPE; return ((CollectionElement<E>) getWrapped()).isAcceptable(value); } @Override public E get() { return getWrapped().get(); } }; return el -> { container[0] = el; return wrappingEl; }; }; return new WrappingQuiterator<>(coll.spliterator(), fn); } @Override public String toString() { return Qollection.toString(this); } } /** * Implements {@link Qollection#flatten(Qollection)} * * @param <E> The type of elements in the collection */ class FlattenedQollection<E> implements PartialQollectionImpl<E> { private final Qollection<? extends Qollection<? extends E>> theOuter; private final TypeToken<E> theType; protected FlattenedQollection(Qollection<? extends Qollection<? extends E>> collection) { theOuter = collection; theType = (TypeToken<E>) theOuter.getType().resolveType(Qollection.class.getTypeParameters()[0]); } protected Qollection<? extends Qollection<? extends E>> getWrapped() { return theOuter; } @Override public Transaction lock(boolean write, Object cause) { Transaction outer = theOuter.lock(write, cause); Transaction[] inner = new Transaction[theOuter.size()]; int[] i = new int[1]; theOuter.spliterator().forEachRemaining(coll -> inner[i[0]++] = coll.lock(write, cause)); return () -> { for (int j = 0; j < inner.length; j++) inner[j].close(); outer.close(); }; } @Override public TypeToken<E> getType() { return theType; } @Override public int size() { int ret = 0; for (Qollection<? extends E> subColl : theOuter) ret += subColl.size(); return ret; } @Override public String canRemove(Object value) { if (theOuter.isEmpty()) return StdMsg.UNSUPPORTED_OPERATION; String msg = null; for (Qollection<? extends E> sub : theOuter) { if (sub.contains(value)) { String subMsg = sub.canRemove(value); if (subMsg == null) return null; else if (msg == null) msg = subMsg; } } return msg; } @Override public boolean remove(Object o) { if (theOuter.isEmpty()) return false; for (Qollection<? extends E> sub : theOuter) { if (sub.remove(o)) return true; } return false; } @Override public String canAdd(E value) { if (theOuter.isEmpty()) return StdMsg.UNSUPPORTED_OPERATION; String msg = null; for (Qollection<? extends E> sub : theOuter) { if (value == null || sub.getType().getRawType().isInstance(value)) { String subMsg = ((OrderedQollection<E>) sub).canAdd(value); if (subMsg == null) return null; else if (msg == null) msg = subMsg; } } return msg; } @Override public boolean add(E e) { if (theOuter.isEmpty()) return false; for (Qollection<? extends E> sub : theOuter) { if (e == null || sub.getType().getRawType().isInstance(e)) { if (((Qollection<E>) sub).add(e)) return true; } } return false; } @Override public void clear() { for (Qollection<? extends E> sub : theOuter) sub.clear(); } @Override public Quiterator<E> spliterator() { return new Quiterator<E>() { private final Quiterator<? extends Qollection<? extends E>> theOuterator = theOuter.spliterator(); private WrappingQuiterator<E, E> theInnerator; private Supplier<Function<CollectionElement<? extends E>, CollectionElement<E>>> theElementMap; private AtomicInteger counted = new AtomicInteger(); { theElementMap = () -> { CollectionElement<? extends E>[] container = new CollectionElement[1]; WrappingElement<E, E> wrapper = new WrappingElement<E, E>(getType(), container) { @Override public E get() { return getWrapped().get(); } @Override public <V extends E> E set(V value, Object cause) throws IllegalArgumentException { if (!getWrapped().getType().getRawType().isInstance(value)) throw new IllegalArgumentException(StdMsg.BAD_TYPE); return ((CollectionElement<E>) getWrapped()).set(value, cause); } @Override public <V extends E> String isAcceptable(V value) { if (!getWrapped().getType().getRawType().isInstance(value)) return StdMsg.BAD_TYPE; return ((CollectionElement<E>) getWrapped()).isAcceptable(value); } }; return el -> { counted.incrementAndGet(); container[0] = el; return wrapper; }; }; } @Override public long estimateSize() { return size() - counted.get(); } @Override public int characteristics() { return Spliterator.SIZED; } @Override public boolean tryAdvanceElement(Consumer<? super CollectionElement<E>> action) { if (theInnerator == null && !theOuterator.tryAdvance(coll -> theInnerator = new WrappingQuiterator<>(coll.spliterator(), theElementMap))) return false; while (!theInnerator.tryAdvanceElement(action)) { if (!theOuterator.tryAdvance(coll -> theInnerator = new WrappingQuiterator<>(coll.spliterator(), theElementMap))) return false; } return true; } @Override public void forEachElement(Consumer<? super CollectionElement<E>> action) { theOuterator.forEachRemaining(coll -> { new WrappingQuiterator<>(coll.spliterator(), theElementMap).forEachElement(action); }); } @Override public Quiterator<E> trySplit() { Quiterator<E>[] ret = new Quiterator[1]; theOuterator.tryAdvance(coll -> { counted.addAndGet(coll.size()); ret[0] = new WrappingQuiterator<>(coll.spliterator(), theElementMap); }); return ret[0]; } }; } @Override public String toString() { return Qollection.toString(this); } } }
package net.sf.mzmine.main; import net.sf.mzmine.modules.batchmode.BatchModeModule; import net.sf.mzmine.modules.masslistmethods.ADAPchromatogrambuilder.ADAPChromatogramBuilderModule; import net.sf.mzmine.modules.masslistmethods.chromatogrambuilder.ChromatogramBuilderModule; import net.sf.mzmine.modules.masslistmethods.shoulderpeaksfilter.ShoulderPeaksFilterModule; import net.sf.mzmine.modules.peaklistmethods.alignment.adap3.ADAP3AlignerModule; import net.sf.mzmine.modules.peaklistmethods.alignment.hierarchical.HierarAlignerGcModule; import net.sf.mzmine.modules.peaklistmethods.alignment.join.JoinAlignerModule; import net.sf.mzmine.modules.peaklistmethods.alignment.ransac.RansacAlignerModule; import net.sf.mzmine.modules.peaklistmethods.dataanalysis.clustering.ClusteringModule; import net.sf.mzmine.modules.peaklistmethods.dataanalysis.heatmaps.HeatMapModule; import net.sf.mzmine.modules.peaklistmethods.dataanalysis.projectionplots.CDAPlotModule; import net.sf.mzmine.modules.peaklistmethods.dataanalysis.projectionplots.PCAPlotModule; import net.sf.mzmine.modules.peaklistmethods.dataanalysis.projectionplots.SammonsPlotModule; import net.sf.mzmine.modules.peaklistmethods.dataanalysis.rtmzplots.cvplot.CVPlotModule; import net.sf.mzmine.modules.peaklistmethods.dataanalysis.rtmzplots.logratioplot.LogratioPlotModule; import net.sf.mzmine.modules.peaklistmethods.dataanalysis.significance.SignificanceModule; import net.sf.mzmine.modules.peaklistmethods.filtering.clearannotations.PeaklistClearAnnotationsModule; import net.sf.mzmine.modules.peaklistmethods.filtering.duplicatefilter.DuplicateFilterModule; import net.sf.mzmine.modules.peaklistmethods.filtering.groupms2.GroupMS2Module; import net.sf.mzmine.modules.peaklistmethods.filtering.neutralloss.NeutralLossFilterModule; import net.sf.mzmine.modules.peaklistmethods.filtering.peakcomparisonrowfilter.PeakComparisonRowFilterModule; import net.sf.mzmine.modules.peaklistmethods.filtering.peakfilter.PeakFilterModule; import net.sf.mzmine.modules.peaklistmethods.filtering.rowsfilter.RowsFilterModule; import net.sf.mzmine.modules.peaklistmethods.gapfilling.peakfinder.PeakFinderModule; import net.sf.mzmine.modules.peaklistmethods.gapfilling.peakfinder.multithreaded.MultiThreadPeakFinderModule; import net.sf.mzmine.modules.peaklistmethods.gapfilling.samerange.SameRangeGapFillerModule; import net.sf.mzmine.modules.peaklistmethods.identification.adductsearch.AdductSearchModule; import net.sf.mzmine.modules.peaklistmethods.identification.camera.CameraSearchModule; import net.sf.mzmine.modules.peaklistmethods.identification.complexsearch.ComplexSearchModule; import net.sf.mzmine.modules.peaklistmethods.identification.customdbsearch.CustomDBSearchModule; import net.sf.mzmine.modules.peaklistmethods.identification.formulaprediction.FormulaPredictionModule; import net.sf.mzmine.modules.peaklistmethods.identification.formulapredictionpeaklist.FormulaPredictionPeakListModule; import net.sf.mzmine.modules.peaklistmethods.identification.fragmentsearch.FragmentSearchModule; import net.sf.mzmine.modules.peaklistmethods.identification.gnpsresultsimport.GNPSResultsImportModule; import net.sf.mzmine.modules.peaklistmethods.identification.lipididentification.LipidSearchModule; import net.sf.mzmine.modules.peaklistmethods.identification.ms2search.Ms2SearchModule; import net.sf.mzmine.modules.peaklistmethods.identification.nist.NistMsSearchModule; import net.sf.mzmine.modules.peaklistmethods.identification.onlinedbsearch.OnlineDBSearchModule; import net.sf.mzmine.modules.peaklistmethods.identification.precursordbsearch.PrecursorDBSearchModule; import net.sf.mzmine.modules.peaklistmethods.identification.sirius.SiriusProcessingModule; import net.sf.mzmine.modules.peaklistmethods.identification.spectraldbsearch.LocalSpectralDBSearchModule; import net.sf.mzmine.modules.peaklistmethods.identification.spectraldbsearch.sort.SortSpectralDBIdentitiesModule; import net.sf.mzmine.modules.peaklistmethods.io.adapmgfexport.AdapMgfExportModule; import net.sf.mzmine.modules.peaklistmethods.io.csvexport.CSVExportModule; import net.sf.mzmine.modules.peaklistmethods.io.gnpsexport.GNPSExportAndSubmitModule; import net.sf.mzmine.modules.peaklistmethods.io.metaboanalystexport.MetaboAnalystExportModule; import net.sf.mzmine.modules.peaklistmethods.io.mspexport.MSPExportModule; import net.sf.mzmine.modules.peaklistmethods.io.mztabexport.MzTabExportModule; import net.sf.mzmine.modules.peaklistmethods.io.mztabimport.MzTabImportModule; import net.sf.mzmine.modules.peaklistmethods.io.siriusexport.SiriusExportModule; import net.sf.mzmine.modules.peaklistmethods.io.spectraldbsubmit.LibrarySubmitModule; import net.sf.mzmine.modules.peaklistmethods.io.sqlexport.SQLExportModule; import net.sf.mzmine.modules.peaklistmethods.io.xmlexport.XMLExportModule; import net.sf.mzmine.modules.peaklistmethods.io.xmlimport.XMLImportModule; import net.sf.mzmine.modules.peaklistmethods.isotopes.deisotoper.IsotopeGrouperModule; import net.sf.mzmine.modules.peaklistmethods.isotopes.isotopepeakscanner.IsotopePeakScannerModule; import net.sf.mzmine.modules.peaklistmethods.isotopes.isotopeprediction.IsotopePatternCalculator; import net.sf.mzmine.modules.peaklistmethods.normalization.linear.LinearNormalizerModule; import net.sf.mzmine.modules.peaklistmethods.normalization.rtcalibration.RTCalibrationModule; import net.sf.mzmine.modules.peaklistmethods.normalization.standardcompound.StandardCompoundNormalizerModule; import net.sf.mzmine.modules.peaklistmethods.peakpicking.adap3decompositionV1_5.ADAP3DecompositionV1_5Module; import net.sf.mzmine.modules.peaklistmethods.peakpicking.adap3decompositionV2.ADAP3DecompositionV2Module; import net.sf.mzmine.modules.peaklistmethods.peakpicking.deconvolution.DeconvolutionModule; import net.sf.mzmine.modules.peaklistmethods.peakpicking.peakextender.PeakExtenderModule; import net.sf.mzmine.modules.peaklistmethods.peakpicking.shapemodeler.ShapeModelerModule; import net.sf.mzmine.modules.peaklistmethods.peakpicking.smoothing.SmoothingModule; import net.sf.mzmine.modules.peaklistmethods.sortpeaklists.SortPeakListsModule; import net.sf.mzmine.modules.projectmethods.projectclose.ProjectCloseModule; import net.sf.mzmine.modules.projectmethods.projectload.ProjectLoadModule; import net.sf.mzmine.modules.projectmethods.projectsave.ProjectSaveAsModule; import net.sf.mzmine.modules.projectmethods.projectsave.ProjectSaveModule; import net.sf.mzmine.modules.rawdatamethods.exportscans.ExportScansFromRawFilesModule; import net.sf.mzmine.modules.rawdatamethods.exportscans.ExportScansModule; import net.sf.mzmine.modules.rawdatamethods.extractscans.ExtractScansModule; import net.sf.mzmine.modules.rawdatamethods.filtering.alignscans.AlignScansModule; import net.sf.mzmine.modules.rawdatamethods.filtering.baselinecorrection.BaselineCorrectionModule; import net.sf.mzmine.modules.rawdatamethods.filtering.cropper.CropFilterModule; import net.sf.mzmine.modules.rawdatamethods.filtering.scanfilters.ScanFiltersModule; import net.sf.mzmine.modules.rawdatamethods.filtering.scansmoothing.ScanSmoothingModule; import net.sf.mzmine.modules.rawdatamethods.merge.RawFileMergeModule; import net.sf.mzmine.modules.rawdatamethods.peakpicking.gridmass.GridMassModule; import net.sf.mzmine.modules.rawdatamethods.peakpicking.manual.ManualPeakPickerModule; import net.sf.mzmine.modules.rawdatamethods.peakpicking.manual.XICManualPickerModule; import net.sf.mzmine.modules.rawdatamethods.peakpicking.massdetection.MassDetectionModule; import net.sf.mzmine.modules.rawdatamethods.peakpicking.msms.MsMsPeakPickerModule; import net.sf.mzmine.modules.rawdatamethods.peakpicking.targetedpeakdetection.TargetedPeakDetectionModule; import net.sf.mzmine.modules.rawdatamethods.rawdataexport.RawDataExportModule; import net.sf.mzmine.modules.rawdatamethods.rawdataimport.RawDataImportModule; import net.sf.mzmine.modules.rawdatamethods.sortdatafiles.SortDataFilesModule; import net.sf.mzmine.modules.tools.isotopepatternpreview.IsotopePatternPreviewModule; import net.sf.mzmine.modules.tools.msmsspectramerge.MsMsSpectraMergeModule; import net.sf.mzmine.modules.tools.mzrangecalculator.MzRangeFormulaCalculatorModule; import net.sf.mzmine.modules.tools.mzrangecalculator.MzRangeMassCalculatorModule; import net.sf.mzmine.modules.visualization.fx3d.Fx3DVisualizerModule; import net.sf.mzmine.modules.visualization.histogram.HistogramVisualizerModule; import net.sf.mzmine.modules.visualization.infovisualizer.InfoVisualizerModule; import net.sf.mzmine.modules.visualization.intensityplot.IntensityPlotModule; import net.sf.mzmine.modules.visualization.kendrickmassplot.KendrickMassPlotModule; import net.sf.mzmine.modules.visualization.mzhistogram.MZDistributionHistoModule; import net.sf.mzmine.modules.visualization.neutralloss.NeutralLossVisualizerModule; import net.sf.mzmine.modules.visualization.peaklisttable.PeakListTableModule; import net.sf.mzmine.modules.visualization.peaklisttable.export.IsotopePatternExportModule; import net.sf.mzmine.modules.visualization.peaklisttable.export.MSMSExportModule; import net.sf.mzmine.modules.visualization.productionfilter.ProductIonFilterVisualizerModule; import net.sf.mzmine.modules.visualization.scatterplot.ScatterPlotVisualizerModule; import net.sf.mzmine.modules.visualization.spectra.msms.MsMsVisualizerModule; import net.sf.mzmine.modules.visualization.spectra.simplespectra.SpectraVisualizerModule; import net.sf.mzmine.modules.visualization.spectra.simplespectra.datapointprocessing.DataPointProcessingManager; import net.sf.mzmine.modules.visualization.spectra.simplespectra.datapointprocessing.identification.sumformulaprediction.DPPSumFormulaPredictionModule; import net.sf.mzmine.modules.visualization.spectra.simplespectra.datapointprocessing.isotopes.deisotoper.DPPIsotopeGrouperModule; import net.sf.mzmine.modules.visualization.spectra.simplespectra.datapointprocessing.massdetection.DPPMassDetectionModule; import net.sf.mzmine.modules.visualization.spectra.simplespectra.spectraidentification.customdatabase.CustomDBSpectraSearchModule; import net.sf.mzmine.modules.visualization.spectra.simplespectra.spectraidentification.lipidsearch.LipidSpectraSearchModule; import net.sf.mzmine.modules.visualization.spectra.simplespectra.spectraidentification.onlinedatabase.OnlineDBSpectraSearchModule; import net.sf.mzmine.modules.visualization.spectra.simplespectra.spectraidentification.spectraldatabase.SpectraIdentificationSpectralDatabaseModule; import net.sf.mzmine.modules.visualization.spectra.simplespectra.spectraidentification.sumformula.SumFormulaSpectraSearchModule; import net.sf.mzmine.modules.visualization.spectra.spectralmatchresults.SpectraIdentificationResultsModule; import net.sf.mzmine.modules.visualization.tic.TICVisualizerModule; import net.sf.mzmine.modules.visualization.twod.TwoDVisualizerModule; import net.sf.mzmine.modules.visualization.vankrevelendiagram.VanKrevelenDiagramModule; /** * List of modules included in MZmine 2 */ public class MZmineModulesList { public static final Class<?> MODULES[] = new Class<?>[] { // Project methods ProjectLoadModule.class, ProjectSaveModule.class, ProjectSaveAsModule.class, ProjectCloseModule.class, // Batch mode BatchModeModule.class, // Raw data methods RawDataImportModule.class, RawDataExportModule.class, ExportScansFromRawFilesModule.class, RawFileMergeModule.class, ExtractScansModule.class, MassDetectionModule.class, ShoulderPeaksFilterModule.class, ChromatogramBuilderModule.class, ADAPChromatogramBuilderModule.class, // Not ready for prime time: ADAP3DModule.class, GridMassModule.class, ManualPeakPickerModule.class, MsMsPeakPickerModule.class, ScanFiltersModule.class, CropFilterModule.class, BaselineCorrectionModule.class, AlignScansModule.class, ScanSmoothingModule.class, SortDataFilesModule.class, XICManualPickerModule.class, // Alignment SortPeakListsModule.class, JoinAlignerModule.class, HierarAlignerGcModule.class, RansacAlignerModule.class, ADAP3AlignerModule.class, // PathAlignerModule.class, CSVExportModule.class, MetaboAnalystExportModule.class, MzTabExportModule.class, SQLExportModule.class, XMLExportModule.class, MzTabImportModule.class, XMLImportModule.class, MSPExportModule.class, AdapMgfExportModule.class, GNPSExportAndSubmitModule.class, SiriusExportModule.class, // Gap filling PeakFinderModule.class, MultiThreadPeakFinderModule.class, SameRangeGapFillerModule.class, // Isotopes IsotopeGrouperModule.class, IsotopePatternCalculator.class, IsotopePeakScannerModule.class, // Feature detection SmoothingModule.class, DeconvolutionModule.class, ShapeModelerModule.class, PeakExtenderModule.class, TargetedPeakDetectionModule.class, ADAP3DecompositionV1_5Module.class, ADAP3DecompositionV2Module.class, // Feature list filtering GroupMS2Module.class, DuplicateFilterModule.class, RowsFilterModule.class, PeakComparisonRowFilterModule.class, PeakFilterModule.class, PeaklistClearAnnotationsModule.class, NeutralLossFilterModule.class, // Normalization RTCalibrationModule.class, LinearNormalizerModule.class, StandardCompoundNormalizerModule.class, // Data analysis CVPlotModule.class, LogratioPlotModule.class, PCAPlotModule.class, CDAPlotModule.class, SammonsPlotModule.class, ClusteringModule.class, HeatMapModule.class, SignificanceModule.class, // Identification LocalSpectralDBSearchModule.class, PrecursorDBSearchModule.class, SortSpectralDBIdentitiesModule.class, CustomDBSearchModule.class, FormulaPredictionModule.class, FragmentSearchModule.class, AdductSearchModule.class, ComplexSearchModule.class, OnlineDBSearchModule.class, LipidSearchModule.class, CameraSearchModule.class, NistMsSearchModule.class, FormulaPredictionPeakListModule.class, Ms2SearchModule.class, SiriusProcessingModule.class, GNPSResultsImportModule.class, // Visualizers TICVisualizerModule.class, SpectraVisualizerModule.class, TwoDVisualizerModule.class, Fx3DVisualizerModule.class, MsMsVisualizerModule.class, NeutralLossVisualizerModule.class, MZDistributionHistoModule.class, PeakListTableModule.class, IsotopePatternExportModule.class, MSMSExportModule.class, ScatterPlotVisualizerModule.class, HistogramVisualizerModule.class, InfoVisualizerModule.class, IntensityPlotModule.class, KendrickMassPlotModule.class, VanKrevelenDiagramModule.class, ProductIonFilterVisualizerModule.class, // Tools MzRangeMassCalculatorModule.class, MzRangeFormulaCalculatorModule.class, IsotopePatternPreviewModule.class, MsMsSpectraMergeModule.class, // all other regular MZmineModule (not MZmineRunnableModule) NOT LISTED IN MENU SpectraIdentificationSpectralDatabaseModule.class, LibrarySubmitModule.class, CustomDBSpectraSearchModule.class, LipidSpectraSearchModule.class, OnlineDBSpectraSearchModule.class, SumFormulaSpectraSearchModule.class, ExportScansModule.class, SpectraIdentificationResultsModule.class, // Data point processing, implement DataPointProcessingModule DataPointProcessingManager.class, DPPMassDetectionModule.class, DPPSumFormulaPredictionModule.class, DPPIsotopeGrouperModule.class}; }
package net.simpvp.Misc; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityPotionEffectEvent; import org.bukkit.potion.PotionEffectType; //This file disables elder guardians from giving mining fatigue within 100 blocks of spawn public class PotionEffectListener implements Listener { List<?> listOfWorlds = Misc.instance.getConfig().getList("disableElderGuardians"); @EventHandler public void potionEffectEvent(EntityPotionEffectEvent event) { //Check if world name is in the config if (!listOfWorlds.contains(event.getEntity().getWorld().getName())) { return; } //If entity is less than 100 blocks from spawn if (event.getEntity().getLocation().distanceSquared(event.getEntity().getWorld().getSpawnLocation()) <= 100*100) { //If potion equals mining fatigue and the event is from the "attack" cause if (event.getModifiedType().equals(PotionEffectType.SLOW_DIGGING) && event.getCause().equals(EntityPotionEffectEvent.Cause.ATTACK)) { //Cancel event event.setCancelled(true); } } } }
package net.snowflake.client.log; import net.snowflake.client.util.SecretDetector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.helpers.FormattingTuple; import org.slf4j.helpers.MessageFormatter; import org.slf4j.spi.LocationAwareLogger; public class SLF4JLogger implements SFLogger { private Logger slf4jLogger; private boolean isLocationAwareLogger; private static final String FQCN = SLF4JLogger.class.getName(); public SLF4JLogger(Class<?> clazz) { slf4jLogger = LoggerFactory.getLogger(clazz); isLocationAwareLogger = slf4jLogger instanceof LocationAwareLogger; } public SLF4JLogger(String name) { slf4jLogger = LoggerFactory.getLogger(name); isLocationAwareLogger = slf4jLogger instanceof LocationAwareLogger; } public boolean isDebugEnabled() { return this.slf4jLogger.isDebugEnabled(); } public boolean isErrorEnabled() { return this.slf4jLogger.isErrorEnabled(); } public boolean isInfoEnabled() { return this.slf4jLogger.isInfoEnabled(); } public boolean isTraceEnabled() { return this.slf4jLogger.isTraceEnabled(); } public boolean isWarnEnabled() { return this.slf4jLogger.isWarnEnabled(); } public void debug(String msg, boolean isMasked) { msg = isMasked == true ? SecretDetector.maskSecrets(msg) : msg; if (isLocationAwareLogger) { ((LocationAwareLogger) slf4jLogger) .log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, null); } else { slf4jLogger.debug(msg); } } // This function is used to display unmasked, potentially sensitive log information for internal // regression testing purposes. Do not use otherwise public void debugNoMask(String msg) { if (isLocationAwareLogger) { ((LocationAwareLogger) slf4jLogger) .log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, null); } else { slf4jLogger.debug(msg); } } public void debug(String msg, Object... arguments) { // use this as format example for JDK14Logger. if (isDebugEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, evaluateLambdaArgs(arguments)); this.debug(SecretDetector.maskSecrets(ft.getMessage()), true); } } public void debug(String msg, Throwable t) { msg = SecretDetector.maskSecrets(msg); if (isLocationAwareLogger) { ((LocationAwareLogger) slf4jLogger) .log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, t); } else { slf4jLogger.debug(msg, t); } } public void error(String msg, boolean isMasked) { msg = isMasked == true ? SecretDetector.maskSecrets(msg) : msg; if (isLocationAwareLogger) { ((LocationAwareLogger) slf4jLogger) .log(null, FQCN, LocationAwareLogger.ERROR_INT, msg, null, null); } else { slf4jLogger.error(msg); } } public void error(String msg, Object... arguments) { if (isErrorEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, evaluateLambdaArgs(arguments)); this.error(SecretDetector.maskSecrets(ft.getMessage()), true); } } public void error(String msg, Throwable t) { msg = SecretDetector.maskSecrets(msg); if (isLocationAwareLogger) { ((LocationAwareLogger) slf4jLogger) .log(null, FQCN, LocationAwareLogger.ERROR_INT, msg, null, t); } else { slf4jLogger.error(msg, t); } } public void info(String msg, boolean isMasked) { msg = isMasked == true ? SecretDetector.maskSecrets(msg) : msg; if (isLocationAwareLogger) { ((LocationAwareLogger) slf4jLogger) .log(null, FQCN, LocationAwareLogger.INFO_INT, msg, null, null); } else { slf4jLogger.info(msg); } } public void info(String msg, Object... arguments) { if (isInfoEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, evaluateLambdaArgs(arguments)); this.info(SecretDetector.maskSecrets(ft.getMessage()), true); } } public void info(String msg, Throwable t) { msg = SecretDetector.maskSecrets(msg); if (isLocationAwareLogger) { ((LocationAwareLogger) slf4jLogger) .log(null, FQCN, LocationAwareLogger.INFO_INT, msg, null, t); } else { slf4jLogger.error(msg, t); } } public void trace(String msg, boolean isMasked) { msg = isMasked == true ? SecretDetector.maskSecrets(msg) : msg; if (isLocationAwareLogger) { ((LocationAwareLogger) slf4jLogger) .log(null, FQCN, LocationAwareLogger.TRACE_INT, msg, null, null); } else { slf4jLogger.trace(msg); } } public void trace(String msg, Object... arguments) { if (isTraceEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, evaluateLambdaArgs(arguments)); this.trace(SecretDetector.maskSecrets(ft.getMessage()), true); } } public void trace(String msg, Throwable t) { msg = SecretDetector.maskSecrets(msg); if (isLocationAwareLogger) { ((LocationAwareLogger) slf4jLogger) .log(null, FQCN, LocationAwareLogger.TRACE_INT, msg, null, t); } else { slf4jLogger.trace(msg, t); } } public void warn(String msg, boolean isMasked) { msg = isMasked == true ? SecretDetector.maskSecrets(msg) : msg; if (isLocationAwareLogger) { ((LocationAwareLogger) slf4jLogger) .log(null, FQCN, LocationAwareLogger.WARN_INT, msg, null, null); } else { slf4jLogger.error(msg); } } public void warn(String msg, Object... arguments) { if (isWarnEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, evaluateLambdaArgs(arguments)); this.warn(SecretDetector.maskSecrets(ft.getMessage()), true); } } public void warn(String msg, Throwable t) { msg = SecretDetector.maskSecrets(msg); if (isLocationAwareLogger) { ((LocationAwareLogger) slf4jLogger) .log(null, FQCN, LocationAwareLogger.WARN_INT, msg, null, t); } else { slf4jLogger.error(msg, t); } } private static Object[] evaluateLambdaArgs(Object... args) { final Object[] result = new Object[args.length]; for (int i = 0; i < args.length; i++) { result[i] = args[i] instanceof ArgSupplier ? ((ArgSupplier) args[i]).get() : args[i]; } return result; } }
package ru.kpecmuk.snakegame.game; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.kpecmuk.snakegame.apple.Apples; import ru.kpecmuk.snakegame.graphics.Display; import ru.kpecmuk.snakegame.graphics.GameField; import ru.kpecmuk.snakegame.snake.Snake; import ru.kpecmuk.snakegame.utils.Time; import java.awt.*; /** * @author kpecmuk * @since 24.10.2017 */ public class Game implements Runnable { private static final Logger log = LoggerFactory.getLogger(Game.class); private static final int FIELD_X_SIZE = 30; private static final int FIELD_Y_SIZE = 25; public static final int CELL_SIZE = 32; public static final int CLEAR_COLOR = 0xff_40_40_40; public static final int WINDOW_WIDTH = CELL_SIZE * FIELD_X_SIZE + 5; public static final int WINDOW_HEIGHT = CELL_SIZE * FIELD_Y_SIZE + 5; public static final String WINDOW_TITLE = "Snake"; public static final int NUMBER_OF_BUFFERS = 3; private boolean isRunning; private Display display; private Graphics2D graphics; private Thread gameThread; private Time time; private static final long IDLE_TIME = 1; private static final float UPDATE_RATE = 60.0f; private static long GAME_SPEED = 500_000_000L; private GameField gameField; private Snake snake; private Apples apples; private boolean needToMove = false; private long moveLastTime = 0; public Game(Display display) { this.isRunning = false; this.display = display; this.display.createWindow(); this.graphics = display.getGraphics(); this.time = new Time(); this.gameField = new GameField(); this.snake = new Snake(this.graphics, FIELD_X_SIZE / 2, FIELD_Y_SIZE / 2); this.apples = new Apples(this.graphics, FIELD_X_SIZE / 4, FIELD_Y_SIZE / 4); } public synchronized void startGame() { if (isRunning) return; isRunning = true; gameThread = new Thread(this); gameThread.start(); } synchronized void stopGame() { if (!isRunning) return; try { gameThread.join(); } catch (InterruptedException e) { log.error(String.valueOf(e)); } finally { this.isRunning = false; cleanUp(); } } private void cleanUp() { display.destroyWindow(); } private void doRender() { display.clear(); gameField.drawField(graphics); apples.drawApples(); snake.drawSnake(graphics); display.swapBuffers(); } private void update() { apples.check(); if (needToMove) { snake.getMovement().moveUp(); needToMove = false; } } @Override public void run() { float delta = 0; int fps = 0, upd = 0, updateLoops = 0; long count = 0; long lastTime = time.getTime(); while (isRunning) { long currentTime = time.getTime(); if (currentTime - moveLastTime > GAME_SPEED) { needToMove = true; moveLastTime = currentTime; } long elapsedTime = currentTime - lastTime; lastTime = currentTime; count += elapsedTime; boolean needRender = false; float UPDATE_INTERVAL = time.getSecond() / UPDATE_RATE; delta += (elapsedTime / UPDATE_INTERVAL); while (delta > 1) { update(); upd++; delta if (needRender) { updateLoops++; } else { needRender = true; } } if (needRender) { doRender(); fps++; } else { try { Thread.sleep(IDLE_TIME); } catch (InterruptedException e) { log.error(String.valueOf(e)); } } if (count >= time.getSecond()) { String title = WINDOW_TITLE + " || fps:" + fps + " | Upd: " + upd + " | Loops: " + updateLoops; display.setWindowTitle(title); count = upd = updateLoops = fps = 0; } } } }
package vizceral.hystrix; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.base64.Base64; import io.netty.handler.codec.http.HttpMethod; import io.reactivex.netty.RxNetty; import io.reactivex.netty.pipeline.PipelineConfigurators; import io.reactivex.netty.pipeline.ssl.DefaultFactories; import io.reactivex.netty.protocol.http.client.HttpClient; import io.reactivex.netty.protocol.http.client.HttpClientBuilder; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import java.util.concurrent.TimeUnit; import java.io.IOException; import java.net.ConnectException; import java.nio.charset.StandardCharsets; /** * Reads a hystrix event stream (typically from turbine) and emits events when items are received in the SSE stream. */ public class HystrixReader { private static final Logger logger = LoggerFactory.getLogger(HystrixReader.class); private static final ObjectMapper objectMapper = new ObjectMapper(); private final HttpClient<ByteBuf, ServerSentEvent> rxNetty; private final Configuration configuration; private final String cluster; /** * Creates a new hystrix reader. * * @param configuration The configuration to use. * @param cluster The cluster to read from. */ public HystrixReader(Configuration configuration, String cluster) { this.configuration = configuration; this.cluster = cluster; HttpClientBuilder<ByteBuf, ServerSentEvent> builder = RxNetty.newHttpClientBuilder(configuration.getTurbineHost(), configuration.getTurbinePort()); builder.pipelineConfigurator(PipelineConfigurators.clientSseConfigurator()); if (configuration.isSecure()) { builder.withSslEngineFactory(DefaultFactories.trustAll()); } rxNetty = builder.build(); } /** * Starts reading Sever Sent Events from hystrix and emits one item to the observable per HystrixCommand type event. * * @return Observable that can be subscribed to receive events from hystrix. */ public Observable<HystrixEvent> read() { String path = configuration.getTurbinePath(cluster); logger.info("Starting to read from path {}", path); final HttpClientRequest<ByteBuf> request = HttpClientRequest.create(HttpMethod.GET, path); if (configuration.authEnabled()) { String authHeader = "Basic " + Base64.encode(Unpooled.copiedBuffer(configuration.getUsername() + ":" + configuration.getPassword(), StandardCharsets.UTF_8)).toString(StandardCharsets.UTF_8).replace("\n", ""); request.getHeaders().add("Authorization", authHeader); } return rxNetty.submit(request) .flatMap(c -> { logger.info("Http code {} for path {} in region {}", c.getStatus().code(), path, configuration.getRegionName()); if (c.getStatus().code() == 404) { return Observable.error(new UnknownClusterException("Turbine does not recognize cluster " + cluster)); } else if (c.getStatus().code() != 200) { return Observable.error(new IllegalStateException("Got " + c.getStatus().code() + " from turbine")); } else { return c.getContent(); } }) .map(sse -> { try { JsonNode objectNode = objectMapper.readTree(sse.contentAsString()); if (!"HystrixCommand".equals(objectNode.get("type").asText())) { return null; } String commandName = objectNode.get("name").asText(); String group = configuration.getEffectiveGroup(objectNode.get("group").asText()); if (group.isEmpty()) { logger.warn("Invalid hystrix event with an empty group for command {}", commandName); return null; } return HystrixEvent .newBuilder() .rejectedCount((sumFields(objectNode, "rollingCountSemaphoreRejected", "rollingCountThreadPoolRejected")) / 10) .timeoutCount(objectNode.get("rollingCountTimeout").asInt() / 10) .errorCount((sumFields(objectNode, "rollingCountFailure", "rollingCountSemaphoreRejected", "rollingCountShortCircuited") / 10)) .requestCount(objectNode.get("rollingCountSuccess").asInt() / 10) .totalRequestCount(objectNode.get("requestCount").asInt() / 10) .group(group) .name(commandName) .isCircuitBreakerOpen(objectNode.get("isCircuitBreakerOpen").asBoolean()) .build(); } catch (IOException e) { logger.error("Could not parse json", e); return null; } }) .filter(c -> c != null) .onErrorResumeNext(ex -> { if (ex instanceof ConnectException) { try { TimeUnit.SECONDS.sleep(10); } catch (Exception ignore) { }; } if (!(ex instanceof UnknownClusterException || ex instanceof IllegalStateException)) { logger.error("Exception from hystrix event for cluster " + cluster + " for region " + configuration.getRegionName() + ". Will retry", ex); return read(); } return Observable.error(ex); }); } private static int sumFields(JsonNode objectNode, String... keys) { int sum = 0; for (String key : keys) { if (objectNode.has(key)) { sum += objectNode.get(key).asInt(); } } return sum; } }
package nom.bdezonia.zorbage.misc; import java.util.ArrayList; import java.util.List; import nom.bdezonia.zorbage.algebra.Algebra; import nom.bdezonia.zorbage.algebra.G; import nom.bdezonia.zorbage.data.DimensionedDataSource; import nom.bdezonia.zorbage.tuple.Tuple2; import nom.bdezonia.zorbage.type.bool.BooleanMember; import nom.bdezonia.zorbage.type.character.CharMember; import nom.bdezonia.zorbage.type.color.ArgbMember; import nom.bdezonia.zorbage.type.color.RgbMember; import nom.bdezonia.zorbage.type.complex.float128.ComplexFloat128Member; import nom.bdezonia.zorbage.type.complex.float16.ComplexFloat16CartesianTensorProductMember; import nom.bdezonia.zorbage.type.complex.float16.ComplexFloat16MatrixMember; import nom.bdezonia.zorbage.type.complex.float16.ComplexFloat16Member; import nom.bdezonia.zorbage.type.complex.float16.ComplexFloat16VectorMember; import nom.bdezonia.zorbage.type.complex.float32.ComplexFloat32CartesianTensorProductMember; import nom.bdezonia.zorbage.type.complex.float32.ComplexFloat32MatrixMember; import nom.bdezonia.zorbage.type.complex.float32.ComplexFloat32Member; import nom.bdezonia.zorbage.type.complex.float32.ComplexFloat32VectorMember; import nom.bdezonia.zorbage.type.complex.float64.ComplexFloat64CartesianTensorProductMember; import nom.bdezonia.zorbage.type.complex.float64.ComplexFloat64MatrixMember; import nom.bdezonia.zorbage.type.complex.float64.ComplexFloat64Member; import nom.bdezonia.zorbage.type.complex.float64.ComplexFloat64VectorMember; import nom.bdezonia.zorbage.type.complex.highprec.ComplexHighPrecisionCartesianTensorProductMember; import nom.bdezonia.zorbage.type.complex.highprec.ComplexHighPrecisionMatrixMember; import nom.bdezonia.zorbage.type.complex.highprec.ComplexHighPrecisionMember; import nom.bdezonia.zorbage.type.complex.highprec.ComplexHighPrecisionVectorMember; import nom.bdezonia.zorbage.type.gaussian.int16.GaussianInt16Member; import nom.bdezonia.zorbage.type.gaussian.int32.GaussianInt32Member; import nom.bdezonia.zorbage.type.gaussian.int64.GaussianInt64Member; import nom.bdezonia.zorbage.type.gaussian.int8.GaussianInt8Member; import nom.bdezonia.zorbage.type.gaussian.unbounded.GaussianIntUnboundedMember; import nom.bdezonia.zorbage.type.integer.int1.SignedInt1Member; import nom.bdezonia.zorbage.type.integer.int1.UnsignedInt1Member; import nom.bdezonia.zorbage.type.integer.int10.SignedInt10Member; import nom.bdezonia.zorbage.type.integer.int10.UnsignedInt10Member; import nom.bdezonia.zorbage.type.integer.int11.SignedInt11Member; import nom.bdezonia.zorbage.type.integer.int11.UnsignedInt11Member; import nom.bdezonia.zorbage.type.integer.int12.SignedInt12Member; import nom.bdezonia.zorbage.type.integer.int12.UnsignedInt12Member; import nom.bdezonia.zorbage.type.integer.int128.SignedInt128Member; import nom.bdezonia.zorbage.type.integer.int128.UnsignedInt128Member; import nom.bdezonia.zorbage.type.integer.int13.SignedInt13Member; import nom.bdezonia.zorbage.type.integer.int13.UnsignedInt13Member; import nom.bdezonia.zorbage.type.integer.int14.SignedInt14Member; import nom.bdezonia.zorbage.type.integer.int14.UnsignedInt14Member; import nom.bdezonia.zorbage.type.integer.int15.SignedInt15Member; import nom.bdezonia.zorbage.type.integer.int15.UnsignedInt15Member; import nom.bdezonia.zorbage.type.integer.int16.SignedInt16Member; import nom.bdezonia.zorbage.type.integer.int16.UnsignedInt16Member; import nom.bdezonia.zorbage.type.integer.int2.SignedInt2Member; import nom.bdezonia.zorbage.type.integer.int2.UnsignedInt2Member; import nom.bdezonia.zorbage.type.integer.int3.SignedInt3Member; import nom.bdezonia.zorbage.type.integer.int3.UnsignedInt3Member; import nom.bdezonia.zorbage.type.integer.int32.SignedInt32Member; import nom.bdezonia.zorbage.type.integer.int32.UnsignedInt32Member; import nom.bdezonia.zorbage.type.integer.int4.SignedInt4Member; import nom.bdezonia.zorbage.type.integer.int4.UnsignedInt4Member; import nom.bdezonia.zorbage.type.integer.int5.SignedInt5Member; import nom.bdezonia.zorbage.type.integer.int5.UnsignedInt5Member; import nom.bdezonia.zorbage.type.integer.int6.SignedInt6Member; import nom.bdezonia.zorbage.type.integer.int6.UnsignedInt6Member; import nom.bdezonia.zorbage.type.integer.int64.SignedInt64Member; import nom.bdezonia.zorbage.type.integer.int64.UnsignedInt64Member; import nom.bdezonia.zorbage.type.integer.int7.SignedInt7Member; import nom.bdezonia.zorbage.type.integer.int7.UnsignedInt7Member; import nom.bdezonia.zorbage.type.integer.int8.SignedInt8Member; import nom.bdezonia.zorbage.type.integer.int8.UnsignedInt8Member; import nom.bdezonia.zorbage.type.integer.int9.SignedInt9Member; import nom.bdezonia.zorbage.type.integer.int9.UnsignedInt9Member; import nom.bdezonia.zorbage.type.integer.unbounded.UnboundedIntMember; import nom.bdezonia.zorbage.type.octonion.float16.OctonionFloat16CartesianTensorProductMember; import nom.bdezonia.zorbage.type.octonion.float16.OctonionFloat16MatrixMember; import nom.bdezonia.zorbage.type.octonion.float16.OctonionFloat16Member; import nom.bdezonia.zorbage.type.octonion.float16.OctonionFloat16RModuleMember; import nom.bdezonia.zorbage.type.octonion.float32.OctonionFloat32CartesianTensorProductMember; import nom.bdezonia.zorbage.type.octonion.float32.OctonionFloat32MatrixMember; import nom.bdezonia.zorbage.type.octonion.float32.OctonionFloat32Member; import nom.bdezonia.zorbage.type.octonion.float32.OctonionFloat32RModuleMember; import nom.bdezonia.zorbage.type.octonion.float64.OctonionFloat64CartesianTensorProductMember; import nom.bdezonia.zorbage.type.octonion.float64.OctonionFloat64MatrixMember; import nom.bdezonia.zorbage.type.octonion.float64.OctonionFloat64Member; import nom.bdezonia.zorbage.type.octonion.float64.OctonionFloat64RModuleMember; import nom.bdezonia.zorbage.type.octonion.highprec.OctonionHighPrecisionCartesianTensorProductMember; import nom.bdezonia.zorbage.type.octonion.highprec.OctonionHighPrecisionMatrixMember; import nom.bdezonia.zorbage.type.octonion.highprec.OctonionHighPrecisionMember; import nom.bdezonia.zorbage.type.octonion.highprec.OctonionHighPrecisionRModuleMember; import nom.bdezonia.zorbage.type.point.Point; import nom.bdezonia.zorbage.type.quaternion.float16.QuaternionFloat16CartesianTensorProductMember; import nom.bdezonia.zorbage.type.quaternion.float16.QuaternionFloat16MatrixMember; import nom.bdezonia.zorbage.type.quaternion.float16.QuaternionFloat16Member; import nom.bdezonia.zorbage.type.quaternion.float16.QuaternionFloat16RModuleMember; import nom.bdezonia.zorbage.type.quaternion.float32.QuaternionFloat32CartesianTensorProductMember; import nom.bdezonia.zorbage.type.quaternion.float32.QuaternionFloat32MatrixMember; import nom.bdezonia.zorbage.type.quaternion.float32.QuaternionFloat32Member; import nom.bdezonia.zorbage.type.quaternion.float32.QuaternionFloat32RModuleMember; import nom.bdezonia.zorbage.type.quaternion.float64.QuaternionFloat64CartesianTensorProductMember; import nom.bdezonia.zorbage.type.quaternion.float64.QuaternionFloat64MatrixMember; import nom.bdezonia.zorbage.type.quaternion.float64.QuaternionFloat64Member; import nom.bdezonia.zorbage.type.quaternion.float64.QuaternionFloat64RModuleMember; import nom.bdezonia.zorbage.type.quaternion.highprec.QuaternionHighPrecisionCartesianTensorProductMember; import nom.bdezonia.zorbage.type.quaternion.highprec.QuaternionHighPrecisionMatrixMember; import nom.bdezonia.zorbage.type.quaternion.highprec.QuaternionHighPrecisionMember; import nom.bdezonia.zorbage.type.quaternion.highprec.QuaternionHighPrecisionRModuleMember; import nom.bdezonia.zorbage.type.rational.RationalMember; import nom.bdezonia.zorbage.type.real.float128.Float128Member; import nom.bdezonia.zorbage.type.real.float16.Float16CartesianTensorProductMember; import nom.bdezonia.zorbage.type.real.float16.Float16MatrixMember; import nom.bdezonia.zorbage.type.real.float16.Float16Member; import nom.bdezonia.zorbage.type.real.float16.Float16VectorMember; import nom.bdezonia.zorbage.type.real.float32.Float32CartesianTensorProductMember; import nom.bdezonia.zorbage.type.real.float32.Float32MatrixMember; import nom.bdezonia.zorbage.type.real.float32.Float32Member; import nom.bdezonia.zorbage.type.real.float32.Float32VectorMember; import nom.bdezonia.zorbage.type.real.float64.Float64CartesianTensorProductMember; import nom.bdezonia.zorbage.type.real.float64.Float64MatrixMember; import nom.bdezonia.zorbage.type.real.float64.Float64Member; import nom.bdezonia.zorbage.type.real.float64.Float64VectorMember; import nom.bdezonia.zorbage.type.real.highprec.HighPrecisionCartesianTensorProductMember; import nom.bdezonia.zorbage.type.real.highprec.HighPrecisionMatrixMember; import nom.bdezonia.zorbage.type.real.highprec.HighPrecisionMember; import nom.bdezonia.zorbage.type.real.highprec.HighPrecisionVectorMember; import nom.bdezonia.zorbage.type.string.FixedStringMember; import nom.bdezonia.zorbage.type.string.StringMember; /** * @author Barry DeZonia */ public class DataBundle { public List<DimensionedDataSource<ArgbMember>> argbs = new ArrayList<>(); public List<DimensionedDataSource<BooleanMember>> bools = new ArrayList<>(); public List<DimensionedDataSource<ComplexFloat128Member>> cquads = new ArrayList<>(); public List<DimensionedDataSource<Float128Member>> quads = new ArrayList<>(); public List<DimensionedDataSource<ComplexFloat64Member>> cdbls = new ArrayList<>(); public List<DimensionedDataSource<ComplexFloat64VectorMember>> cdbl_vecs = new ArrayList<>(); public List<DimensionedDataSource<ComplexFloat64MatrixMember>> cdbl_mats = new ArrayList<>(); public List<DimensionedDataSource<ComplexFloat64CartesianTensorProductMember>> cdbl_tens = new ArrayList<>(); public List<DimensionedDataSource<ComplexFloat32Member>> cflts = new ArrayList<>(); public List<DimensionedDataSource<ComplexFloat32VectorMember>> cflt_vecs = new ArrayList<>(); public List<DimensionedDataSource<ComplexFloat32MatrixMember>> cflt_mats = new ArrayList<>(); public List<DimensionedDataSource<ComplexFloat32CartesianTensorProductMember>> cflt_tens = new ArrayList<>(); public List<DimensionedDataSource<CharMember>> chars = new ArrayList<>(); public List<DimensionedDataSource<ComplexFloat16Member>> chlfs = new ArrayList<>(); public List<DimensionedDataSource<ComplexFloat16VectorMember>> chlf_vecs = new ArrayList<>(); public List<DimensionedDataSource<ComplexFloat16MatrixMember>> chlf_mats = new ArrayList<>(); public List<DimensionedDataSource<ComplexFloat16CartesianTensorProductMember>> chlf_tens = new ArrayList<>(); public List<DimensionedDataSource<ComplexHighPrecisionMember>> chps = new ArrayList<>(); public List<DimensionedDataSource<ComplexHighPrecisionVectorMember>> chp_vecs = new ArrayList<>(); public List<DimensionedDataSource<ComplexHighPrecisionMatrixMember>> chp_mats = new ArrayList<>(); public List<DimensionedDataSource<ComplexHighPrecisionCartesianTensorProductMember>> chp_tens = new ArrayList<>(); public List<DimensionedDataSource<Float64Member>> dbls = new ArrayList<>(); public List<DimensionedDataSource<Float64VectorMember>> dbl_vecs = new ArrayList<>(); public List<DimensionedDataSource<Float64MatrixMember>> dbl_mats = new ArrayList<>(); public List<DimensionedDataSource<Float64CartesianTensorProductMember>> dbl_tens = new ArrayList<>(); public List<DimensionedDataSource<Float32Member>> flts = new ArrayList<>(); public List<DimensionedDataSource<Float32VectorMember>> flt_vecs = new ArrayList<>(); public List<DimensionedDataSource<Float32MatrixMember>> flt_mats = new ArrayList<>(); public List<DimensionedDataSource<Float32CartesianTensorProductMember>> flt_tens = new ArrayList<>(); public List<DimensionedDataSource<FixedStringMember>> fstrs = new ArrayList<>(); public List<DimensionedDataSource<Float16Member>> hlfs = new ArrayList<>(); public List<DimensionedDataSource<Float16VectorMember>> hlf_vecs = new ArrayList<>(); public List<DimensionedDataSource<Float16MatrixMember>> hlf_mats = new ArrayList<>(); public List<DimensionedDataSource<Float16CartesianTensorProductMember>> hlf_tens = new ArrayList<>(); public List<DimensionedDataSource<HighPrecisionMember>> hps = new ArrayList<>(); public List<DimensionedDataSource<HighPrecisionVectorMember>> hp_vecs = new ArrayList<>(); public List<DimensionedDataSource<HighPrecisionMatrixMember>> hp_mats = new ArrayList<>(); public List<DimensionedDataSource<HighPrecisionCartesianTensorProductMember>> hp_tens = new ArrayList<>(); public List<DimensionedDataSource<SignedInt1Member>> int1s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt2Member>> int2s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt3Member>> int3s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt4Member>> int4s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt5Member>> int5s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt6Member>> int6s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt7Member>> int7s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt8Member>> int8s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt9Member>> int9s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt10Member>> int10s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt11Member>> int11s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt12Member>> int12s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt13Member>> int13s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt14Member>> int14s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt15Member>> int15s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt16Member>> int16s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt32Member>> int32s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt64Member>> int64s = new ArrayList<>(); public List<DimensionedDataSource<SignedInt128Member>> int128s = new ArrayList<>(); public List<DimensionedDataSource<OctonionFloat64Member>> odbls = new ArrayList<>(); public List<DimensionedDataSource<OctonionFloat64RModuleMember>> odbl_rmods = new ArrayList<>(); public List<DimensionedDataSource<OctonionFloat64MatrixMember>> odbl_mats = new ArrayList<>(); public List<DimensionedDataSource<OctonionFloat64CartesianTensorProductMember>> odbl_tens = new ArrayList<>(); public List<DimensionedDataSource<OctonionFloat32Member>> oflts = new ArrayList<>(); public List<DimensionedDataSource<OctonionFloat32RModuleMember>> oflt_rmods = new ArrayList<>(); public List<DimensionedDataSource<OctonionFloat32MatrixMember>> oflt_mats = new ArrayList<>(); public List<DimensionedDataSource<OctonionFloat32CartesianTensorProductMember>> oflt_tens = new ArrayList<>(); public List<DimensionedDataSource<OctonionFloat16Member>> ohlfs = new ArrayList<>(); public List<DimensionedDataSource<OctonionFloat16RModuleMember>> ohlf_rmods = new ArrayList<>(); public List<DimensionedDataSource<OctonionFloat16MatrixMember>> ohlf_mats = new ArrayList<>(); public List<DimensionedDataSource<OctonionFloat16CartesianTensorProductMember>> ohlf_tens = new ArrayList<>(); public List<DimensionedDataSource<OctonionHighPrecisionMember>> ohps = new ArrayList<>(); public List<DimensionedDataSource<OctonionHighPrecisionRModuleMember>> ohp_rmods = new ArrayList<>(); public List<DimensionedDataSource<OctonionHighPrecisionMatrixMember>> ohp_mats = new ArrayList<>(); public List<DimensionedDataSource<OctonionHighPrecisionCartesianTensorProductMember>> ohp_tens = new ArrayList<>(); public List<DimensionedDataSource<Point>> points = new ArrayList<>(); public List<DimensionedDataSource<QuaternionFloat64Member>> qdbls = new ArrayList<>(); public List<DimensionedDataSource<QuaternionFloat64RModuleMember>> qdbl_rmods = new ArrayList<>(); public List<DimensionedDataSource<QuaternionFloat64MatrixMember>> qdbl_mats = new ArrayList<>(); public List<DimensionedDataSource<QuaternionFloat64CartesianTensorProductMember>> qdbl_tens = new ArrayList<>(); public List<DimensionedDataSource<QuaternionFloat32Member>> qflts = new ArrayList<>(); public List<DimensionedDataSource<QuaternionFloat32RModuleMember>> qflt_rmods = new ArrayList<>(); public List<DimensionedDataSource<QuaternionFloat32MatrixMember>> qflt_mats = new ArrayList<>(); public List<DimensionedDataSource<QuaternionFloat32CartesianTensorProductMember>> qflt_tens = new ArrayList<>(); public List<DimensionedDataSource<QuaternionFloat16Member>> qhlfs = new ArrayList<>(); public List<DimensionedDataSource<QuaternionFloat16RModuleMember>> qhlf_rmods = new ArrayList<>(); public List<DimensionedDataSource<QuaternionFloat16MatrixMember>> qhlf_mats = new ArrayList<>(); public List<DimensionedDataSource<QuaternionFloat16CartesianTensorProductMember>> qhlf_tens = new ArrayList<>(); public List<DimensionedDataSource<QuaternionHighPrecisionMember>> qhps = new ArrayList<>(); public List<DimensionedDataSource<QuaternionHighPrecisionRModuleMember>> qhp_rmods = new ArrayList<>(); public List<DimensionedDataSource<QuaternionHighPrecisionMatrixMember>> qhp_mats = new ArrayList<>(); public List<DimensionedDataSource<QuaternionHighPrecisionCartesianTensorProductMember>> qhp_tens = new ArrayList<>(); public List<DimensionedDataSource<RationalMember>> rationals = new ArrayList<>(); public List<DimensionedDataSource<RgbMember>> rgbs = new ArrayList<>(); public List<DimensionedDataSource<StringMember>> strs = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt1Member>> uint1s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt2Member>> uint2s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt3Member>> uint3s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt4Member>> uint4s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt5Member>> uint5s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt6Member>> uint6s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt7Member>> uint7s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt8Member>> uint8s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt9Member>> uint9s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt10Member>> uint10s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt11Member>> uint11s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt12Member>> uint12s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt13Member>> uint13s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt14Member>> uint14s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt15Member>> uint15s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt16Member>> uint16s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt32Member>> uint32s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt64Member>> uint64s = new ArrayList<>(); public List<DimensionedDataSource<UnsignedInt128Member>> uint128s = new ArrayList<>(); public List<DimensionedDataSource<UnboundedIntMember>> unbounds = new ArrayList<>(); public List<DimensionedDataSource<GaussianInt8Member>> gint8s = new ArrayList<>(); public List<DimensionedDataSource<GaussianInt16Member>> gint16s = new ArrayList<>(); public List<DimensionedDataSource<GaussianInt32Member>> gint32s = new ArrayList<>(); public List<DimensionedDataSource<GaussianInt64Member>> gint64s = new ArrayList<>(); public List<DimensionedDataSource<GaussianIntUnboundedMember>> gintus = new ArrayList<>(); public void mergeArgb(DimensionedDataSource<ArgbMember> ds) { if (ds != null) argbs.add(ds); } public void mergeBool(DimensionedDataSource<BooleanMember> ds) { if (ds != null) bools.add(ds); } public void mergeComplexFlt128(DimensionedDataSource<ComplexFloat128Member> ds) { if (ds != null) cquads.add(ds); } public void mergeComplexFlt64(DimensionedDataSource<ComplexFloat64Member> ds) { if (ds != null) cdbls.add(ds); } public void mergeComplexFlt64Vec(DimensionedDataSource<ComplexFloat64VectorMember> ds) { if (ds != null) cdbl_vecs.add(ds); } public void mergeComplexFlt64Mat(DimensionedDataSource<ComplexFloat64MatrixMember> ds) { if (ds != null) cdbl_mats.add(ds); } public void mergeComplexFlt64Tens(DimensionedDataSource<ComplexFloat64CartesianTensorProductMember> ds) { if (ds != null) cdbl_tens.add(ds); } public void mergeComplexFlt32(DimensionedDataSource<ComplexFloat32Member> ds) { if (ds != null) cflts.add(ds); } public void mergeComplexFlt32Vec(DimensionedDataSource<ComplexFloat32VectorMember> ds) { if (ds != null) cflt_vecs.add(ds); } public void mergeComplexFlt32Mat(DimensionedDataSource<ComplexFloat32MatrixMember> ds) { if (ds != null) cflt_mats.add(ds); } public void mergeComplexFlt32Tens(DimensionedDataSource<ComplexFloat32CartesianTensorProductMember> ds) { if (ds != null) cflt_tens.add(ds); } public void mergeChar(DimensionedDataSource<CharMember> ds) { if (ds != null) chars.add(ds); } public void mergeComplexFlt16(DimensionedDataSource<ComplexFloat16Member> ds) { if (ds != null) chlfs.add(ds); } public void mergeComplexFlt16Vec(DimensionedDataSource<ComplexFloat16VectorMember> ds) { if (ds != null) chlf_vecs.add(ds); } public void mergeComplexFlt16Mat(DimensionedDataSource<ComplexFloat16MatrixMember> ds) { if (ds != null) chlf_mats.add(ds); } public void mergeComplexFlt16Tens(DimensionedDataSource<ComplexFloat16CartesianTensorProductMember> ds) { if (ds != null) chlf_tens.add(ds); } public void mergeComplexHP(DimensionedDataSource<ComplexHighPrecisionMember> ds) { if (ds != null) chps.add(ds); } public void mergeComplexHPVec(DimensionedDataSource<ComplexHighPrecisionVectorMember> ds) { if (ds != null) chp_vecs.add(ds); } public void mergeComplexHPMat(DimensionedDataSource<ComplexHighPrecisionMatrixMember> ds) { if (ds != null) chp_mats.add(ds); } public void mergeComplexHPTens(DimensionedDataSource<ComplexHighPrecisionCartesianTensorProductMember> ds) { if (ds != null) chp_tens.add(ds); } public void mergeFlt128(DimensionedDataSource<Float128Member> ds) { if (ds != null) quads.add(ds); } public void mergeFlt64(DimensionedDataSource<Float64Member> ds) { if (ds != null) dbls.add(ds); } public void mergeFlt64Vec(DimensionedDataSource<Float64VectorMember> ds) { if (ds != null) dbl_vecs.add(ds); } public void mergeFlt64Mat(DimensionedDataSource<Float64MatrixMember> ds) { if (ds != null) dbl_mats.add(ds); } public void mergeFlt64Tens(DimensionedDataSource<Float64CartesianTensorProductMember> ds) { if (ds != null) dbl_tens.add(ds); } public void mergeFlt32(DimensionedDataSource<Float32Member> ds) { if (ds != null) flts.add(ds); } public void mergeFlt32Vec(DimensionedDataSource<Float32VectorMember> ds) { if (ds != null) flt_vecs.add(ds); } public void mergeFlt32Mat(DimensionedDataSource<Float32MatrixMember> ds) { if (ds != null) flt_mats.add(ds); } public void mergeFlt32Tens(DimensionedDataSource<Float32CartesianTensorProductMember> ds) { if (ds != null) flt_tens.add(ds); } public void mergeFixedString(DimensionedDataSource<FixedStringMember> ds) { if (ds != null) fstrs.add(ds); } public void mergeFlt16(DimensionedDataSource<Float16Member> ds) { if (ds != null) hlfs.add(ds); } public void mergeFlt16Vec(DimensionedDataSource<Float16VectorMember> ds) { if (ds != null) hlf_vecs.add(ds); } public void mergeFlt16Mat(DimensionedDataSource<Float16MatrixMember> ds) { if (ds != null) hlf_mats.add(ds); } public void mergeFlt16Tens(DimensionedDataSource<Float16CartesianTensorProductMember> ds) { if (ds != null) hlf_tens.add(ds); } public void mergeHP(DimensionedDataSource<HighPrecisionMember> ds) { if (ds != null) hps.add(ds); } public void mergeHPVec(DimensionedDataSource<HighPrecisionVectorMember> ds) { if (ds != null) hp_vecs.add(ds); } public void mergeHPMat(DimensionedDataSource<HighPrecisionMatrixMember> ds) { if (ds != null) hp_mats.add(ds); } public void mergeHPTens(DimensionedDataSource<HighPrecisionCartesianTensorProductMember> ds) { if (ds != null) hp_tens.add(ds); } public void mergeInt1(DimensionedDataSource<SignedInt1Member> ds) { if (ds != null) int1s.add(ds); } public void mergeInt2(DimensionedDataSource<SignedInt2Member> ds) { if (ds != null) int2s.add(ds); } public void mergeInt3(DimensionedDataSource<SignedInt3Member> ds) { if (ds != null) int3s.add(ds); } public void mergeInt4(DimensionedDataSource<SignedInt4Member> ds) { if (ds != null) int4s.add(ds); } public void mergeInt5(DimensionedDataSource<SignedInt5Member> ds) { if (ds != null) int5s.add(ds); } public void mergeInt6(DimensionedDataSource<SignedInt6Member> ds) { if (ds != null) int6s.add(ds); } public void mergeInt7(DimensionedDataSource<SignedInt7Member> ds) { if (ds != null) int7s.add(ds); } public void mergeInt8(DimensionedDataSource<SignedInt8Member> ds) { if (ds != null) int8s.add(ds); } public void mergeInt9(DimensionedDataSource<SignedInt9Member> ds) { if (ds != null) int9s.add(ds); } public void mergeInt10(DimensionedDataSource<SignedInt10Member> ds) { if (ds != null) int10s.add(ds); } public void mergeInt11(DimensionedDataSource<SignedInt11Member> ds) { if (ds != null) int11s.add(ds); } public void mergeInt12(DimensionedDataSource<SignedInt12Member> ds) { if (ds != null) int12s.add(ds); } public void mergeInt13(DimensionedDataSource<SignedInt13Member> ds) { if (ds != null) int13s.add(ds); } public void mergeInt14(DimensionedDataSource<SignedInt14Member> ds) { if (ds != null) int14s.add(ds); } public void mergeInt15(DimensionedDataSource<SignedInt15Member> ds) { if (ds != null) int15s.add(ds); } public void mergeInt16(DimensionedDataSource<SignedInt16Member> ds) { if (ds != null) int16s.add(ds); } public void mergeInt32(DimensionedDataSource<SignedInt32Member> ds) { if (ds != null) int32s.add(ds); } public void mergeInt64(DimensionedDataSource<SignedInt64Member> ds) { if (ds != null) int64s.add(ds); } public void mergeInt128(DimensionedDataSource<SignedInt128Member> ds) { if (ds != null) int128s.add(ds); } public void mergeOct64(DimensionedDataSource<OctonionFloat64Member> ds) { if (ds != null) odbls.add(ds); } public void mergeOct64RMod(DimensionedDataSource<OctonionFloat64RModuleMember> ds) { if (ds != null) odbl_rmods.add(ds); } public void mergeOct64Mat(DimensionedDataSource<OctonionFloat64MatrixMember> ds) { if (ds != null) odbl_mats.add(ds); } public void mergeOct64Tens(DimensionedDataSource<OctonionFloat64CartesianTensorProductMember> ds) { if (ds != null) odbl_tens.add(ds); } public void mergeOct32(DimensionedDataSource<OctonionFloat32Member> ds) { if (ds != null) oflts.add(ds); } public void mergeOct32RMod(DimensionedDataSource<OctonionFloat32RModuleMember> ds) { if (ds != null) oflt_rmods.add(ds); } public void mergeOct32Mat(DimensionedDataSource<OctonionFloat32MatrixMember> ds) { if (ds != null) oflt_mats.add(ds); } public void mergeOct32Tens(DimensionedDataSource<OctonionFloat32CartesianTensorProductMember> ds) { if (ds != null) oflt_tens.add(ds); } public void mergeOct16(DimensionedDataSource<OctonionFloat16Member> ds) { if (ds != null) ohlfs.add(ds); } public void mergeOct16RMod(DimensionedDataSource<OctonionFloat16RModuleMember> ds) { if (ds != null) ohlf_rmods.add(ds); } public void mergeOct16Mat(DimensionedDataSource<OctonionFloat16MatrixMember> ds) { if (ds != null) ohlf_mats.add(ds); } public void mergeOct16Tens(DimensionedDataSource<OctonionFloat16CartesianTensorProductMember> ds) { if (ds != null) ohlf_tens.add(ds); } public void mergeOctHP(DimensionedDataSource<OctonionHighPrecisionMember> ds) { if (ds != null) ohps.add(ds); } public void mergeOctHPRMod(DimensionedDataSource<OctonionHighPrecisionRModuleMember> ds) { if (ds != null) ohp_rmods.add(ds); } public void mergeOctHPMat(DimensionedDataSource<OctonionHighPrecisionMatrixMember> ds) { if (ds != null) ohp_mats.add(ds); } public void mergeOctHPTens(DimensionedDataSource<OctonionHighPrecisionCartesianTensorProductMember> ds) { if (ds != null) ohp_tens.add(ds); } public void mergePoint(DimensionedDataSource<Point> ds) { if (ds != null) points.add(ds); } public void mergeQuat64(DimensionedDataSource<QuaternionFloat64Member> ds) { if (ds != null) qdbls.add(ds); } public void mergeQuat64RMod(DimensionedDataSource<QuaternionFloat64RModuleMember> ds) { if (ds != null) qdbl_rmods.add(ds); } public void mergeQuat64Mat(DimensionedDataSource<QuaternionFloat64MatrixMember> ds) { if (ds != null) qdbl_mats.add(ds); } public void mergeQuat64Tens(DimensionedDataSource<QuaternionFloat64CartesianTensorProductMember> ds) { if (ds != null) qdbl_tens.add(ds); } public void mergeQuat32(DimensionedDataSource<QuaternionFloat32Member> ds) { if (ds != null) qflts.add(ds); } public void mergeQuat32RMod(DimensionedDataSource<QuaternionFloat32RModuleMember> ds) { if (ds != null) qflt_rmods.add(ds); } public void mergeQuat32Mat(DimensionedDataSource<QuaternionFloat32MatrixMember> ds) { if (ds != null) qflt_mats.add(ds); } public void mergeQuat32Tens(DimensionedDataSource<QuaternionFloat32CartesianTensorProductMember> ds) { if (ds != null) qflt_tens.add(ds); } public void mergeQuat16(DimensionedDataSource<QuaternionFloat16Member> ds) { if (ds != null) qhlfs.add(ds); } public void mergeQuat16RMod(DimensionedDataSource<QuaternionFloat16RModuleMember> ds) { if (ds != null) qhlf_rmods.add(ds); } public void mergeQuat16Mat(DimensionedDataSource<QuaternionFloat16MatrixMember> ds) { if (ds != null) qhlf_mats.add(ds); } public void mergeQuat16Tens(DimensionedDataSource<QuaternionFloat16CartesianTensorProductMember> ds) { if (ds != null) qhlf_tens.add(ds); } public void mergeQuatHP(DimensionedDataSource<QuaternionHighPrecisionMember> ds) { if (ds != null) qhps.add(ds); } public void mergeQuatHPRMod(DimensionedDataSource<QuaternionHighPrecisionRModuleMember> ds) { if (ds != null) qhp_rmods.add(ds); } public void mergeQuatHPMat(DimensionedDataSource<QuaternionHighPrecisionMatrixMember> ds) { if (ds != null) qhp_mats.add(ds); } public void mergeQuatHPTens(DimensionedDataSource<QuaternionHighPrecisionCartesianTensorProductMember> ds) { if (ds != null) qhp_tens.add(ds); } public void mergeRational(DimensionedDataSource<RationalMember> ds) { if (ds != null) rationals.add(ds); } public void mergeRgb(DimensionedDataSource<RgbMember> ds) { if (ds != null) rgbs.add(ds); } public void mergeString(DimensionedDataSource<StringMember> ds) { if (ds != null) strs.add(ds); } public void mergeUInt1(DimensionedDataSource<UnsignedInt1Member> ds) { if (ds != null) uint1s.add(ds); } public void mergeUInt2(DimensionedDataSource<UnsignedInt2Member> ds) { if (ds != null) uint2s.add(ds); } public void mergeUInt3(DimensionedDataSource<UnsignedInt3Member> ds) { if (ds != null) uint3s.add(ds); } public void mergeUInt4(DimensionedDataSource<UnsignedInt4Member> ds) { if (ds != null) uint4s.add(ds); } public void mergeUInt5(DimensionedDataSource<UnsignedInt5Member> ds) { if (ds != null) uint5s.add(ds); } public void mergeUInt6(DimensionedDataSource<UnsignedInt6Member> ds) { if (ds != null) uint6s.add(ds); } public void mergeUInt7(DimensionedDataSource<UnsignedInt7Member> ds) { if (ds != null) uint7s.add(ds); } public void mergeUInt8(DimensionedDataSource<UnsignedInt8Member> ds) { if (ds != null) uint8s.add(ds); } public void mergeUInt9(DimensionedDataSource<UnsignedInt9Member> ds) { if (ds != null) uint9s.add(ds); } public void mergeUInt10(DimensionedDataSource<UnsignedInt10Member> ds) { if (ds != null) uint10s.add(ds); } public void mergeUInt11(DimensionedDataSource<UnsignedInt11Member> ds) { if (ds != null) uint11s.add(ds); } public void mergeUInt12(DimensionedDataSource<UnsignedInt12Member> ds) { if (ds != null) uint12s.add(ds); } public void mergeUInt13(DimensionedDataSource<UnsignedInt13Member> ds) { if (ds != null) uint13s.add(ds); } public void mergeUInt14(DimensionedDataSource<UnsignedInt14Member> ds) { if (ds != null) uint14s.add(ds); } public void mergeUInt15(DimensionedDataSource<UnsignedInt15Member> ds) { if (ds != null) uint15s.add(ds); } public void mergeUInt16(DimensionedDataSource<UnsignedInt16Member> ds) { if (ds != null) uint16s.add(ds); } public void mergeUInt32(DimensionedDataSource<UnsignedInt32Member> ds) { if (ds != null) uint32s.add(ds); } public void mergeUInt64(DimensionedDataSource<UnsignedInt64Member> ds) { if (ds != null) uint64s.add(ds); } public void mergeUInt128(DimensionedDataSource<UnsignedInt128Member> ds) { if (ds != null) uint128s.add(ds); } public void mergeBigInt(DimensionedDataSource<UnboundedIntMember> ds) { if (ds != null) unbounds.add(ds); } public void mergeGaussianInt8(DimensionedDataSource<GaussianInt8Member> ds) { if (ds != null) gint8s.add(ds); } public void mergeGaussianInt16(DimensionedDataSource<GaussianInt16Member> ds) { if (ds != null) gint16s.add(ds); } public void mergeGaussianInt32(DimensionedDataSource<GaussianInt32Member> ds) { if (ds != null) gint32s.add(ds); } public void mergeGaussianInt64(DimensionedDataSource<GaussianInt64Member> ds) { if (ds != null) gint64s.add(ds); } public void mergeGaussianIntUnbounded(DimensionedDataSource<GaussianIntUnboundedMember> ds) { if (ds != null) gintus.add(ds); } public void mergeAll(DataBundle other) { if (this == other) return; argbs.addAll(other.argbs); bools.addAll(other.bools); cquads.addAll(other.cquads); cdbls.addAll(other.cdbls); cdbl_vecs.addAll(other.cdbl_vecs); cdbl_mats.addAll(other.cdbl_mats); cdbl_tens.addAll(other.cdbl_tens); cflts.addAll(other.cflts); cflt_vecs.addAll(other.cflt_vecs); cflt_mats.addAll(other.cflt_mats); cflt_tens.addAll(other.cflt_tens); chars.addAll(other.chars); chlfs.addAll(other.chlfs); chlf_vecs.addAll(other.chlf_vecs); chlf_mats.addAll(other.chlf_mats); chlf_tens.addAll(other.chlf_tens); chps.addAll(other.chps); chp_vecs.addAll(other.chp_vecs); chp_mats.addAll(other.chp_mats); chp_tens.addAll(other.chp_tens); dbls.addAll(other.dbls); dbl_vecs.addAll(other.dbl_vecs); dbl_mats.addAll(other.dbl_mats); dbl_tens.addAll(other.dbl_tens); flts.addAll(other.flts); flt_vecs.addAll(other.flt_vecs); flt_mats.addAll(other.flt_mats); flt_tens.addAll(other.flt_tens); fstrs.addAll(other.fstrs); gint8s.addAll(other.gint8s); gint16s.addAll(other.gint16s); gint32s.addAll(other.gint32s); gint64s.addAll(other.gint64s); gintus.addAll(other.gintus); hlfs.addAll(other.hlfs); hlf_vecs.addAll(other.hlf_vecs); hlf_mats.addAll(other.hlf_mats); hlf_tens.addAll(other.hlf_tens); hps.addAll(other.hps); hp_vecs.addAll(other.hp_vecs); hp_mats.addAll(other.hp_mats); hp_tens.addAll(other.hp_tens); int1s.addAll(other.int1s); int2s.addAll(other.int2s); int3s.addAll(other.int3s); int4s.addAll(other.int4s); int5s.addAll(other.int5s); int6s.addAll(other.int6s); int7s.addAll(other.int7s); int8s.addAll(other.int8s); int9s.addAll(other.int9s); int10s.addAll(other.int10s); int11s.addAll(other.int11s); int12s.addAll(other.int12s); int13s.addAll(other.int13s); int14s.addAll(other.int14s); int15s.addAll(other.int15s); int16s.addAll(other.int16s); int32s.addAll(other.int32s); int64s.addAll(other.int64s); int128s.addAll(other.int128s); odbls.addAll(other.odbls); odbl_rmods.addAll(other.odbl_rmods); odbl_mats.addAll(other.odbl_mats); odbl_tens.addAll(other.odbl_tens); oflts.addAll(other.oflts); oflt_rmods.addAll(other.oflt_rmods); oflt_mats.addAll(other.oflt_mats); oflt_tens.addAll(other.oflt_tens); ohlfs.addAll(other.ohlfs); ohlf_rmods.addAll(other.ohlf_rmods); ohlf_mats.addAll(other.ohlf_mats); ohlf_tens.addAll(other.ohlf_tens); ohps.addAll(other.ohps); ohp_rmods.addAll(other.ohp_rmods); ohp_mats.addAll(other.ohp_mats); ohp_tens.addAll(other.ohp_tens); points.addAll(other.points); quads.addAll(other.quads); qdbls.addAll(other.qdbls); qdbl_rmods.addAll(other.qdbl_rmods); qdbl_mats.addAll(other.qdbl_mats); qdbl_tens.addAll(other.qdbl_tens); qflts.addAll(other.qflts); qflt_rmods.addAll(other.qflt_rmods); qflt_mats.addAll(other.qflt_mats); qflt_tens.addAll(other.qflt_tens); qhlfs.addAll(other.qhlfs); qhlf_rmods.addAll(other.qhlf_rmods); qhlf_mats.addAll(other.qhlf_mats); qhlf_tens.addAll(other.qhlf_tens); qhps.addAll(other.qhps); qhp_rmods.addAll(other.qhp_rmods); qhp_mats.addAll(other.qhp_mats); qhp_tens.addAll(other.qhp_tens); rationals.addAll(other.rationals); rgbs.addAll(other.rgbs); strs.addAll(other.strs); uint1s.addAll(other.uint1s); uint2s.addAll(other.uint2s); uint3s.addAll(other.uint3s); uint4s.addAll(other.uint4s); uint5s.addAll(other.uint5s); uint6s.addAll(other.uint6s); uint7s.addAll(other.uint7s); uint8s.addAll(other.uint8s); uint9s.addAll(other.uint9s); uint10s.addAll(other.uint10s); uint11s.addAll(other.uint11s); uint12s.addAll(other.uint12s); uint13s.addAll(other.uint13s); uint14s.addAll(other.uint14s); uint15s.addAll(other.uint15s); uint16s.addAll(other.uint16s); uint32s.addAll(other.uint32s); uint64s.addAll(other.uint64s); uint128s.addAll(other.uint128s); unbounds.addAll(other.unbounds); } @SuppressWarnings("unchecked") public <T extends Algebra<T,U>, U> List<Tuple2<T,DimensionedDataSource<U>>> bundle() { ArrayList<Tuple2<T,DimensionedDataSource<U>>> fullList = new ArrayList<>(); for (DimensionedDataSource<?> ds : this.argbs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.ARGB, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.bools) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.BOOL, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.cdbls) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CDBL, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.cdbl_vecs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CDBL_VEC, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.cdbl_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CDBL_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.cdbl_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CDBL_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.cflts) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CFLT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.cflt_vecs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CFLT_VEC, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.cflt_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CFLT_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.cflt_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CFLT_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.chlfs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CHLF, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.chlf_vecs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CHLF_VEC, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.chlf_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CHLF_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.chlf_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CHLF_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.chps) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CHP, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.chp_vecs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CHP_VEC, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.chp_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CHP_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.chp_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CHP_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.dbls) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.DBL, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.dbl_vecs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.DBL_VEC, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.dbl_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.DBL_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.dbl_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.DBL_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.flts) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.FLT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.flt_vecs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.FLT_VEC, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.flt_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.FLT_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.flt_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.FLT_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.fstrs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.FSTRING, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.strs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.STRING, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.chars) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.CHAR, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.gint8s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.GAUSS8, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.gint16s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.GAUSS16, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.gint32s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.GAUSS32, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.gint64s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.GAUSS64, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.gintus) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.GAUSSU, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.hlfs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.HLF, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.hlf_vecs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.HLF_VEC, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.hlf_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.HLF_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.hlf_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.HLF_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.hps) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.HP, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.hp_vecs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.HP_VEC, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.hp_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.HP_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.hp_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.HP_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int1s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT1, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int2s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT2, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int3s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT3, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int4s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT4, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int5s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT5, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int6s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT6, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int7s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT7, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int8s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT8, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int9s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT9, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int10s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT10, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int11s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT11, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int12s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT12, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int13s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT13, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int14s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT14, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int15s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT15, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int16s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT16, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int32s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT32, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int64s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT64, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.int128s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.INT128, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.odbls) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.ODBL, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.odbl_rmods) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.ODBL_RMOD, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.odbl_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.ODBL_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.odbl_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.ODBL_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.oflts) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.OFLT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.oflt_rmods) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.OFLT_RMOD, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.oflt_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.OFLT_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.oflt_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.OFLT_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.ohlfs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.OHLF, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.ohlf_rmods) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.OHLF_RMOD, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.ohlf_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.OHLF_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.ohlf_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.OHLF_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.ohps) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.OHP, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.ohp_rmods) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.OHP_RMOD, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.ohp_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.OHP_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.ohp_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.OHP_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.points) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.POINT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qdbls) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QDBL, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qdbl_rmods) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QDBL_RMOD, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qdbl_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QDBL_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qdbl_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QDBL_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qflts) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QFLT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qflt_rmods) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QFLT_RMOD, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qflt_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QFLT_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qflt_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QFLT_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qhlfs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QHLF, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qhlf_rmods) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QHLF_RMOD, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qhlf_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QHLF_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qhlf_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QHLF_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qhps) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QHP, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qhp_rmods) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QHP_RMOD, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qhp_mats) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QHP_MAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.qhp_tens) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.QHP_TEN, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.rationals) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.RAT, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.rgbs) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.RGB, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint1s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT1, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint2s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT2, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint3s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT3, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint4s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT4, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint5s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT5, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint6s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT6, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint7s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT7, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint8s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT8, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint9s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT9, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint10s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT10, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint11s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT11, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint12s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT12, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint13s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT13, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint14s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT14, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint15s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT15, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint16s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT16, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint32s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT32, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint64s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT64, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.uint128s) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT128, (DimensionedDataSource<U>)ds); fullList.add(tuple); } for (DimensionedDataSource<?> ds : this.unbounds) { Tuple2<T, DimensionedDataSource<U>> tuple = new Tuple2<T, DimensionedDataSource<U>>((T)G.UNBOUND, (DimensionedDataSource<U>)ds); fullList.add(tuple); } return fullList; } }
package nuclibook.server; import com.j256.ormlite.jdbc.JdbcConnectionSource; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; import nuclibook.constants.C; import nuclibook.models.*; import java.sql.SQLException; public class SqlServerConnection { /* singleton pattern */ private SqlServerConnection() { } private static ConnectionSource connection = null; public static ConnectionSource acquireConnection() { return acquireConnection(C.MYSQL_URI, C.MYSQL_USERNAME, C.MYSQL_PASSWORD); } public static ConnectionSource acquireConnection(String uri, String username, String password) { if (connection == null) { try { connection = new JdbcConnectionSource(uri); ((JdbcConnectionSource) connection).setUsername(username); ((JdbcConnectionSource) connection).setPassword(password); initDB(connection); } catch (Exception e) { // TODO deal with exception e.printStackTrace(); } } return connection; } public static void initDB(ConnectionSource connection) { try { TableUtils.createTableIfNotExists(connection, ActionLog.class); TableUtils.createTableIfNotExists(connection, Booking.class); TableUtils.createTableIfNotExists(connection, BookingPatternSection.class); TableUtils.createTableIfNotExists(connection, BookingSection.class); TableUtils.createTableIfNotExists(connection, BookingStaff.class); TableUtils.createTableIfNotExists(connection, Camera.class); TableUtils.createTableIfNotExists(connection, CameraType.class); TableUtils.createTableIfNotExists(connection, Tracer.class); TableUtils.createTableIfNotExists(connection, Patient.class); TableUtils.createTableIfNotExists(connection, PatientQuestion.class); TableUtils.createTableIfNotExists(connection, Permission.class); TableUtils.createTableIfNotExists(connection, Staff.class); TableUtils.createTableIfNotExists(connection, StaffAbsence.class); TableUtils.createTableIfNotExists(connection, StaffAvailability.class); TableUtils.createTableIfNotExists(connection, StaffRole.class); TableUtils.createTableIfNotExists(connection, StaffRolePermission.class); TableUtils.createTableIfNotExists(connection, Therapy.class); TableUtils.createTableIfNotExists(connection, TherapyCameraType.class); } catch (SQLException e) { // TODO deal with exception e.printStackTrace(); } } }
package org.ajabshahar.platform.daos; import io.dropwizard.hibernate.AbstractDAO; import org.ajabshahar.platform.models.Song; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; public class SongDAO extends AbstractDAO<Song> { private final static Logger logger = LoggerFactory.getLogger(SongDAO.class); private final SessionFactory sessionFactory; public SongDAO(SessionFactory sessionFactory) { super(sessionFactory); this.sessionFactory = sessionFactory; } public Song findById(Long id) { return (Song) sessionFactory.openSession().get(Song.class, id); } public Song saveSong(Song song) { currentSession().update(song.getTitle()); currentSession().save(song); return song; } public List<Song> findAll() { Session currentSession = sessionFactory.getCurrentSession(); Criteria findSongs = currentSession.createCriteria(Song.class); findSongs.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return findSongs.list(); } public Song invokeAllSetters(Song originalSongData, Song updatableSongData) { originalSongData.setTitle(updatableSongData.getTitle()); originalSongData.setSongTitle(updatableSongData.getSongTitle()); originalSongData.setAbout(updatableSongData.getAbout()); originalSongData.setNotes(updatableSongData.getNotes()); originalSongData.setDownload_url(updatableSongData.getDownload_url()); originalSongData.setShowOnLandingPage(updatableSongData.getShowOnLandingPage()); originalSongData.setDuration(updatableSongData.getDuration()); originalSongData.setYoutubeVideoId(updatableSongData.getYoutubeVideoId()); originalSongData.setThumbnail_url(updatableSongData.getThumbnail_url()); originalSongData.setIsAuthoringComplete(updatableSongData.getIsAuthoringComplete()); originalSongData.setSingers(updatableSongData.getSingers()); originalSongData.setPoets(updatableSongData.getPoets()); originalSongData.setSongCategory(updatableSongData.getSongCategory()); originalSongData.setMediaCategory(updatableSongData.getMediaCategory()); return originalSongData; } public int getCountOfSongsThatStartWith(String letter) { return list(namedQuery("org.ajabshahar.platform.models.Song.findAllFilteredBy").setParameter("letter", letter + "%")).size(); } public List<Song> findBy(int songId, int singerId, int poetId, int startFrom, String filteredLetter) { Session currentSession = sessionFactory.getCurrentSession(); Criteria findSongs = currentSession.createCriteria(Song.class); if (songId != 0) { findSongs.add(Restrictions.eq("id", Long.valueOf(songId))); } if (singerId != 0) { findSongs.createAlias("singers", "singersAlias"); findSongs.add(Restrictions.eq("singersAlias.id", Long.valueOf(singerId))); } if (poetId != 0) { findSongs.createAlias("poets", "poetsAlias"); findSongs.add(Restrictions.eq("poetsAlias.id", Long.valueOf(poetId))); } if (startFrom != 0) { findSongs.setFirstResult(startFrom); } if (filteredLetter != null) { findSongs.createAlias("songTitle", "songTitleAlias"); findSongs.add(Restrictions.like("songTitleAlias.englishTranslation", filteredLetter, MatchMode.START)); } findSongs.add(Restrictions.eq("isAuthoringComplete",true)); findSongs.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return findSongs.list(); } public Song updateSong(Song updatableSong) { Long id = updatableSong.getId(); Song originalSongData = (Song) sessionFactory.openStatelessSession().get(Song.class, id); if (updatableSong.getSongTitle().getId() == 0) { TitleDAO titleDAO = new TitleDAO(sessionFactory); titleDAO.create(updatableSong.getSongTitle()); } if (updatableSong.getTitle().getId() == 0) { TitleDAO titleDAO = new TitleDAO(sessionFactory); titleDAO.create(updatableSong.getTitle()); } originalSongData = invokeAllSetters(originalSongData, updatableSong); sessionFactory.getCurrentSession().update(originalSongData.getTitle()); sessionFactory.getCurrentSession().update(originalSongData.getSongTitle()); sessionFactory.getCurrentSession().update(originalSongData); return originalSongData; } public List<Song> findSongWithVersions(int songId) { Session currentSession = sessionFactory.getCurrentSession(); Criteria findSongs = currentSession.createCriteria(Song.class); Song song = findById(Long.valueOf(songId)); if (song != null) { findSongs.createAlias("title", "titleAlias"); findSongs.add(Restrictions.eq("titleAlias.id", song.getTitle().getId())); findSongs.add(Restrictions.eq("isAuthoringComplete", true)); } else { return new ArrayList<>(); } findSongs.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return findSongs.list(); } }
package cs201.structures.bank; import java.util.HashMap; import java.util.List; import cs201.agents.PersonAgent.Intention; import cs201.roles.Role; import cs201.roles.bankRoles.BankGuardRole; import cs201.roles.bankRoles.BankTellerRole; import cs201.structures.Structure; public class Bank extends Structure { // Member Variables List<BankTellerRole> bankTellers; static BankGuardRole bankGuard; static boolean isOpen; double bankBalance; public enum AccountTypes { BUSINESS, PERSONAL } HashMap personalAccounts = new HashMap(); HashMap businessAccounts = new HashMap(); // Constructors public Bank(int x, int y, int width, int height, int id) { super(x, y, width, height, id); } // Methods // Returns a list of this Bank's tellers public List<BankTellerRole> getTellers() { return bankTellers; } // Returns the bank's guard public static BankGuardRole getGuard() { return bankGuard; } // Returns SimCity201's personal accounts public HashMap getPersonalAccounts() { return personalAccounts; } // Returns SimCity201's business accounts public HashMap getBusinessAccounts() { return businessAccounts; } // Returns the total money held inside of the Bank (Useful for granting loans) public double getBankBalance() { /*for(int actNum : personalAccounts.keySet()) { bankBalance += personalAccounts.get(actNum); } for(int actNum : businessAccounts.keySet()) { bankBalance += businessAccounts.get(actNum); }*/ return bankBalance; } // Sets whether this Bank is open or closed public void setOpen(boolean open) { isOpen = open; } // Returns whether or not this Bank is open public static boolean getOpen() { return isOpen; } @Override public Role getRole(Intention role) { // TODO Auto-generated method stub return null; } }
package database; import java.io.InputStream; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.sql.rowset.serial.SerialBlob; import server.ClientsSessions; import server.ConfigurationProperties; import server.DataEncryptor; import server.PasswordHasher; import server.RSAKeys; import server.SecurityValidator; import dto.ActionDto; import dto.CandidateDto; import dto.ElectionDto; import dto.ElectionProgressDto; import dto.InputValidation; import dto.UserDto; import dto.Validator; import dto.VoteDto; import enumeration.ElectionType; import enumeration.Status; import enumeration.ElectionStatus; import enumeration.UserRole; import enumeration.UserStatus; public class DatabaseConnector { private static String dbHost; private static String dbPort; private static String dbUser; private static String dbPassword; private static String dbName; private Connection con; private static String newLine = System.getProperty("line.separator"); public DatabaseConnector() { Connection con = null; dbHost = ConfigurationProperties.dbHost(); dbPort = ConfigurationProperties.dbPort(); dbName = ConfigurationProperties.dbSchema(); dbUser = ConfigurationProperties.dbUser(); dbPassword = ConfigurationProperties.dbPassword(); try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName; con = DriverManager.getConnection(url, dbUser, dbPassword); this.con = con; } catch (Exception e) { System.out.println("Db connection failed"); e.printStackTrace(); } } public UserDto selectUserById(int userId) { UserDto u = new UserDto(); PreparedStatement st = null; String query = "SELECT * FROM users WHERE user_id = ?"; try { st = con.prepareStatement(query); st.setInt(1, userId); ResultSet res = st.executeQuery(); if (res.next()) { u.setUserId(res.getInt(1)); u.setFirstName(res.getString(2)); u.setLastName(res.getString(3)); u.setEmail(res.getString(4)); u.setPassword(res.getString(5)); u.setSalt(res.getString(6)); u.setTempPassword(res.getString(7)); u.setTempSalt(res.getString(8)); u.setActivationCode(res.getString(9)); u.setPublicKey(res.getString(10)); u.setAdministratorFlag(res.getInt(11)); u.setStatus(res.getInt(12)); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return u; } public Validator checkIfUsernamePasswordMatch(String email, String plainPass) { // 1. validate input Validator result = validateEmailAndPlainInput(email, plainPass); if (!result.isVerified()) { return result; } // 2. validate email result = checkUserEmail(email); if (!result.isVerified()) { return result; } // get this user limited info from the database UserDto userDto = selectUserByEmailLimited(email); String dbHash = userDto.getPassword(); String dbSalt = userDto.getSalt(); int statusId = userDto.getStatus(); int id = userDto.getUserId(); String plainHash = PasswordHasher.sha512(plainPass, dbSalt); // 3. if entered password is correct, return true with welcome message if (plainHash.equals(dbHash)) { result.setObject(userDto); result.setVerified(true); result.setStatus("Welcome to Certus"); return result; } else { result.setVerified(false); result.setStatus("Error, the system could not resolve the provided combination of username and password."); return result; } } public Validator validateEmailAndPlainInput(String email, String plainPass) { InputValidation iv = new InputValidation(); Validator vResult = new Validator(); Validator vEmail, vPlain; Boolean verified = true; String status = ""; // 1. email vEmail = iv.validateEmail(email, "Email"); verified &= vEmail.isVerified(); status += vEmail.getStatus(); // 2. plain vPlain = iv.validateString(plainPass, "Password"); verified &= vPlain.isVerified(); status += vPlain.getStatus(); vResult.setVerified(verified); vResult.setStatus(status); return vResult; } private Validator checkUserEmail(String emailToSelect) { Validator v = new Validator(); v.setVerified(false); v.setStatus("Error, the system could not resolve the provided combination of username and password."); PreparedStatement st = null; String query = "SELECT user_id FROM users WHERE email = ?"; try { st = con.prepareStatement(query); st.setString(1, emailToSelect); ResultSet res = st.executeQuery(); if (res.next()) { v.setVerified(true); v.setStatus(""); return v; } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return v; } public UserDto selectUserByEmailLimited(String emailToSelect) { UserDto userDto = new UserDto(); PreparedStatement st = null; String query = "SELECT user_id, first_name, last_name, password, salt, status, admin FROM users WHERE email = ?"; try { st = this.con.prepareStatement(query); st.setString(1, emailToSelect); ResultSet res = st.executeQuery(); if (res.next()) { int user_id = res.getInt(1); String first_name = res.getString(2); String last_name = res.getString(3); String password = res.getString(4); String salt = res.getString(5); int statusId = res.getInt(6); int admin = res.getInt(7); userDto.setUserId(user_id); userDto.setFirstName(first_name); userDto.setLastName(last_name); userDto.setPassword(password); userDto.setSalt(salt); userDto.setStatus(statusId); userDto.setAdministratorFlag(admin); } else { } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return userDto; } // Election /** * @param id * (int) - Election identification number (primary key) * @return Validator : ElectionDto - Details of a particular election * @author Hirosh Wickramasuriya */ public Validator selectElection(int id) { Validator validator = new Validator(); ElectionDto electionDto = new ElectionDto(); PreparedStatement st = null; String query = "SELECT election_id, election_name, e.description, start_datetime, close_datetime, " + " status, s.code, s.description, owner_id, candidates_string, type, allowed_users_emails" + " FROM election e " + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " + " WHERE election_id = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, id); ResultSet res = st.executeQuery(); if (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); String electionDescription = res.getString(3); String startDatetime = res.getString(4); String closeDatetime = res.getString(5); int statusId = res.getInt(6); String statusCode = res.getString(7); String statusDescription = res.getString(8); int ownerId = res.getInt(9); String candidatesListString = res.getString(10); int electionType = res.getInt(11); String allowedUserEmails = res.getString(12); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setElectionDescription(electionDescription); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); electionDto.setCandidatesListString(candidatesListString); electionDto.setElectionType(electionType); electionDto.setRegisteredEmailList(allowedUserEmails); Validator vCandidates = selectCandidatesOfElection(electionId); electionDto.setCandidateList( (ArrayList<CandidateDto>) vCandidates.getObject()); validator.setVerified(true); validator.setObject(electionDto); validator.setStatus("Select successful"); } else { validator.setStatus("Election not found"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setVerified(false); validator.setStatus("Select failed"); } return validator; } public Validator selectElectionFullDetail(int id) { Validator validator = new Validator(); ElectionDto electionDto = new ElectionDto(); PreparedStatement st = null; String query = "SELECT e.election_id, election_name, e.description, start_datetime, close_datetime, " + " e.status, s.code, s.description, owner_id, candidates_string, type" + " FROM election e " + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " + " WHERE e.election_id = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, id); ResultSet res = st.executeQuery(); if (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); String electionDescription = res.getString(3); String startDatetime = res.getString(4); String closeDatetime = res.getString(5); int statusId = res.getInt(6); String statusCode = res.getString(7); String statusDescription = res.getString(8); int ownerId = res.getInt(9); String candidatesListString = res.getString(10); int electionType = res.getInt(11); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setElectionDescription(electionDescription); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); electionDto.setCandidatesListString(candidatesListString); electionDto.setElectionType(electionType); electionDto.setCurrentEmailList(selectParticipatingVotersOfElection(electionId)); electionDto.setCandidateList((ArrayList<CandidateDto>) selectCandidatesOfElection( electionId , Status.ENABLED).getObject()); validator.setVerified(true); validator.setObject(electionDto); validator.setStatus("Select successful"); } else { validator.setStatus("Election not found"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setVerified(false); validator.setStatus("Select failed"); } return validator; } /** * @param status * (ElectionStatus) - specific status to be searched * @return Validator : ArrayList<ElectionDto> - List of elections that * matches a specific status * @author Hirosh Wickramasuriya */ public Validator selectElections(ElectionStatus electionStatus) { Validator validator = new Validator(); ArrayList<ElectionDto> elections = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT election_id, election_name, e.description, start_datetime, close_datetime," + " status, s.code, s.description, owner_id, candidates_string " + " FROM election e" + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " + " WHERE status = ?" + " ORDER BY election_id"; try { st = this.con.prepareStatement(query); st.setInt(1, electionStatus.getCode()); ResultSet res = st.executeQuery(); while (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); String electionDescription = res.getString(3); String startDatetime = res.getString(4); String closeDatetime = res.getString(5); int statusId = res.getInt(6); String statusCode = res.getString(7); String statusDescription = res.getString(8); int ownerId = res.getInt(9); String candidatesListString = res.getString(10); ElectionDto electionDto = new ElectionDto(); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setElectionDescription(electionDescription); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); electionDto.setCandidatesListString(candidatesListString); elections.add(electionDto); } validator.setVerified(true); validator.setObject(elections); validator.setStatus("Successfully selected"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setStatus("Select Failed."); } return validator; } /** * @param status * (ElectionStatus) - specific status to be searched * @return Validator : ArrayList<ElectionDto> - List of elections that * does not match to the status * @author Hirosh Wickramasuriya */ public Validator selectElectionsNotInStatus(ElectionStatus electionStatus) { Validator validator = new Validator(); ArrayList<ElectionDto> elections = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT election_id, election_name, e.description, start_datetime, close_datetime," + " status, s.code, s.description, owner_id, candidates_string " + " FROM election e" + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " + " WHERE status <> ?" + " ORDER BY election_id"; try { st = this.con.prepareStatement(query); st.setInt(1, electionStatus.getCode()); ResultSet res = st.executeQuery(); while (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); String electionDescription = res.getString(3); String startDatetime = res.getString(4); String closeDatetime = res.getString(5); int statusId = res.getInt(6); String statusCode = res.getString(7); String statusDescription = res.getString(8); int ownerId = res.getInt(9); String candidatesListString = res.getString(10); ElectionDto electionDto = new ElectionDto(); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setElectionDescription(electionDescription); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); electionDto.setCandidatesListString(candidatesListString); elections.add(electionDto); } validator.setVerified(true); validator.setObject(elections); validator.setStatus("Successfully selected"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setStatus("Select Failed."); } return validator; } /** * @param electionOwnerId * (int) - user_id of the user who owns this election * @param status * (ElectionStatus) - specific status to be searched * @return Validator : ArrayList<ElectionDto> - List of elections owned by * the specific user, that matches a specific status * @author Hirosh Wickramasuriya */ public Validator selectElectionsOwnedByUser(int electionOwnerId, ElectionStatus electionStatus) { Validator validator = new Validator(); ArrayList<ElectionDto> elections = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT election_id, election_name, e.description, start_datetime, close_datetime, " + " status, s.code, s.description, owner_id, candidates_string, type " + " FROM election e" + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " + " WHERE owner_id = ?" + " AND status = ?" + " ORDER BY election_id DESC"; try { st = this.con.prepareStatement(query); st.setInt(1, electionOwnerId); st.setInt(2, electionStatus.getCode()); ResultSet res = st.executeQuery(); while (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); String electionDescription = res.getString(3); String startDatetime = res.getString(4); String closeDatetime = res.getString(5); int statusId = res.getInt(6); String statusCode = res.getString(7); String statusDescription = res.getString(8); int ownerId = res.getInt(9); String candidatesListString = res.getString(10); int electionType = res.getInt(11); ElectionDto electionDto = new ElectionDto(); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setElectionDescription(electionDescription); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); electionDto.setCandidatesListString(candidatesListString); electionDto.setElectionType(electionType); elections.add(electionDto); } validator.setVerified(true); validator.setObject(elections); validator.setStatus("Successfully selected"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setStatus("Select failed"); } return validator; } /** * @return Validator : ArrayList<ElectionDto> - List of all the elections * (regardless of status) * @author Hirosh Wickramasuriya */ public Validator selectElections() { Validator validator = new Validator(); ArrayList<ElectionDto> elections = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT election_id, election_name, e.description, start_datetime, close_datetime," + " status, s.code, s.description, owner_id, candidates_string " + " FROM election e" + " INNER JOIN status_election s " + " ON (e.status = s.status_id)" + " ORDER BY election_id"; try { st = this.con.prepareStatement(query); ResultSet res = st.executeQuery(); while (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); String electionDescription = res.getString(3); String startDatetime = res.getString(4); String closeDatetime = res.getString(5); int statusId = res.getInt(6); String statusCode = res.getString(7); String statusDescription = res.getString(8); int ownerId = res.getInt(9); String candidatesListString = res.getString(10); ElectionDto electionDto = new ElectionDto(); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setElectionDescription(electionDescription); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); electionDto.setCandidatesListString(candidatesListString); elections.add(electionDto); } validator.setVerified(true); validator.setObject(elections); validator.setStatus("Successfully selected"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setStatus("Select failed"); } return validator; } /** * @param election_owner_id * (int) - user_id of the user who owns elections * @return Validator : ArrayList<ElectionDto> - List of all the elections (not disabled only) * owned by the specific user (regardless of status) * @author Hirosh Wickramasuriya */ public Validator selectElectionsOwnedByUser(int electionOwnerId) { Validator validator = new Validator(); ArrayList<ElectionDto> elections = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT election_id, election_name, e.description, start_datetime, close_datetime," + " status, s.code, s.description, owner_id, candidates_string, type " + " FROM election e" + " INNER JOIN status_election s " + " ON (e.status = s.status_id) " + " WHERE owner_id = ? " + " AND status <> " + ElectionStatus.DELETED.getCode() + " ORDER BY election_id DESC"; try { st = this.con.prepareStatement(query); st.setInt(1, electionOwnerId); ResultSet res = st.executeQuery(); while (res.next()) { int electionId = res.getInt(1); String electionName = res.getString(2); String electionDescription = res.getString(3); String startDatetime = res.getString(4); String closeDatetime = res.getString(5); int statusId = res.getInt(6); String statusCode = res.getString(7); String statusDescription = res.getString(8); int ownerId = res.getInt(9); String candidatesListString = res.getString(10); int electionType = res.getInt(11); ElectionDto electionDto = new ElectionDto(); electionDto.setElectionId(electionId); electionDto.setElectionName(electionName); electionDto.setElectionDescription(electionDescription); electionDto.setStartDatetime(startDatetime); electionDto.setCloseDatetime(closeDatetime); electionDto.setStatus(statusId); electionDto.setStatusCode(statusCode); electionDto.setStatusDescription(statusDescription); electionDto.setOwnerId(ownerId); electionDto.setCandidatesListString(candidatesListString); electionDto.setElectionType(electionType); elections.add(electionDto); } validator.setVerified(true); validator.setObject(elections); validator.setStatus("Successfully selected"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setStatus("Select failed"); } return validator; } public Validator selectAllElectionsForVoter(int user_id) { Validator val = new Validator(); ArrayList<ElectionDto> elecs = new ArrayList<ElectionDto>(); PreparedStatement st = null; String query = "SELECT e.election_id, e.election_name, e.description, e.owner_id, " + "e.start_datetime, e.close_datetime FROM election as e " + "LEFT JOIN vote as v ON e.election_id = v.election_id " + "WHERE (v.user_id is null OR v.user_id != ?) AND e.status = ? " + "GROUP BY e.election_id"; try { st = this.con.prepareStatement(query); st.setInt(1, user_id); st.setInt(2, ElectionStatus.OPEN.getCode()); ResultSet res = st.executeQuery(); while (res.next()) { ElectionDto e = new ElectionDto(); e.setElectionId(res.getInt(1)); e.setCandidateList((ArrayList<CandidateDto>) selectCandidatesOfElection( e.getElectionId() , Status.ENABLED).getObject()); e.setElectionName(res.getString(2)); e.setElectionDescription(res.getString(3)); e.setOwnerId(res.getInt(4)); e.setStartDatetime(res.getString(5)); e.setCloseDatetime(res.getString(6)); elecs.add(e); } val.setStatus("Retrieved Elections"); val.setVerified(true); val.setObject(elecs); return val; } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("Select failed"); val.setVerified(false); return val; } } // Candidates /** * @param id * - candidate identification number (primary key) * @return Validator :CandidateDto - Details of a particular candidate * @author Hirosh Wickramasuriya */ public Validator selectCandidate(int id) { Validator validator = new Validator(); CandidateDto candidateDto = new CandidateDto(); PreparedStatement st = null; String query = "SELECT candidate_id, candidate_name, election_id, display_order, status FROM candidate WHERE candidate_id = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, id); ResultSet res = st.executeQuery(); if (res.next()) { int candidateId = res.getInt(1); String candidate_name = res.getString(2); int electionId = res.getInt(3); int displayOrder = res.getInt(4); int statusId = res.getInt(5); candidateDto.setCandidateId(candidateId); candidateDto.setCandidateName(candidate_name); candidateDto.setElectionId(electionId); candidateDto.setDisplayOrder(displayOrder); candidateDto.setStatus(statusId); validator.setVerified(true); validator.setObject(candidateDto); validator.setStatus("Successfully selected"); } else { validator.setStatus("Candidate not found"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setStatus("Select failed"); } return validator; } /** * @param electionIdKey * - election identification number * @return Validator : ArrayList<CandidateDto>- list of all the candidates * under specified election * @author Hirosh Wickramasuriya */ public Validator selectCandidatesOfElection(int electionIdKey) { Validator validator = new Validator(); ArrayList<CandidateDto> candidates = new ArrayList<CandidateDto>(); PreparedStatement st = null; String query = "SELECT candidate_id, candidate_name, election_id, display_order, status FROM candidate WHERE election_id = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, electionIdKey); ResultSet res = st.executeQuery(); while (res.next()) { int candidateId = res.getInt(1); String candidateName = res.getString(2); int electionId = res.getInt(3); int displayOrder = res.getInt(4); int statusId = res.getInt(5); CandidateDto candidateDto = new CandidateDto(); candidateDto.setCandidateId(candidateId); candidateDto.setCandidateName(candidateName); candidateDto.setElectionId(electionId); candidateDto.setDisplayOrder(displayOrder); candidateDto.setStatus(statusId); candidates.add(candidateDto); } validator.setVerified(true); validator.setObject(candidates); validator.setStatus("Successfully selected"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setStatus("select failed"); } return validator; } /** * @param electionIdKey * - election identification number * @param candidateStatus * - desired status of candidate which required to be returned * for given election * @return Validator :ArrayList<CandidateDto> - list of all the candidates * that matches the status under specified election * @author Hirosh Wickramasuriya */ public Validator selectCandidatesOfElection(int electionIdKey, Status candidateStatus) { Validator validator = new Validator(); ArrayList<CandidateDto> candidates = new ArrayList<CandidateDto>(); PreparedStatement st = null; String query = "SELECT candidate_id, candidate_name, election_id, display_order, status " + " FROM candidate " + " WHERE election_id = ?" + " AND status = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, electionIdKey); st.setInt(2, candidateStatus.getCode()); ResultSet res = st.executeQuery(); while (res.next()) { int candidateId = res.getInt(1); String candidateName = res.getString(2); int electionId = res.getInt(3); int displayOrder = res.getInt(4); int statusId = res.getInt(5); CandidateDto candidateDto = new CandidateDto(); candidateDto.setCandidateId(candidateId); candidateDto.setCandidateName(candidateName); candidateDto.setElectionId(electionId); candidateDto.setDisplayOrder(displayOrder); candidateDto.setStatus(statusId); candidates.add(candidateDto); } validator.setVerified(true); validator.setObject(candidates); validator.setStatus("Successfully selected"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); validator.setVerified(false); validator.setStatus("Select failed"); } return validator; } /** * @param electionIdKey * - election identification number * @return String : list of all the voters email participating the election (seperated by new line) * of a given election * @author Hirosh Wickramasuriya */ private String selectParticipatingVotersOfElection(int electionIdKey) { PreparedStatement st = null; String query = "SELECT p.user_id, p.election_id, email " + " FROM participate p" + " INNER JOIN users u" + " ON (p.user_id = u.user_id)" + " WHERE election_id = ?" + " GROUP BY p.user_id" ; String currentEmailList = ""; try { st = this.con.prepareStatement(query); st.setInt(1, electionIdKey); ResultSet res = st.executeQuery(); while (res.next()) { currentEmailList += res.getString(3) + newLine; } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return currentEmailList; } /** * @param name * - election name Add new election to db * @author Steven Frink */ private int addElectionWithCandidatesString(ElectionDto electionDto) { PreparedStatement st = null; ResultSet rs = null; int newId = 0; SecurityValidator sec=new SecurityValidator(); try { String query = "INSERT INTO election " + " (election_name, description, status, owner_id, candidates_string, start_datetime, close_datetime, type, allowed_users_emails, public_key, private_key)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; Validator keyVal=sec.generateKeyPair(); if(keyVal.isVerified()){ byte[] pk=((ArrayList<byte[]>)keyVal.getObject()).get(0); byte[] sk=DataEncryptor.AESEncrypt(((ArrayList<byte[]>)keyVal.getObject()).get(1), electionDto.getPassword()); st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, electionDto.getElectionName()); st.setString(2, electionDto.getElectionDescription()); st.setInt(3, ElectionStatus.NEW.getCode()); st.setInt(4, electionDto.getOwnerId()); st.setString(5, electionDto.getCandidatesListString()); st.setString(6, electionDto.getStartDatetime()); st.setString(7, electionDto.getCloseDatetime()); st.setInt(8, electionDto.getElectionType()); if (electionDto.getElectionType() == ElectionType.PRIVATE.getCode()) { st.setString(9, electionDto.getRegisteredEmailList()); } else { st.setString(9, ""); } Blob bpk=new SerialBlob(pk); st.setBlob(10, bpk); Blob bsk = new SerialBlob(sk); st.setBlob(11,bsk); // update query st.executeUpdate(); // get inserted id rs = st.getGeneratedKeys(); if (rs.next() ) { newId = rs.getInt(1); } } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } catch (Exception e){ Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, e.getMessage(), e); } return newId; } /** * @param electionDto - election details * @return Validator - with ElectionDto object with primary key assigned by the db, upon successful insert * @author Hirosh Wickramasuriya */ public Validator addElection(ElectionDto electionDto) { Validator val = new Validator(); // Validate the election Validator vElection = electionDto.Validate(); if (vElection.isVerified()) { int electionId = 0; // For private elections, check whether the given email addresses are registered if (electionDto.getElectionType() == ElectionType.PRIVATE.getCode()) { // private election - check all the emails Validator vEmailList = checkUserEmails(electionDto); ElectionDto electionDtoEmailChecked = (ElectionDto)vEmailList.getObject(); electionDto.setRegisteredEmailList(electionDtoEmailChecked.getRegisteredEmailList()); electionDto.setUnregisteredEmailList(electionDtoEmailChecked.getUnregisteredEmailList()); electionDto.setEmailListError(electionDtoEmailChecked.isEmailListError()); electionDto.setEmailListMessage(electionDtoEmailChecked.getEmailListMessage()); if (!electionDtoEmailChecked.isEmailListError()) { electionId = addElectionWithCandidatesString(electionDto); } } else if (electionDto.getElectionType() == ElectionType.PUBLIC.getCode()) { electionId = addElectionWithCandidatesString(electionDto); } // insert election if (electionId > 0) { electionDto.setElectionId(electionId); val.setObject(electionDto); val.setVerified(true & !electionDto.isEmailListError()); val.setStatus("Election has been inserted"); } else { val.setObject(electionDto); val.setVerified(false); val.setStatus("Election insert failed"); } } else { val = vElection; } return val; } /** * @param candidateDto * - candidate object * @param election_id * - id of the election which the candidate should be associated * @return Validator - status of the candidate insert operation * @author Hirosh Wickramasuriya */ private Validator addCandidate(CandidateDto candidateDto) { PreparedStatement st = null; ResultSet rs = null; Validator val = new Validator(); int newCandidateId = 0; try { String query = "INSERT INTO candidate (candidate_name, election_id, status, display_order) VALUES (?,?,?,?)"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, candidateDto.getCandidateName()); st.setInt(2, candidateDto.getElectionId()); st.setInt(3, Status.ENABLED.getCode()); st.setInt(4, candidateDto.getDisplayOrder()); // run the query and get new candidate id st.executeUpdate(); rs = st.getGeneratedKeys(); rs.next(); newCandidateId = rs.getInt(1); if (newCandidateId > 0) { candidateDto.setCandidateId(newCandidateId); val.setVerified(true); val.setStatus("Candidates inserted successfully"); val.setObject(candidateDto); } else { val.setStatus("Failed to insert candidate"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setVerified(false); val.setStatus("SQL Error"); } return val; } /** * @param electionDto * - election data object * @return validator - status of election update operation * @author Hirosh / Dmitry */ public Validator editElection(ElectionDto electionDto) { Validator val = new Validator(); // check the election status. ElectionDto vElectionCurrent = (ElectionDto) selectElection(electionDto.getElectionId()).getObject(); if (vElectionCurrent.getStatus() == ElectionStatus.NEW.getCode()) { // Validate Election Validator vElection = electionDto.Validate(); if (vElection.isVerified()) { // For private elections, check whether the given email addresses are registered Validator vEditElection = new Validator(); if (electionDto.getElectionType() == ElectionType.PRIVATE.getCode()) { // private election - check all the emails Validator vEmailList = checkUserEmails(electionDto); ElectionDto electionDtoEmailChecked = (ElectionDto)vEmailList.getObject(); electionDto.setRegisteredEmailList(electionDtoEmailChecked.getRegisteredEmailList()); electionDto.setUnregisteredEmailList(electionDtoEmailChecked.getUnregisteredEmailList()); electionDto.setEmailListError(electionDtoEmailChecked.isEmailListError()); electionDto.setEmailListMessage(electionDtoEmailChecked.getEmailListMessage()); if (!electionDtoEmailChecked.isEmailListError()) { // Update the election details if all email good for private election vEditElection = editElectionWithCandidatesString(electionDto); } } else if (electionDto.getElectionType() == ElectionType.PUBLIC.getCode()) { // updated the election details of public election vEditElection = editElectionWithCandidatesString(electionDto); } val.setObject(electionDto); val.setStatus(vEditElection.getStatus()); val.setVerified(vEditElection.isVerified() & !electionDto.isEmailListError()); } else { val = vElection; } } else { val.setStatus("Election status is " + vElectionCurrent.getStatusCode() + ", does not allow to modify."); } return val; } /** * @param electionDto * - election data object * @return validator - status of election update operation * @author Hirosh / Dmitry */ public Validator openElectionAndPopulateCandidates(int electionId) { Validator val = new Validator(); Validator vElectionStatus = compareElectionStatus(electionId, ElectionStatus.NEW); // Retrieve the election object in the db ElectionDto electionInDb = (ElectionDto)vElectionStatus.getObject(); if (vElectionStatus.isVerified()) { // Validate the election, so that all the candidates get validated, // and also the list of email account for private election Validator vElection = electionInDb.Validate(); if (vElection.isVerified()) { // remove if there are any candidates already for this election deleteCandidates( electionInDb.getElectionId() ); // add the list of candidates Validator vAddCandidates = addCandidates(electionId, electionInDb.getCandidatesListString()); if (vAddCandidates.isVerified()) { // add allowed users for private elections if (electionInDb.getElectionType() == ElectionType.PRIVATE.getCode()) { Validator vAddUsers = addAllowedUsers(electionId, electionInDb.getRegisteredEmailList()); if (vAddUsers.isVerified()) { } else { // remove the candidates already added deleteCandidates( electionInDb.getElectionId() ); val = vAddUsers; } } // change the status of electio to OPEN Validator vElectionStatusOpen = editElectionStatus(electionId, ElectionStatus.OPEN); if (vElectionStatusOpen.isVerified()) { val.setVerified(true); val.setStatus("Election has been opened."); } else { val = vElectionStatusOpen; } } else { val = vAddCandidates; } } else { val.setStatus(vElection.getStatus()); } } else { val.setStatus(vElectionStatus.getStatus()); } return val; } private Validator addCandidates(int electionId, String candidatesListString) { Validator val = new Validator(); // split the list of candidates by new line into an array of string String[] candidateNames = candidatesListString.split(newLine); int displayOrder = 1; boolean status = true; for (String candidateName : candidateNames) { // add each candidate to this election CandidateDto candidateDto = new CandidateDto(); candidateDto.setCandidateName(candidateName); candidateDto.setDisplayOrder(displayOrder); candidateDto.setElectionId(electionId); // add candidate to the election Validator vCandiateInserted = addCandidate(candidateDto); val.setStatus(val.getStatus() + newLine + vCandiateInserted.getStatus()); status &= vCandiateInserted.isVerified(); displayOrder++; } val.setVerified(status); if (status) { val.setVerified(true); val.setStatus("Candidates have been added to the election"); } return val; } public Validator addAdditionalUsersToElection(ElectionDto electionDto) { Validator val = new Validator(); // check the election status. ElectionDto electionDtoCurrent = (ElectionDto) selectElection(electionDto.getElectionId()).getObject(); if (electionDtoCurrent.getStatus() == ElectionStatus.NEW.getCode() || electionDtoCurrent.getStatus() == ElectionStatus.OPEN.getCode() ) { // Election is NEW or OPEN state // These properties are set from the db, in order to pass the validation. electionDto.setElectionName(electionDtoCurrent.getElectionName()); electionDto.setElectionDescription(electionDtoCurrent.getElectionDescription()); electionDto.setElectionType(electionDtoCurrent.getElectionType()); electionDto.setCandidatesListString(electionDtoCurrent.getCandidatesListString()); // Validate Election Validator vElection = electionDto.Validate(); if (vElection.isVerified()) { // For private elections, check whether the given email addresses are registered Validator vEditElection = new Validator(); if (electionDtoCurrent.getElectionType() == ElectionType.PRIVATE.getCode()) { // private election - check all the emails Validator vEmailList = checkUserEmails(electionDto); ElectionDto electionDtoEmailChecked = (ElectionDto)vEmailList.getObject(); electionDto.setRegisteredEmailList(electionDtoEmailChecked.getRegisteredEmailList()); electionDto.setUnregisteredEmailList(electionDtoEmailChecked.getUnregisteredEmailList()); electionDto.setEmailListError(electionDtoEmailChecked.isEmailListError()); electionDto.setEmailListMessage(electionDtoEmailChecked.getEmailListMessage()); if (!electionDtoEmailChecked.isEmailListError()) { // add new users to the participate table if all email good for private election Validator vAddUsers = addAllowedUsers(electionDto.getElectionId(), electionDto.getRegisteredEmailList()); val = vAddUsers; // Verified status is set to true or false by the previous statement } else { val.setStatus(electionDtoEmailChecked.getEmailListMessage()); } // get the current users' email list electionDto.setCurrentEmailList(selectParticipatingVotersOfElection(electionDto.getElectionId())); val.setObject(electionDto); } else { // not a private election, do not add users vEditElection.setStatus("This is not a private election, cannot add new users to this election"); } } else { val = vElection; } } else { val.setStatus("Election status is " + electionDtoCurrent.getStatusCode() + ", does not allow to add new users"); } return val; } private Validator addAllowedUsers(int electionId, String emailListString) { Validator val = new Validator(); // split the list of emails by new line into an array of string String[] emails = emailListString.split(newLine); boolean status = true; for (String email : emails) { // add users to participate table Validator vAddUser = AddAllowedUser(electionId, email, UserRole.ELECTORATE); val.setStatus(val.getStatus() + newLine + vAddUser.getStatus()); status &= vAddUser.isVerified(); } val.setVerified(status); if (status) { val.setVerified(true); val.setStatus("Users have been allowed to participate the election"); } return val; } private Validator AddAllowedUser(int electionId, String email, UserRole userRole) { Validator val = new Validator(); PreparedStatement st = null; try { String query = "INSERT INTO participate " + " (user_id, election_id, role_id) " + " VALUES " + "( " + " (SELECT user_id FROM users WHERE email = ?) " + " , ?" + " , ? " + ")"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, email); st.setInt(2, electionId); st.setInt(3, userRole.getCode()); // run the query and get the count of rows updated int recInserted = st.executeUpdate(); if (recInserted > 0) { // successfully inserted val.setVerified(true); val.setStatus("User allowed to vote is inserted successfully"); } else { val.setStatus("Failed to insert user : " + email); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setVerified(false); val.setStatus("SQL Error"); } return val; } public Validator editCandidateStatus(CandidateDto cand) { PreparedStatement st = null; //InputValidation iv = new InputValidation(); Validator val = new Validator(); try { //val = iv.validateInt(cand.getStatus(), "Candidate Status"); if (val.isVerified()) { String query = "UPDATE candidate SET status=? WHERE candidate_id=?"; st = this.con.prepareStatement(query); st.setInt(1, cand.getStatus()); st.setInt(2, cand.getCandidateId()); st.execute(); val.setVerified(true); val.setStatus("Candidate status updated"); } else { val.setStatus("Status failed to verify"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } /** * @param electionId - election identification number * @return boolean - true : if the election is deleted successfully, else false * @author Hirosh Wickramasuriya */ private boolean deleteCandidates(int electionId) { PreparedStatement st = null; boolean status = false; try { String query = "DELETE FROM candidate WHERE election_id = ?"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setInt(1, electionId); // update query if (st.executeUpdate() < 0) { // delete failed } else { // delete= sucessful status = true; } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return status; } /** * @param electionId * - the election id to update the status Delete an election * @param electionStatus * - new status of the election * @return validator - validator object with response of update operation * @author Steven Frink */ public Validator editElectionStatus(int electionId, ElectionStatus electionStatus) { PreparedStatement st = null; Validator val = new Validator(); try { String query = ""; if (electionStatus.equals(ElectionStatus.OPEN)) { query = "UPDATE election SET status=?, allowed_users_emails = null WHERE election_id=?"; } else { query = "UPDATE election SET status=? WHERE election_id=?"; } st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setInt(1, electionStatus.getCode()); st.setInt(2, electionId); st.executeUpdate(); int updateCount = st.getUpdateCount(); if (updateCount > 0) { val.setStatus("Election status updated successfully"); val.setVerified(true); } else { val.setStatus("Failed to update the election status"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } /** * @param electionDto * - the election to edit Edit an election * @author Steven Frink */ private Validator editElectionWithCandidatesString(ElectionDto electionDto) { PreparedStatement st = null; Validator val = new Validator(); try { String query = "UPDATE election SET election_name = ? " + " , description = ? " + " , candidates_string = ? " + " , start_datetime = ? " + " , close_datetime = ? " + " , type = ?" + " , allowed_users_emails = ? " + " WHERE election_id=?"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, electionDto.getElectionName()); st.setString(2, electionDto.getElectionDescription()); st.setString(3, electionDto.getCandidatesListString()); st.setString(4, electionDto.getStartDatetime()); st.setString(5, electionDto.getCloseDatetime()); st.setInt(6, electionDto.getElectionType()); if (electionDto.getElectionType() == ElectionType.PRIVATE.getCode()) { st.setString(7, electionDto.getRegisteredEmailList()); } else { st.setString(7, ""); } st.setInt(8, electionDto.getElectionId()); st.executeUpdate(); int updateCount = st.getUpdateCount(); if (updateCount > 0) { val.setStatus("Election updated successfully"); val.setVerified(true); } else { val.setStatus("Failed to update the election"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } // Vote /** * @param voteDto * - the vote to submit Submit a vote * @author Steven Frink */ public Validator vote(VoteDto voteDto) { PreparedStatement st = null; Validator val = new Validator(); if (voteDto.Validate().isVerified()) { try { String query = "SELECT user_id, election_id FROM vote WHERE user_id=? AND election_id=?"; st = this.con.prepareStatement(query); st.setInt(1, voteDto.getUserId()); st.setInt(2, voteDto.getElectionId()); ResultSet rs = st.executeQuery(); SecurityValidator sec = new SecurityValidator(); if (!rs.next() && sec.checkSignature(voteDto.getVoteSignature(), voteDto.getVoteEncrypted(), voteDto.getUserId()).isVerified()) { query = "INSERT INTO vote (user_id, election_id, vote_encrypted, vote_signature)" + " VALUES (?,?,?,?)"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setInt(1, voteDto.getUserId()); st.setInt(2, voteDto.getElectionId()); st.setString(3, voteDto.getVoteEncrypted()); st.setString(4, voteDto.getVoteSignature()); int updateCount = st.executeUpdate(); if (updateCount > 0) { val.setStatus("Vote successfully cast"); val.setVerified(true); } else { val.setStatus("Failed to cast vote"); } } else { voteDto.setVoteSignatureError(true); voteDto.setVoteSignatureErrorMessage("invalid signature for this vote"); val.setObject(voteDto); val.setStatus("invalid signature for this vote"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } } else { val.setStatus("Vote information did not validate"); } return val; } /** * @param userDto * - userDetails with public key * @return Validator - status of the public key update operation * @author Hirosh Wickramasuriya * This function can be called only by admins. */ public Validator editUserPublicKey(UserDto userDto) { PreparedStatement st = null; Validator val = new Validator(); String query = "UPDATE users SET public_key = ? WHERE user_id = ?"; Validator vUserDto = userDto.Validate(); if (vUserDto.isVerified()) { try { st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, userDto.getPublicKey()); st.setInt(2, userDto.getUserId()); int updateCount = st.executeUpdate(); if (updateCount > 0) { val.setStatus("User's public key updated successfully"); val.setVerified(true); } else { val.setStatus("Failed to update the user's public key"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } } else { val = vUserDto; } return val; } /** * @param userDto * - userDto with the userId * @return Validator - with user's public key * @author Steven Frink */ public Validator selectUserPublicKey(UserDto userDto) { PreparedStatement st = null; Validator val = new Validator(); InputValidation iv = new InputValidation(); Validator vUserDto = iv.validateInt(userDto.getUserId(), "User ID"); // Validator vUserDto = userDto.Validate(); if (vUserDto.isVerified()) { String query = "SELECT public_key FROM users WHERE user_id = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, userDto.getUserId()); ResultSet res = st.executeQuery(); if (res.next()) { Blob pubKey = res.getBlob(1); byte[] pk = pubKey.getBytes(1, (int) pubKey.length()); val.setObject(pk); val.setVerified(true); val.setStatus("Public key retrieved"); } else { val.setStatus("No public key for this user id"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } } else { val = vUserDto; // Failed to validate the user id } return val; } public Validator selectVotesByElectionId(int election_id) { Validator val = new Validator(); InputValidation iv = new InputValidation(); ArrayList<VoteDto> votes = new ArrayList<VoteDto>(); Validator vElection = iv.validateInt(election_id, "Election ID"); PreparedStatement st = null; try { if (vElection.isVerified()) { String query = "SELECT user_id, vote_encrypted, vote_signature, timestamp " + " FROM vote " + " WHERE election_id = ?"; st = this.con.prepareStatement(query); st.setInt(1, election_id); ResultSet res = st.executeQuery(); while (res.next()) { int user_id = res.getInt(1); String vote_encrypted = res.getString(2); String vote_signature = res.getString(3); Timestamp t = res.getTimestamp(4); VoteDto vote = new VoteDto(); vote.setUserId(user_id); vote.setVoteEncrypted(vote_encrypted); vote.setVoteSignature(vote_signature); vote.setElectionId(election_id); vote.setTimestamp(t); votes.add(vote); } val.setStatus("Successfully retrieved votes"); val.setObject(votes); val.setVerified(true); } else { val = vElection; // Failed to validate the election id } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } public Validator checkCandidateInElection(int electionId, int cand_id){ Validator val=new Validator(); ArrayList<CandidateDto> candidatesOfElection = (ArrayList<CandidateDto>) selectCandidatesOfElection(electionId, Status.ENABLED).getObject(); boolean validCand = false; for (int j = 0; j < candidatesOfElection.size(); j++) { if (candidatesOfElection.get(j).getCandidateId() == cand_id) { validCand = true; break; } } val.setVerified(validCand); return val; } private Validator checkUserEmails(ElectionDto electionDto){ Validator val=new Validator(); String registeredEmails = ""; String unregisteredEmails = ""; boolean allRegisteredEmails = true; if (electionDto.getEmailList() != null) { String[] emails = electionDto.getEmailList().split(newLine); for (String email : emails) { String emailTrimmed = email.trim(); if (checkUserEmail(emailTrimmed).isVerified()) { registeredEmails += emailTrimmed + newLine; } else { unregisteredEmails += emailTrimmed + newLine; allRegisteredEmails = false; } } } electionDto.setRegisteredEmailList(registeredEmails); electionDto.setUnregisteredEmailList(unregisteredEmails); electionDto.setEmailListError(!allRegisteredEmails); if (allRegisteredEmails) { val.setVerified(true); val.setStatus("All email addresses are valid"); } else { val.setVerified(false); val.setStatus("Unregistered email addresses detected"); electionDto.setEmailListMessage("Unregistered email addresses detected"); } val.setObject(electionDto); return val; } private Map<Integer, CandidateDto> initMap(ElectionDto elec){ Map<Integer, CandidateDto> map = new HashMap<Integer, CandidateDto>(); // initialize the hashmap to have all the candidates for (CandidateDto candidate : elec.getCandidateList()) { map.put(candidate.getCandidateId(), candidate); } return map; } private Map<Integer, CandidateDto> addToMap(Map<Integer, CandidateDto> map, int cand_id){ if (map.containsKey(cand_id)) { // candidateDto is in the Hashmap CandidateDto candidateDto = map.get(cand_id); candidateDto.addVoteCount(); // replace the candidateDto in the Hashmap map.remove(cand_id); map.put(cand_id, candidateDto); // TODO: not sure without these twolines, // value is udpated by reference } else { // this is a new candidateDto to the Hashmap CandidateDto candidateDto = (CandidateDto) selectCandidate(cand_id).getObject(); candidateDto.setVoteCount(1); // First voted counted map.put(cand_id, candidateDto); } return map; } private ElectionDto putResultsInElection(Map<Integer, CandidateDto> map, ElectionDto e){ ArrayList<CandidateDto> candidateResultList = new ArrayList<CandidateDto>(); Iterator<Integer> iterator = map.keySet().iterator(); while (iterator.hasNext()) { Integer key = iterator.next(); CandidateDto candidateResult = map.get(key); candidateResultList.add(candidateResult); } e.setCandidateList(candidateResultList); return e; } private int getDecryptedCandId(VoteDto vote, String password, int electionId){ String enc = vote.getVoteEncrypted(); String sig = vote.getVoteSignature(); SecurityValidator sec=new SecurityValidator(); if (sec.checkSignature(sig, enc, vote.getUserId()).isVerified()){ //System.out.println(" String plainHex=sec.decrypt(enc, password, electionId); //System.out.println(" byte[] plain=sec.hexStringtoByteArray(plainHex); String id=new String(plain); int cand_id = Integer.parseInt(id); return cand_id; } else{ return -1; } } /** * @param electionId * @return Validator with ElectionDto that has results * @author Steven Frink/Hirosh Wickramasuriya */ public Validator tally(ElectionDto elec) { Validator val = new Validator(); // get the votes for this election Validator voteVal = selectVotesByElectionId(elec.getElectionId()); if (voteVal.isVerified()) { Map<Integer, CandidateDto> map=initMap(elec); ArrayList<VoteDto> votes = (ArrayList<VoteDto>) voteVal.getObject(); // all the votes for the election // check the validity of each vote, decrypt and count the vote for (int i = 0; i < votes.size(); i++) { int cand_id=getDecryptedCandId(votes.get(i), elec.getPassword(), elec.getElectionId()); if (cand_id!=-1) { map=addToMap(map, cand_id); } } // attach the candidates list with results to the ElectionDto elec=putResultsInElection(map, elec); val.setStatus("Tally computed"); val.setObject(elec); val.setVerified(true); } else { val = voteVal; } return val; } /** * @param electionId * @return Validator with ElectionProgressDto * @author Hirosh Wickramasuriya */ public Validator voteProgressStatusForElection(int electionId) { Validator val = new Validator(); SecurityValidator sec = new SecurityValidator(); ElectionProgressDto electionProgressDto = new ElectionProgressDto(); if (electionId > 0) { electionProgressDto.setElectionId(electionId); Validator valVote = selectVotesByElectionId(electionId); if (valVote.isVerified()) { ArrayList<VoteDto> votes = (ArrayList<VoteDto>) valVote.getObject(); electionProgressDto.setTotalVotes(votes.size()); for (VoteDto voteDto : votes) { // check for the validity if (sec.checkSignature(voteDto).isVerified()) { // valid vote electionProgressDto.addValidVotes(1); } else { // rejected vote electionProgressDto.addRejectedVotes(1); } } // bind the final result to the validator val.setObject(electionProgressDto); val.setStatus("Election progress computed"); val.setVerified(true); } else { val = valVote; } } else { val.setStatus("Invalid Election Id"); } return val; } public Validator publishResults(int electionId, String password) { Validator val = new Validator(); Validator vElectionStatus = compareElectionStatus(electionId, ElectionStatus.CLOSED); if (vElectionStatus.isVerified()) { Validator vResult = computeElectionResults(electionId, password); if (vResult.isVerified()) { vElectionStatus = editElectionStatus(electionId, ElectionStatus.PUBLISHED); if (vElectionStatus.isVerified()) { val.setStatus("Election results has been published"); val.setVerified(true); } else { val = vElectionStatus; } } else { val = vResult; } } else { val = vElectionStatus; } return val; } /** * @param electionId - election identificatin number * @return Validator - (1) true if the election results computed and the table is populated successfully * (2) false if it failed to compute and populate the election results * @author Hirosh Wickramasuriya */ private Validator computeElectionResults(int electionId, String password) { Validator val = new Validator(); // check the election status Validator vElectionStatus = compareElectionStatus(electionId, ElectionStatus.CLOSED); if (vElectionStatus.isVerified()) { ElectionDto electionDto = (ElectionDto)vElectionStatus.getObject(); electionDto.setPassword(password); // get the tallying results Validator vElectionTally = tally(electionDto); if (vElectionTally.isVerified()) { // Get the results for each candidates electionDto = (ElectionDto)vElectionTally.getObject(); ArrayList<CandidateDto> candidates = electionDto.getCandidateList(); boolean valid = true; for (CandidateDto candidate : candidates) { if (addResult(candidate) > 0) { valid &= true; // result has been added } else { // Failed to add the result deleteResults(electionDto.getElectionId()); // delete existing results if any val.setStatus("Failed to add results"); // set the validator valid &= false; break; } } val.setVerified(valid); if (valid) { val.setStatus("Results added successfully"); } else { val.setStatus("Failed to add results"); } } else { val = vElectionTally; } } else { val = vElectionStatus; } return val; } /** * @param ElectionDto - Election object * @param electionStatus - ElectionStatus enumerated value * @return Validator - the property isVerified() contains whether the given status * matches to the status of the given electionDto * @author Hirosh Wickramasuriya */ private Validator compareElectionStatus(ElectionDto electionDto, ElectionStatus electionStatus) { Validator val = new Validator(); if (electionDto.getStatus() == electionStatus.getCode()) { val.setObject(electionDto); val.setStatus("Status matched"); val.setVerified(true); } else { val.setStatus("Election is not in the " + electionStatus.getLabel() + " status"); } return val; } /** * @param electionId - Election identification number * @param electionStatus - ElectionStatus enumerated value * @return Validator - the property isVerified() contains whether the given status * matches to the status recorded in the database for the given election id * @author Hirosh Wickramasuriya */ private Validator compareElectionStatus(int electionId, ElectionStatus electionStatus) { Validator val = new Validator(); Validator vElection = selectElection(electionId); if (vElection.isVerified()) { val = compareElectionStatus((ElectionDto)vElection.getObject(), electionStatus ); } else { val = vElection; } return val; } /** * @param candidateDto - candiate object to be added to the results table * @return id of the inserted result record * @author Hirosh Wickramasuriya */ private int addResult(CandidateDto candidateDto) { PreparedStatement st = null; ResultSet rs = null; int newId = 0; try { String query = "INSERT INTO results (election_id, candidate_id, vote_count) VALUES (?,?,?)"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setInt(1, candidateDto.getElectionId()); st.setInt(2, candidateDto.getCandidateId()); st.setInt(3, candidateDto.getVoteCount()); // update query st.executeUpdate(); // get inserted id rs = st.getGeneratedKeys(); rs.next(); newId = rs.getInt(1); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return newId; } /** * @param electionId - election identification number * @return boolean - true : if the election is deleted successfully, else false * @author Hirosh Wickramasuriya */ private boolean deleteResults(int electionId) { PreparedStatement st = null; boolean status = false; try { String query = "DELETE FROM results WHERE election_id = ?"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setInt(1, electionId); // update query if (st.executeUpdate() < 0) { // delete failed } else { // delete= sucessful status = true; } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return status; } /** * @param electionId - election identification number * @return Validator - with ElectionDto having results of each candidates * @author Hirosh Wickramasuriya */ public Validator selectResults(int electionId) { Validator val = new Validator(); ArrayList<CandidateDto> candidates = new ArrayList<CandidateDto>(); PreparedStatement st = null; Validator vElectionStatus = compareElectionStatus(electionId, ElectionStatus.PUBLISHED); if (vElectionStatus.isVerified()) { ElectionDto electionDto = (ElectionDto)vElectionStatus.getObject(); try { String query = "SELECT r.election_id, r.candidate_id, vote_count, candidate_name, display_order, status" + " FROM results r" + " INNER JOIN candidate c" + " ON (r.candidate_id = c.candidate_id)" + " WHERE r.election_id = ?"; int maxVote = 0; st = this.con.prepareStatement(query); st.setInt(1, electionId); ResultSet res = st.executeQuery(); while (res.next()) { int resElectionId = res.getInt(1); int resCandidateId = res.getInt(2); int resVoteCount = res.getInt(3); String resCandiateName = res.getString(4); int resDisplayOrder = res.getInt(5); int resStatus = res.getInt(6); // populate candidates list CandidateDto candidateDto = new CandidateDto(); candidateDto.setCandidateId(resCandidateId); candidateDto.setCandidateName(resCandiateName); candidateDto.setElectionId(resElectionId); candidateDto.setDisplayOrder(resDisplayOrder); candidateDto.setVoteCount(resVoteCount); candidateDto.setStatus(resStatus); // indicate the winning candidate if (resVoteCount > maxVote) { for (CandidateDto candidate : candidates) { candidate.setWinner(false); } candidateDto.setWinner(true); maxVote = resVoteCount; } else if ( (resVoteCount == maxVote) && (resVoteCount >0)) { candidateDto.setWinner(true); } candidates.add(candidateDto); } electionDto.setCandidateList(candidates); // attach candidates list to the election // set the validator val.setVerified(true); val.setObject(electionDto); val.setStatus("Results selected successfully"); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("Select failed"); } } else { val = vElectionStatus; } return val; } // User /** * @param userDto * @return Validator with the userDto including the primary key assigned by the db. */ public Validator addUser(UserDto userDto) { Validator val = new Validator(); PreparedStatement st = null; ResultSet rs = null; int newUserId = 0; // Validate the user Validator vUser = userDto.Validate(); if (vUser.isVerified()) { // insert user String query = "INSERT INTO users (first_name, last_name, email) " + " VALUES (?, ?, ?)"; try { st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, userDto.getFirstName()); st.setString(2, userDto.getLastName()); st.setString(3, userDto.getEmail()); // run the query and get new user id st.executeUpdate(); rs = st.getGeneratedKeys(); rs.next(); newUserId = rs.getInt(1); if (newUserId > 0) { userDto.setUserId(newUserId); val.setVerified(true); val.setStatus("User inserted successfully"); val.setObject(userDto); } else { val.setStatus("Failed to insert user"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setVerified(false); val.setStatus("SQL Error"); } } else { val = vUser; } return val; } /** * @return - Validator with ArrayList<UserDto> all the users in the system * @author Hirosh Wickramasuriya */ public Validator selectAllUsers() { Validator val = new Validator(); ArrayList<UserDto> users = new ArrayList<UserDto>(); PreparedStatement st = null; String query = "SELECT user_id, first_name, last_name, email " + " , u.status, s.description " + " FROM users u" + " INNER JOIN status_user s" + " ON (u.status = s.status_id)" + " ORDER BY user_id"; try { st = this.con.prepareStatement(query); ResultSet res = st.executeQuery(); while (res.next()) { UserDto userDto = new UserDto(); userDto.setUserId(res.getInt(1)); userDto.setFirstName(res.getString(2)); userDto.setLastName(res.getString(3)); userDto.setEmail(res.getString(4)); userDto.setStatus(res.getInt(5)); userDto.setStatusDescription(res.getString(6)); users.add(userDto); } val.setStatus("Retrieved Users"); val.setVerified(true); val.setObject(users); } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("Select failed"); } return val; } /** * @param - userId - user identificaiton number * @return - Validator with UserDto containing user information for the given user id * @author Hirosh Wickramasuriya */ public Validator selectUser(int userId) { Validator val = new Validator(); UserDto userDto = new UserDto(); PreparedStatement st = null; String query = "SELECT user_id, first_name, last_name, email " + " , u.status, s.description " + " FROM users u" + " INNER JOIN status_user s" + " ON (u.status = s.status_id)" + " WHERE user_id = ?"; try { st = this.con.prepareStatement(query); st.setInt(1, userId); ResultSet res = st.executeQuery(); if (res.next()) { userDto.setUserId(res.getInt(1)); userDto.setFirstName(res.getString(2)); userDto.setLastName(res.getString(3)); userDto.setEmail(res.getString(4)); userDto.setStatus(res.getInt(5)); userDto.setStatusDescription(res.getString(6)); val.setStatus("Retrieved user information"); val.setVerified(true); val.setObject(userDto); } else { val.setStatus("User not found "); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("Select failed"); } return val; } /** * @param userDto * @return with the verified status true upon successful update, false otherwise * @author Hirosh Wickramasuriya */ public Validator editUser(UserDto userDto) { Validator val = new Validator(); PreparedStatement st = null; try { String query = "UPDATE users SET first_name = ?," + " last_name = ?," + " email = ?," + " status = ? " + " WHERE user_id=?"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, userDto.getFirstName()); st.setString(2, userDto.getLastName()); st.setString(3, userDto.getEmail()); st.setInt(4, userDto.getStatus()); st.setInt(5, userDto.getUserId()); st.executeUpdate(); int updateCount = st.getUpdateCount(); if (updateCount > 0) { val.setStatus("User updated successfully"); val.setVerified(true); } else { val.setStatus("Failed to update the user"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } /** * @param userId * @param userStatus - UserStatus enumeration value * @return Validator with status true upon successful update, false otherwise * @author Hirosh Wickramasuriya */ public Validator editUserStatus(int userId, UserStatus userStatus){ Validator val = new Validator(); PreparedStatement st = null; try { String query = "UPDATE users SET status = ? WHERE user_id=?"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setInt(1, userStatus.getCode()); st.setInt(2, userId); st.executeUpdate(); int updateCount = st.getUpdateCount(); if (updateCount > 0) { val.setStatus("User status updated successfully"); val.setVerified(true); } else { val.setStatus("Failed to update the user status"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } // get user role by the user id: public Validator getUserRoleByID(int userID){ Validator val = new Validator(); PreparedStatement st = null; try{ String query = "SELECT admin from users where (user_id = ?)"; st = con.prepareStatement(query); st.setInt(1, userID); ResultSet res = st.executeQuery(); if (res.next()) { val.setVerified(true); val.setStatus("User found."); val.setObject(res.getInt(1)); }else{ val.setVerified(false); val.setStatus("User not found."); } }catch (SQLException ex){ Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } // check if a user role is permitted to do an action: public Validator checkRoleRight(int roleID, int actionID){ Validator val = new Validator(); PreparedStatement st = null; try{ String query = "SELECT * from role_rights where ((role_id = ? ) && (action_id = ?))"; st = con.prepareStatement(query); st.setInt(1, roleID); st.setInt(2, actionID); ResultSet res = st.executeQuery(); if (res.next()) { val.setVerified(true); val.setStatus("User role is allowed to invoke action."); }else{ val.setVerified(false); val.setStatus("User role is not allowed to invoke action."); } }catch (SQLException ex){ Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } //get action id by the method name: public Validator getActionIDbyMethod(String methodName){ Validator val = new Validator(); PreparedStatement st = null; try{ String query = "SELECT action_id from actions where (method_name = ?)"; st = con.prepareStatement(query); st.setString(1, methodName); ResultSet res = st.executeQuery(); if (res.next()) { val.setVerified(true); val.setStatus("Method name found."); val.setObject(res.getInt(1)); }else{ val.setVerified(false); val.setStatus("Method name is not found."); } }catch (SQLException ex){ Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } //get all the rights allowed for a user role: public Validator getRoleRights(int roleID){ Validator val = new Validator(); PreparedStatement st = null; ArrayList<ActionDto> rightsListArray = new ArrayList<ActionDto>(); try{ String query = "SELECT action_id FROM role_rights where (role_id = ?)"; st = con.prepareStatement(query); st.setInt(1, roleID); ResultSet res = st.executeQuery(); while (res.next()){ ActionDto action = new ActionDto(); action.setActionID(res.getInt(1)); rightsListArray.add(action); } if (rightsListArray.size() != 0){ val.setVerified(true); val.setStatus("Rights found."); val.setObject(rightsListArray); }else{ val.setVerified(false); val.setStatus("No rights found."); } }catch (SQLException ex){ Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } //register new user: public Validator registerNewUser(UserDto newUser){ Validator res = new Validator(); if (checkUserEmail(newUser.getEmail()).isVerified()){ //email found, cannot add user: res.setVerified(false); res.setStatus("E-mail address is used."); }else{ //email address is not found, let's add it: //first we need to generate some salt to hash the password: String salt = PasswordHasher.generateSalt(); //hash the password: String hashedPass = PasswordHasher.sha512(newUser.getPassword(), salt); //let's generate the keys and protect the private key with the users protecion password: String keyPass = newUser.getTempPassword(); RSAKeys rsaKeys = new RSAKeys(); rsaKeys.generateKeys(keyPass); //get the public key to be saved at the DB: PublicKey pubKey = rsaKeys.getPublicKey(); //ready to push to DB: PreparedStatement st = null; ResultSet rs = null; int newUserId = 0; // Validate the user Validator vUser = newUser.Validate(); if (vUser.isVerified()) { // insert user String query = "INSERT INTO users (first_name, last_name, email, password, salt, " + "public_key, admin, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; try { st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, newUser.getFirstName()); st.setString(2, newUser.getLastName()); st.setString(3, newUser.getEmail()); st.setString(4, hashedPass); st.setString(5, salt); Blob pubKeyBlob = new SerialBlob(pubKey.getEncoded()); st.setBlob(6, pubKeyBlob); st.setInt(7, 0); st.setInt(8, 1); // run the query and get new user id st.executeUpdate(); rs = st.getGeneratedKeys(); rs.next(); newUserId = rs.getInt(1); if (newUserId > 0) { newUser.setUserId(newUserId); res.setVerified(true); res.setStatus("User inserted successfully"); //send the private key as an email: rsaKeys.sendProtectedPrivateKey(newUser.getEmail()); } else { res.setStatus("Failed to insert user"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); res.setVerified(false); res.setStatus("SQL Error"); } } else { res = vUser; } } return res; } //get the public key for a user: public byte[] getPublicKeyFromBlob(int userID){ byte [] res = null; PreparedStatement st = null; ResultSet rs = null; String query = "select public_key from users WHERE user_id=?"; try { st = con.prepareStatement(query); st.setInt(1, userID); rs = st.executeQuery(); if(rs.next()){ Blob b = rs.getBlob(1); int blobLength = (int) b.length(); res = b.getBytes(1, blobLength); } } catch (SQLException ex) { ex.printStackTrace(); } return res; } //get email address by user ID: public Validator getUesrEmail (int userID){ Validator res = new Validator(); PreparedStatement st = null; ResultSet rs = null; String query = "select email from users WHERE user_id=?"; try { st = con.prepareStatement(query); st.setInt(1, userID); rs = st.executeQuery(); if(rs.next()){ res.setVerified(true); res.setStatus(rs.getString(1)); }else{ res.setVerified(false); res.setStatus("User not found"); } } catch (SQLException ex) { ex.printStackTrace(); } return res; } //generate new keys for a user: public Validator generateNewKeys(int userID, String newKeyPass){ Validator res = null; res = getUesrEmail(userID); if (res.isVerified()){ String email = res.getStatus(); //let's generate the keys and protect the private key with the users protecion password: RSAKeys rsaKeys = new RSAKeys(); rsaKeys.generateKeys(newKeyPass); //get the public key to be saved at the DB: PublicKey pubKey = rsaKeys.getPublicKey(); PreparedStatement st = null; String query = "UPDATE users SET public_key=? WHERE user_id=?"; try { st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); Blob pubKeyBlob = new SerialBlob(pubKey.getEncoded()); st.setBlob(1, pubKeyBlob); st.setInt(2, userID); st.executeUpdate(); int updateCount = st.getUpdateCount(); if (updateCount > 0) { res.setStatus("User updated successfully"); res.setVerified(true); } else { res.setVerified(false); res.setStatus("Failed to update the user"); } //send the private key as an email: rsaKeys.sendProtectedPrivateKey(email); } catch (SQLException ex) { ex.printStackTrace(); } }else{ res.setVerified(false); res.setStatus("User not found"); } return res; } //Update user information - this function to be invked only by the users: public Validator updateUser(UserDto userDto) { Validator val = new Validator(); PreparedStatement st = null; try { String query = "UPDATE users SET first_name = ?, last_name = ? WHERE user_id=?"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, userDto.getFirstName()); st.setString(2, userDto.getLastName()); st.setInt(3, userDto.getUserId()); st.executeUpdate(); int updateCount = st.getUpdateCount(); if (updateCount > 0) { val.setStatus("User updated successfully"); val.setVerified(true); } else { val.setStatus("Failed to update the user"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("SQL Error"); } return val; } public boolean checkCorrectPassword(int userID, String password){ UserDto dbUser = new UserDto(); dbUser = selectUserById(userID); String dbHash = dbUser.getPassword(); String dbSalt = dbUser.getSalt(); String newHash = PasswordHasher.sha512(password, dbSalt); return newHash.equals(dbHash); } public Validator updateUserPassword(UserDto userInfo){ Validator res = new Validator(); String newPass = userInfo.getTempPassword(); int userID = userInfo.getUserId(); //first we need to generate some salt to hash the password: String newSalt = PasswordHasher.generateSalt(); //hash the password: String hashedPass = PasswordHasher.sha512(newPass, newSalt); //ready to update the password: PreparedStatement st = null; try { String query = "UPDATE users SET password = ?, salt = ? WHERE user_id=?"; st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); st.setString(1, hashedPass); st.setString(2, newSalt); st.setInt(3, userID); st.executeUpdate(); int updateCount = st.getUpdateCount(); if (updateCount > 0) { res.setStatus("Password updated successfully"); res.setVerified(true); } else { res.setStatus("Failed to update password"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); res.setStatus("SQL Error"); } return res; } public Validator uploadPubKey(byte[] keyBytes, int userID) { Validator res = new Validator(); PreparedStatement st = null; if (keyBytes == null){ res.setVerified(false); res.setStatus("Empty input"); return res; } String query = "UPDATE users SET public_key=? WHERE user_id=?"; try { st = this.con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); Blob pubKeyBlob = new SerialBlob(keyBytes); st.setBlob(1, pubKeyBlob); st.setInt(2, userID); st.executeUpdate(); int updateCount = st.getUpdateCount(); if (updateCount > 0) { res.setStatus("Public key updated successfully"); res.setVerified(true); } else { res.setVerified(false); res.setStatus("Failed to update public key"); } } catch (SQLException ex) { ex.printStackTrace(); res.setVerified(false); res.setStatus("SQL Exception"); } return res; } //Check if election is public: public boolean isPublicElection(int electionID){ boolean res = false; PreparedStatement st = null; String query = "SELECT type FROM election WHERE election_id=?"; try { st = con.prepareStatement(query); st.setInt(1, electionID); ResultSet rs = st.executeQuery(); if (rs.next()){ int type = rs.getInt(1); res = (type == 1) ? true : false; } } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); res = false; } return res; } //Check if userID got access to elecionID: public boolean gotAccessToElection(int userID, int electionID){ boolean res = false; if (isPublicElection(electionID)){ return true; } PreparedStatement st = null; String query = "SELECT * FROM participate WHERE (user_id = ?) and (election_id=?)"; try { st = con.prepareStatement(query); st.setInt(1, userID); st.setInt(2, electionID); ResultSet rs = st.executeQuery(); res = (rs.next()) ? true : false; } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); res = false; } return res; } //Check if userID is election authority on electionID: public boolean isElectionAuth(int userID, int electionID){ boolean res = false; PreparedStatement st = null; String query = "SELECT * FROM election WHERE (election_id = ?) and (owner_id=?)"; try { st = con.prepareStatement(query); st.setInt(1, electionID); st.setInt(2, userID); ResultSet rs = st.executeQuery(); res = (rs.next()) ? true : false; } catch (SQLException ex) { Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); res = false; } return res; } public Validator getTallierPublicKey(int electionId){ Validator val=new Validator(); PreparedStatement st = null; String query="SELECT public_key FROM election WHERE election_id=?"; try{ st = this.con.prepareStatement(query); st.setInt(1,electionId); ResultSet rs=st.executeQuery(); if(rs.next()){ Blob pubKey = rs.getBlob(1); byte[] pk = pubKey.getBytes(1, (int) pubKey.length()); PublicKey pub = KeyFactory.getInstance("RSA"). generatePublic(new X509EncodedKeySpec(pk)); val.setObject(pub); val.setVerified(true); val.setStatus("Public key retrieved"); } else{ val.setVerified(false); val.setStatus("Public key does not exist for this election"); } } catch(SQLException ex){ Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setVerified(false); val.setStatus("Failed to retrieve public key"); } catch(Exception ex){ Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setVerified(false); val.setStatus("Key in incorrect binary format"); } return val; } public Validator getPrivateKey(int electionId){ Validator val=new Validator(); PreparedStatement st=null; String query="SELECT private_key FROM election WHERE election_id=?"; try{ st=this.con.prepareStatement(query); st.setInt(1,electionId); ResultSet rs=st.executeQuery(); if(rs.next()){ Blob privKey = rs.getBlob(1); byte[] sk = privKey.getBytes(1, (int) privKey.length()); val.setObject(sk); val.setVerified(true); val.setStatus("Private key retrieved"); } else{ val.setVerified(false); val.setStatus("Private key does not exist for this election"); } } catch(SQLException ex){ Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setVerified(false); val.setStatus("Failed to retrieve private key"); } return val; } }
package net.dtkanov.blocks.tests; import static org.junit.Assert.*; import net.dtkanov.blocks.circuit.high_level.derived.ControlUnit; import net.dtkanov.blocks.logic.ConstantNode; import org.junit.Before; import org.junit.Test; public class ControlUnitTest { private ControlUnit cu; private ConstantNode in_op[]; private ConstantNode in_data1[]; private ConstantNode in_data2[]; private ConstantNode clock; public static final int REG_A = 0b111; public static final int REG_B = 0b000; public static final int REG_C = 0b001; public static final int REG_D = 0b010; public static final int REG_E = 0b011; public static final int REG_H = 0b100; public static final int REG_L = 0b101; @Before public void setUp() throws Exception { cu = new ControlUnit(); in_op = new ConstantNode[ControlUnit.BITNESS]; in_data1 = new ConstantNode[ControlUnit.BITNESS]; in_data2 = new ConstantNode[ControlUnit.BITNESS]; for (int i = 0; i < ControlUnit.BITNESS; i++) { in_op[i] = new ConstantNode(false); in_op[i].connectDst(0, cu, i); in_data1[i] = new ConstantNode(false); in_data1[i].connectDst(0, cu, i+ControlUnit.BITNESS); in_data2[i] = new ConstantNode(false); in_data2[i].connectDst(0, cu, i+2*ControlUnit.BITNESS); } clock = new ConstantNode(true); clock.connectDst(0, cu, 3*ControlUnit.BITNESS); } @Test public void MVITest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI B, 01001011b moveToReg(REG_B, 0b01001011); // MVI H, 11111111b moveToReg(REG_H, 0b11111111); } @Test public void MOVTest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI C, 10101010b moveToReg(REG_C, 0b10101010); // MVI E, C setOperationAndPropagete(0b01011001); setValuesAndPropagete(0b11111111, 0); checkReg(REG_E, 0b10101010); } @Test public void ADITest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI A, 11001011b moveToReg(REG_A, 0b11001011); // ADI 00100111b setOperationAndPropagete(0b11000110); setValuesAndPropagete(0b00100111, 0); // 11001011b + 00100111b = 11110010b checkReg(REG_A, 0b11110010); assertTrue(cu.getFlag(ControlUnit.Z_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.S_FLAG)==true); assertTrue(cu.getFlag(ControlUnit.P_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.C_FLAG)==false); } @Test public void ADDTest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI A, 11001011b moveToReg(0b111, 0b11001011); // MVI D, 00101010b moveToReg(0b010, 0b00101010); // ADD D setOperationAndPropagete(0b10000010); setValuesAndPropagete(0, 0); // 11001011b + 00101010b = 11110101b checkReg(REG_A, 0b11110101); assertTrue(cu.getFlag(ControlUnit.Z_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.S_FLAG)==true); assertTrue(cu.getFlag(ControlUnit.P_FLAG)==true); assertTrue(cu.getFlag(ControlUnit.C_FLAG)==false); } @Test public void SUITest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI A, 01001011b moveToReg(0b111, 0b01001011); // SUI 00100111b setOperationAndPropagete(0b11010110); setValuesAndPropagete(0b00100111, 0); // 01001011b - 00100111b = 00100100b checkReg(REG_A, 0b00100100); assertTrue(cu.getFlag(ControlUnit.Z_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.S_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.P_FLAG)==true); assertTrue(cu.getFlag(ControlUnit.C_FLAG)==false); } @Test public void SUBTest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI A, 01001011b moveToReg(0b111, 0b01001011); // MVI D, 00101010b moveToReg(0b010, 0b00101010); // SUB D setOperationAndPropagete(0b10010010); setValuesAndPropagete(0, 0); // 01001011b - 00101010b = 00100001b checkReg(REG_A, 0b00100001); assertTrue(cu.getFlag(ControlUnit.Z_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.S_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.P_FLAG)==true); assertTrue(cu.getFlag(ControlUnit.C_FLAG)==false); } @Test public void ANITest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI A, 01001011b moveToReg(0b111, 0b01001011); // ANI 00100111b setOperationAndPropagete(0b11100110); setValuesAndPropagete(0b00100111, 0); // 01001011b & 00100111b = 00000011b checkReg(REG_A, 0b00000011); assertTrue(cu.getFlag(ControlUnit.Z_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.S_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.P_FLAG)==true); assertTrue(cu.getFlag(ControlUnit.C_FLAG)==false); } @Test public void ANATest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI A, 01001011b moveToReg(0b111, 0b01001011); // MVI C, 00101010b moveToReg(0b001, 0b00101010); // ANA C setOperationAndPropagete(0b10100001); setValuesAndPropagete(0, 0); // 01001011b & 00101010b = 00001010b checkReg(REG_A, 0b00001010); assertTrue(cu.getFlag(ControlUnit.Z_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.S_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.P_FLAG)==true); assertTrue(cu.getFlag(ControlUnit.C_FLAG)==false); } @Test public void ORITest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI A, 01001011b moveToReg(0b111, 0b01001011); // ORI 00100111b setOperationAndPropagete(0b11110110); setValuesAndPropagete(0b00100111, 0); // 01001011b | 00100111b = 01101111b checkReg(REG_A, 0b01101111); assertTrue(cu.getFlag(ControlUnit.Z_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.S_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.P_FLAG)==true); assertTrue(cu.getFlag(ControlUnit.C_FLAG)==false); } @Test public void ORATest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI A, 01001011b moveToReg(0b111, 0b01001011); // MVI L, 00101010b moveToReg(0b101, 0b00101010); // ORA L setOperationAndPropagete(0b10110101); setValuesAndPropagete(0, 0); // 01001011b | 00101010b = 01101011b checkReg(REG_A, 0b01101011); assertTrue(cu.getFlag(ControlUnit.Z_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.S_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.P_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.C_FLAG)==false); } @Test public void XRITest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI A, 01001011b moveToReg(0b111, 0b01001011); // XRI 00100111b setOperationAndPropagete(0b11101110); setValuesAndPropagete(0b00100111, 0); // 01001011b XOR 00100111b = 01101100b checkReg(REG_A, 0b01101100); assertTrue(cu.getFlag(ControlUnit.Z_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.S_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.P_FLAG)==true); assertTrue(cu.getFlag(ControlUnit.C_FLAG)==false); } @Test public void XRATest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI A, 01001011b moveToReg(0b111, 0b01001011); // MVI L, 00101010b moveToReg(0b101, 0b00101010); // XRA L setOperationAndPropagete(0b10101101); setValuesAndPropagete(0, 0); // 01001011b XOR 00101010b = 01100001b checkReg(REG_A, 0b01100001); assertTrue(cu.getFlag(ControlUnit.Z_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.S_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.P_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.C_FLAG)==false); } @Test public void INRTest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI L, 00101001b moveToReg(0b101, 0b00101001); // INR L setOperationAndPropagete(0b00101100); setValuesAndPropagete(0, 0); // INR 00101001b = 00101010b checkReg(REG_L, 0b00101010); assertTrue(cu.getFlag(ControlUnit.Z_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.S_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.P_FLAG)==false); } @Test public void DCRTest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI L, 00101001b moveToReg(0b101, 0b00101001); // DCR L setOperationAndPropagete(0b00101101); setValuesAndPropagete(0, 0); // DCR 00101001b = 00101000b checkReg(REG_L, 0b00101000); assertTrue(cu.getFlag(ControlUnit.Z_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.S_FLAG)==false); assertTrue(cu.getFlag(ControlUnit.P_FLAG)==true); } @Test public void RLCTest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI A, 10101000b moveToReg(0b111, 0b10101000); // RLC setOperationAndPropagete(0b00000111); setValuesAndPropagete(0, 0); // 01010001b checkReg(REG_A, 0b01010001); assertTrue(cu.getFlag(ControlUnit.C_FLAG)==true); } @Test public void RRCTest() { for (int i = 0; i < 2*ControlUnit.BITNESS; i++) { assertTrue(cu.getRegPCValue(i)==false); } // MVI A, 10101000b moveToReg(0b111, 0b10101000); // RRC setOperationAndPropagete(0b00001111); setValuesAndPropagete(0, 0); // 01010100b checkReg(REG_A, 0b01010100); assertTrue(cu.getFlag(ControlUnit.C_FLAG)==false); } protected void moveToReg(int reg_code, int val) { // MVI REG, VAL in_op[0].setValue(false).propagate(); in_op[1].setValue(true).propagate(); in_op[2].setValue(true).propagate(); in_op[3].setValue((reg_code>>0 & 1) == 1).propagate(); in_op[4].setValue((reg_code>>1 & 1) == 1).propagate(); in_op[5].setValue((reg_code>>2 & 1) == 1).propagate(); in_op[6].setValue(false).propagate(); in_op[7].setValue(false).propagate(); setValuesAndPropagete(val, 0); checkReg(reg_code, val); } protected void setOperationAndPropagete(int op) { for (int i = 0; i < 8; i++) { in_op[i].setValue((op & 1<<i) == 1<<i).propagate(); } } protected void setValuesAndPropagete(int val1, int val2) { for (int i = 0; i < 8; i++) { in_data1[i].setValue((val1 & 1<<i) == 1<<i).propagate(); in_data2[i].setValue((val2 & 1<<i) == 1<<i).propagate(); } clock.setValue(true).propagate(); } protected void checkReg(int reg_code, int val) { for (int i = 0; i < 8; i++) { switch (reg_code) { case 7: assertTrue(cu.getRegAValue(i)==((val & 1<<i) == 1<<i)); break; case 0: assertTrue(cu.getRegBValue(i)==((val & 1<<i) == 1<<i)); break; case 1: assertTrue(cu.getRegCValue(i)==((val & 1<<i) == 1<<i)); break; case 2: assertTrue(cu.getRegDValue(i)==((val & 1<<i) == 1<<i)); break; case 3: assertTrue(cu.getRegEValue(i)==((val & 1<<i) == 1<<i)); break; case 4: assertTrue(cu.getRegHValue(i)==((val & 1<<i) == 1<<i)); break; case 5: assertTrue(cu.getRegLValue(i)==((val & 1<<i) == 1<<i)); break; default: assertTrue(false); break; } } } protected void printRegisters() { System.out.print("[A:"); for (int i = 7; i >= 0; i System.out.print(cu.getRegAValue(i)?"1":"0"); System.out.print("]"); System.out.print("[B:"); for (int i = 7; i >= 0; i System.out.print(cu.getRegBValue(i)?"1":"0"); System.out.print("]"); System.out.print("[C:"); for (int i = 7; i >= 0; i System.out.print(cu.getRegCValue(i)?"1":"0"); System.out.print("]"); System.out.print("[D:"); for (int i = 7; i >= 0; i System.out.print(cu.getRegDValue(i)?"1":"0"); System.out.print("]"); System.out.print("[E:"); for (int i = 7; i >= 0; i System.out.print(cu.getRegEValue(i)?"1":"0"); System.out.print("]"); System.out.print("[H:"); for (int i = 7; i >= 0; i System.out.print(cu.getRegHValue(i)?"1":"0"); System.out.print("]"); System.out.print("[L:"); for (int i = 7; i >= 0; i System.out.print(cu.getRegLValue(i)?"1":"0"); System.out.print("]"); System.out.print("[F:"); for (int i = 7; i >= 0; i System.out.print(cu.getFlag(i)?"1":"0"); System.out.print("]"); System.out.println(); } }
package echowand.sample; import echowand.common.Data; import echowand.common.EOJ; import echowand.common.EPC; import echowand.common.ESV; import echowand.net.*; import echowand.util.LoggerConfig; import java.net.Inet4Address; import java.net.UnknownHostException; import java.util.HashMap; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Yoshiki Makino */ public class TCPSample0 { public static final String peerAddress = "192.168.1.1"; /* * * Get */ public static CommonFrame createCommonFrameGet() { CommonFrame commonFrame = new CommonFrame(new EOJ("013001"), new EOJ("0ef001"), ESV.Get); commonFrame.setTID((short)1); StandardPayload payload = (StandardPayload) commonFrame.getEDATA(); payload.addFirstProperty(new Property(EPC.x80)); payload.addFirstProperty(new Property(EPC.x88)); payload.addFirstProperty(new Property(EPC.x9F)); payload.addFirstProperty(new Property(EPC.x9E)); payload.addFirstProperty(new Property(EPC.x9D)); payload.addFirstProperty(new Property(EPC.xD5)); payload.addFirstProperty(new Property(EPC.xD6)); payload.addFirstProperty(new Property(EPC.xD7)); return commonFrame; } /* * * SetGet */ public static CommonFrame createCommonFrameSetGet() { CommonFrame commonFrame = new CommonFrame(new EOJ("013001"), new EOJ("013001"), ESV.SetGet); commonFrame.setTID((short)2); StandardPayload payload = (StandardPayload) commonFrame.getEDATA(); payload.addFirstProperty(new Property(EPC.xB0, new Data((byte)0x12))); payload.addSecondProperty(new Property(EPC.x80)); payload.addSecondProperty(new Property(EPC.x9F)); payload.addSecondProperty(new Property(EPC.x9E)); payload.addSecondProperty(new Property(EPC.x9D)); return commonFrame; } public static CommonFrame createCommonFrameINFC() { CommonFrame commonFrame = new CommonFrame(new EOJ("013001"), new EOJ("0ef001"), ESV.INFC); commonFrame.setTID((short)3); StandardPayload payload = (StandardPayload) commonFrame.getEDATA(); payload.addFirstProperty(new Property(EPC.x80, new Data((byte)0x31))); return commonFrame; } /* * timeout */ public static void setTimeout(final int timeout) { Thread t = new Thread() { @Override public void run() { try { Thread.sleep(timeout); } catch (InterruptedException e) { e.printStackTrace(); } finally { System.exit(1); } } }; t.setDaemon(true); t.start(); } public static void main(String[] args) { //LoggerConfig.changeLogLevelAll(TCPConnectionPool.class.getName()); //LoggerConfig.changeLogLevelAll(TCPConnection.class.getName()); //LoggerConfig.changeLogLevelAll(TCPNetwork.class.getName()); //LoggerConfig.changeLogLevelAll(TCPReceiveTask.class.getName()); // setTimeout(3000); try { // ECHONET LiteIP Inet4Subnet subnet = new Inet4Subnet(); subnet.startService(); // Node Node remoteNode1 = subnet.getRemoteNode(Inet4Address.getByName(peerAddress)); // Get Frame frame1 = new Frame(subnet.getLocalNode(), remoteNode1, createCommonFrameGet()); subnet.createTCPConnection(frame1); System.out.println("Sending: " + frame1); subnet.send(frame1); System.out.println("Received: " + subnet.receive()); System.out.println(); // Node Node remoteNode2 = subnet.getRemoteNode(Inet4Address.getByName(peerAddress)); // SetGet Frame frame2 = new Frame(subnet.getLocalNode(), remoteNode2, createCommonFrameSetGet()); //subnet.createTCPConnection(frame2); System.out.println("Sending: " + frame2); subnet.send(frame2); Frame rframe2 = subnet.receive(); System.out.println("Received: " + rframe2); System.out.println(); //subnet.deleteTCPConnection(rframe2); // INFC Frame frame3 = new Frame(subnet.getLocalNode(), subnet.getGroupNode(), createCommonFrameINFC()); System.out.println("Sending: " + frame3); subnet.send(frame3); for (;;) { System.out.println("Received: " + subnet.receive()); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (SubnetException e) { e.printStackTrace(); } } }
package org.commonmark.internal; import org.commonmark.internal.util.Escaping; import org.commonmark.internal.util.Html5Entities; import org.commonmark.node.*; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class InlineParser { // Constants for character codes: private static final char C_NEWLINE = '\n'; private static final char C_ASTERISK = '*'; private static final char C_UNDERSCORE = '_'; private static final char C_BACKTICK = '`'; private static final char C_OPEN_BRACKET = '['; private static final char C_CLOSE_BRACKET = ']'; private static final char C_LESSTHAN = '<'; private static final char C_BANG = '!'; private static final char C_BACKSLASH = '\\'; private static final char C_AMPERSAND = '&'; private static final char C_OPEN_PAREN = '('; private static final char C_CLOSE_PAREN = ')'; private static final char C_COLON = ':'; private static final String ESCAPED_CHAR = "\\\\" + Escaping.ESCAPABLE; private static final String REG_CHAR = "[^\\\\()\\x00-\\x20]"; private static final String IN_PARENS_NOSP = "\\((" + REG_CHAR + '|' + ESCAPED_CHAR + ")*\\)"; private static final String TAGNAME = "[A-Za-z][A-Za-z0-9]*"; private static final String ATTRIBUTENAME = "[a-zA-Z_:][a-zA-Z0-9:._-]*"; private static final String UNQUOTEDVALUE = "[^\"'=<>`\\x00-\\x20]+"; private static final String SINGLEQUOTEDVALUE = "'[^']*'"; private static final String DOUBLEQUOTEDVALUE = "\"[^\"]*\""; private static final String ATTRIBUTEVALUE = "(?:" + UNQUOTEDVALUE + "|" + SINGLEQUOTEDVALUE + "|" + DOUBLEQUOTEDVALUE + ")"; private static final String ATTRIBUTEVALUESPEC = "(?:" + "\\s*=" + "\\s*" + ATTRIBUTEVALUE + ")"; private static final String ATTRIBUTE = "(?:" + "\\s+" + ATTRIBUTENAME + ATTRIBUTEVALUESPEC + "?)"; private static final String OPENTAG = "<" + TAGNAME + ATTRIBUTE + "*" + "\\s*/?>"; private static final String CLOSETAG = "</" + TAGNAME + "\\s*[>]"; private static final String HTMLCOMMENT = "|"; private static final String PROCESSINGINSTRUCTION = "[<][?].*?[?][>]"; private static final String DECLARATION = "<![A-Z]+" + "\\s+[^>]*>"; private static final String CDATA = "<!\\[CDATA\\[[\\s\\S]*?\\]\\]>"; private static final String HTMLTAG = "(?:" + OPENTAG + "|" + CLOSETAG + "|" + HTMLCOMMENT + "|" + PROCESSINGINSTRUCTION + "|" + DECLARATION + "|" + CDATA + ")"; private static final String ENTITY = "&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});"; private static final Pattern rePunctuation = Pattern .compile("^[\u2000-\u206F\u2E00-\u2E7F\\\\'!\" private static final Pattern reHtmlTag = Pattern.compile('^' + HTMLTAG, Pattern.CASE_INSENSITIVE); private static final Pattern reLinkTitle = Pattern.compile( "^(?:\"(" + ESCAPED_CHAR + "|[^\"\\x00])*\"" + '|' + "'(" + ESCAPED_CHAR + "|[^'\\x00])*'" + '|' + "\\((" + ESCAPED_CHAR + "|[^)\\x00])*\\))"); private static final Pattern reLinkDestinationBraces = Pattern.compile( "^(?:[<](?:[^<>\\n\\\\\\x00]" + '|' + ESCAPED_CHAR + '|' + "\\\\)*[>])"); private static final Pattern reLinkDestination = Pattern.compile( "^(?:" + REG_CHAR + "+|" + ESCAPED_CHAR + '|' + IN_PARENS_NOSP + ")*"); private static final Pattern reEscapable = Pattern.compile(Escaping.ESCAPABLE); private static final Pattern reEntityHere = Pattern.compile('^' + ENTITY, Pattern.CASE_INSENSITIVE); private static final Pattern reTicks = Pattern.compile("`+"); private static final Pattern reTicksHere = Pattern.compile("^`+"); private static final Pattern reEmailAutolink = Pattern .compile("^<([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>"); private static final Pattern reAutolink = Pattern .compile("^<(?:coap|doi|javascript|aaa|aaas|about|acap|cap|cid|crid|data|dav|dict|dns|file|ftp|geo|go|gopher|h323|http|https|iax|icap|im|imap|info|ipp|iris|iris.beep|iris.xpc|iris.xpcs|iris.lwz|ldap|mailto|mid|msrp|msrps|mtqp|mupdate|news|nfs|ni|nih|nntp|opaquelocktoken|pop|pres|rtsp|service|session|shttp|sieve|sip|sips|sms|snmp|soap.beep|soap.beeps|tag|tel|telnet|tftp|thismessage|tn3270|tip|tv|urn|vemmi|ws|wss|xcon|xcon-userid|xmlrpc.beep|xmlrpc.beeps|xmpp|z39.50r|z39.50s|adiumxtra|afp|afs|aim|apt|attachment|aw|beshare|bitcoin|bolo|callto|chrome|chrome-extension|com-eventbrite-attendee|content|cvs|dlna-playsingle|dlna-playcontainer|dtn|dvb|ed2k|facetime|feed|finger|fish|gg|git|gizmoproject|gtalk|hcp|icon|ipn|irc|irc6|ircs|itms|jar|jms|keyparc|lastfm|ldaps|magnet|maps|market|message|mms|ms-help|msnim|mumble|mvn|notes|oid|palm|paparazzi|platform|proxy|psyc|query|res|resource|rmi|rsync|rtmp|secondlife|sftp|sgn|skype|smb|soldat|spotify|ssh|steam|svn|teamspeak|things|udp|unreal|ut2004|ventrilo|view-source|webcal|wtai|wyciwyg|xfire|xri|ymsgr):[^<>\u0000-\u0020]*>", Pattern.CASE_INSENSITIVE); private static final Pattern reSpnl = Pattern.compile("^ *(?:\n *)?"); private static final Pattern reWhitespaceChar = Pattern.compile("^\\p{IsWhite_Space}"); private static final Pattern reWhitespace = Pattern.compile("\\s+"); private static final Pattern reFinalSpace = Pattern.compile(" *$"); private static final Pattern reLineEnd = Pattern.compile("^ *(?:\n|$)"); private static final Pattern reInitialSpace = Pattern.compile("^ *"); private static final Pattern reLinkLabel = Pattern .compile("^\\[(?:[^\\\\\\[\\]]|\\\\[\\[\\]]){0,1000}\\]"); // Matches a string of non-special characters. private static final Pattern reMain = Pattern.compile("^[^\n`\\[\\]\\\\!<&*_]+"); private String subject = ""; /** * Stack of delimiters (emphasis, strong emphasis). */ private Delimiter delimiter; private int pos = 0; private Map<String, Link> referenceMap = new HashMap<>(); /** * Parse content in block into inline children, using referenceMap to resolve referenceMap. */ public void parse(Node block, String content) { this.subject = content.trim(); this.pos = 0; this.delimiter = null; boolean moreToParse; do { moreToParse = parseInline(block); } while (moreToParse); processEmphasis(null); } // If re matches at current position in the subject, advance // position in subject and return the match; otherwise return null. private String match(Pattern re) { if (this.pos >= this.subject.length()) { return null; } Matcher matcher = re.matcher(this.subject.substring(this.pos)); boolean m = matcher.find(); if (m) { this.pos += matcher.end(); return matcher.group(); } else { return null; } } /** * Returns the char at the current subject position, or {@code '\0'} in case there are no more characters. */ private char peek() { if (this.pos < this.subject.length()) { return this.subject.charAt(this.pos); } else { return '\0'; } } // Parse zero or more space characters, including at most one newline boolean spnl() { this.match(reSpnl); return true; } // Parse a backslash-escaped special character, adding either the escaped // character, a hard line break (if the backslash is followed by a newline), // or a literal backslash to the block's children. boolean parseBackslash(Node block) { String subj = this.subject; int pos = this.pos; Node node; if (subj.charAt(pos) == C_BACKSLASH) { int next = pos + 1; if (next < subj.length() && subj.charAt(next) == '\n') { this.pos = this.pos + 2; node = new HardLineBreak(); block.appendChild(node); } else if (next < subj.length() && reEscapable.matcher(subj.substring(next, next + 1)).matches()) { this.pos = this.pos + 2; block.appendChild(text(subj.substring(next, next + 1))); } else { this.pos++; block.appendChild(text("\\")); } return true; } else { return false; } } // Attempt to parse an autolink (URL or email in pointy brackets). boolean parseAutolink(Node block) { String m; String dest; if ((m = this.match(reEmailAutolink)) != null) { dest = m.substring(1, m.length() - 1); Link node = new Link(Escaping.normalizeURI("mailto:" + dest), null); node.appendChild(text(dest)); block.appendChild(node); return true; } else if ((m = this.match(reAutolink)) != null) { dest = m.substring(1, m.length() - 1); Link node = new Link(Escaping.normalizeURI(dest), null); node.appendChild(text(dest)); block.appendChild(node); return true; } else { return false; } } // Attempt to parse a raw HTML tag. boolean parseHtmlTag(Node block) { String m = this.match(reHtmlTag); if (m != null) { HtmlTag node = new HtmlTag(); node.setLiteral(m); block.appendChild(node); return true; } else { return false; } } // Scan a sequence of characters with code delimiterChar, and return information about // the number of delimiters and whether they are positioned such that // they can open and/or close emphasis or strong emphasis. A utility // function for strong/emph parsing. DelimiterRun scanDelims(char delimiterChar) { int startPos = this.pos; String charBefore = this.pos == 0 ? "\n" : this.subject.substring(this.pos - 1, this.pos); int numDelims = 0; while (this.peek() == delimiterChar) { numDelims++; this.pos++; } char ccAfter = this.peek(); String charAfter; if (ccAfter == '\0') { charAfter = "\n"; } else { charAfter = String.valueOf(ccAfter); } boolean leftFlanking = numDelims > 0 && !(reWhitespaceChar.matcher(charAfter).matches()) && !(rePunctuation.matcher(charAfter).matches() && !(reWhitespaceChar.matcher(charBefore).matches()) && !(rePunctuation.matcher(charBefore).matches())); boolean rightFlanking = numDelims > 0 && !(reWhitespaceChar.matcher(charBefore).matches()) && !(rePunctuation.matcher(charBefore).matches() && !(reWhitespaceChar.matcher(charAfter).matches()) && !(rePunctuation.matcher(charAfter).matches())); boolean canOpen; boolean canClose; if (delimiterChar == C_UNDERSCORE) { canOpen = leftFlanking && !rightFlanking; canClose = rightFlanking && !leftFlanking; } else { canOpen = leftFlanking; canClose = rightFlanking; } this.pos = startPos; return new DelimiterRun(numDelims, canOpen, canClose); } // Attempt to parse emphasis or strong emphasis. boolean parseEmphasis(char delimiterChar, Node block) { DelimiterRun res = this.scanDelims(delimiterChar); int numDelims = res.numDelims; int startPos = this.pos; if (numDelims == 0) { return false; } this.pos += numDelims; Text node = text(this.subject.substring(startPos, this.pos)); block.appendChild(node); // Add entry to stack for this opener this.delimiter = new Delimiter(node, this.delimiter, startPos); this.delimiter.delimiterChar = delimiterChar; this.delimiter.numDelims = numDelims; this.delimiter.canOpen = res.canOpen; this.delimiter.canClose = res.canClose; this.delimiter.active = true; if (this.delimiter.previous != null) { this.delimiter.previous.next = this.delimiter; } return true; } void removeDelimiter(Delimiter delim) { if (delim.previous != null) { delim.previous.next = delim.next; } if (delim.next == null) { // top of stack this.delimiter = delim.previous; } else { delim.next.previous = delim.previous; } } void processEmphasis(Delimiter stackBottom) { Delimiter opener, closer; Delimiter nextstack, tempstack; int useDelims; Node tmp, next; // find first closer above stackBottom: closer = this.delimiter; while (closer != null && closer.previous != stackBottom) { closer = closer.previous; } // move forward, looking for closers, and handling each while (closer != null) { if (closer.canClose && (closer.delimiterChar == C_UNDERSCORE || closer.delimiterChar == C_ASTERISK)) { // found emphasis closer. now look back for first matching opener: opener = closer.previous; while (opener != null && opener != stackBottom) { if (opener.delimiterChar == closer.delimiterChar && opener.canOpen) { break; } opener = opener.previous; } if (opener != null && opener != stackBottom) { // calculate actual number of delimiters used from this closer if (closer.numDelims < 3 || opener.numDelims < 3) { useDelims = closer.numDelims <= opener.numDelims ? closer.numDelims : opener.numDelims; } else { useDelims = closer.numDelims % 2 == 0 ? 2 : 1; } Text openerInl = opener.node; Text closerInl = closer.node; // remove used delimiters from stack elts and inlines opener.numDelims -= useDelims; closer.numDelims -= useDelims; openerInl.setLiteral( openerInl.getLiteral().substring(0, openerInl.getLiteral().length() - useDelims)); closerInl.setLiteral( closerInl.getLiteral().substring(0, closerInl.getLiteral().length() - useDelims)); // build contents for new emph element Node emph = useDelims == 1 ? new Emphasis() : new StrongEmphasis(); tmp = openerInl.getNext(); while (tmp != null && tmp != closerInl) { next = tmp.getNext(); emph.appendChild(tmp); tmp = next; } openerInl.insertAfter(emph); // remove elts btw opener and closer in delimiters stack tempstack = closer.previous; while (tempstack != null && tempstack != opener) { nextstack = tempstack.previous; this.removeDelimiter(tempstack); tempstack = nextstack; } // if opener has 0 delims, remove it and the inline if (opener.numDelims == 0) { openerInl.unlink(); this.removeDelimiter(opener); } if (closer.numDelims == 0) { closerInl.unlink(); tempstack = closer.next; this.removeDelimiter(closer); closer = tempstack; } } else { closer = closer.next; } } else { closer = closer.next; } } // remove all delimiters while (this.delimiter != stackBottom) { this.removeDelimiter(this.delimiter); } } // Attempt to parse link title (sans quotes), returning the string // or null if no match. String parseLinkTitle() { String title = this.match(reLinkTitle); if (title != null) { // chop off quotes from title and unescape: return Escaping.unescapeString(title.substring(1, title.length() - 1)); } else { return null; } } // Attempt to parse link destination, returning the string or // null if no match. String parseLinkDestination() { String res = this.match(reLinkDestinationBraces); if (res != null) { // chop off surrounding <..>: if (res.length() == 2) { return ""; } else { return Escaping.normalizeURI(Escaping.unescapeString(res.substring(1, res.length() - 1))); } } else { res = this.match(reLinkDestination); if (res != null) { return Escaping.normalizeURI(Escaping.unescapeString(res)); } else { return null; } } } // Attempt to parse a link label, returning number of characters parsed. int parseLinkLabel() { String m = this.match(reLinkLabel); return m == null ? 0 : m.length(); } // Add open bracket to delimiter stack and add a text node to block's children. boolean parseOpenBracket(Node block) { int startpos = this.pos; this.pos += 1; Text node = text("["); block.appendChild(node); // Add entry to stack for this opener this.delimiter = new Delimiter(node, this.delimiter, startpos); this.delimiter.delimiterChar = C_OPEN_BRACKET; this.delimiter.numDelims = 1; this.delimiter.canOpen = true; this.delimiter.canClose = false; this.delimiter.active = true; if (this.delimiter.previous != null) { this.delimiter.previous.next = this.delimiter; } return true; } // IF next character is [, and ! delimiter to delimiter stack and // add a text node to block's children. Otherwise just add a text node. boolean parseBang(Node block) { int startpos = this.pos; this.pos += 1; if (this.peek() == C_OPEN_BRACKET) { this.pos += 1; Text node = text("!["); block.appendChild(node); // Add entry to stack for this opener this.delimiter = new Delimiter(node, this.delimiter, startpos + 1); this.delimiter.delimiterChar = C_BANG; this.delimiter.numDelims = 1; this.delimiter.canOpen = true; this.delimiter.canClose = false; this.delimiter.active = true; if (this.delimiter.previous != null) { this.delimiter.previous.next = this.delimiter; } } else { block.appendChild(text("!")); } return true; } // Try to match close bracket against an opening in the delimiter // stack. Add either a link or image, or a plain [ character, // to block's children. If there is a matching delimiter, // remove it from the delimiter stack. boolean parseCloseBracket(Node block) { int startpos; boolean is_image; String dest = null; String title = null; boolean matched = false; String reflabel; Delimiter opener; this.pos += 1; startpos = this.pos; // look through stack of delimiters for a [ or ![ opener = this.delimiter; while (opener != null) { if (opener.delimiterChar == C_OPEN_BRACKET || opener.delimiterChar == C_BANG) { break; } opener = opener.previous; } if (opener == null) { // no matched opener, just return a literal block.appendChild(text("]")); return true; } if (!opener.active) { // no matched opener, just return a literal block.appendChild(text("]")); // take opener off emphasis stack this.removeDelimiter(opener); return true; } // If we got here, open is a potential opener is_image = opener.delimiterChar == C_BANG; // Check to see if we have a link/image // Inline link? if (this.peek() == C_OPEN_PAREN) { this.pos++; this.spnl(); if ((dest = this.parseLinkDestination()) != null) { this.spnl(); // title needs a whitespace before if (reWhitespaceChar.matcher(this.subject.substring(this.pos - 1, this.pos)).matches()) { title = this.parseLinkTitle(); this.spnl(); } if (this.subject.charAt(this.pos) == C_CLOSE_PAREN) { this.pos += 1; matched = true; } } } else { // Next, see if there's a link label int savepos = this.pos; this.spnl(); int beforelabel = this.pos; int n = this.parseLinkLabel(); if (n == 0 || n == 2) { // empty or missing second label reflabel = this.subject.substring(opener.index, startpos); } else { reflabel = this.subject.substring(beforelabel, beforelabel + n); } if (n == 0) { // If shortcut reference link, rewind before spaces we skipped. this.pos = savepos; } // lookup rawlabel in refmap Link link = referenceMap.get(Escaping.normalizeReference(reflabel)); if (link != null) { dest = link.getDestination(); title = link.getTitle(); matched = true; } } if (matched) { Node node = is_image ? new Image(dest, title) : new Link(dest, title); Node tmp, next; tmp = opener.node.getNext(); while (tmp != null) { next = tmp.getNext(); node.appendChild(tmp); tmp = next; } block.appendChild(node); this.processEmphasis(opener.previous); opener.node.unlink(); // processEmphasis will remove this and later delimiters. // Now, for a link, we also deactivate earlier link openers. // (no links in links) if (!is_image) { opener = this.delimiter; while (opener != null) { if (opener.delimiterChar == C_OPEN_BRACKET) { opener.active = false; // deactivate this opener } opener = opener.previous; } } return true; } else { // no match this.removeDelimiter(opener); // remove this opener from stack this.pos = startpos; block.appendChild(text("]")); return true; } } // Attempt to parse an entity, return Entity object if successful. boolean parseEntity(Node block) { String m; if ((m = this.match(reEntityHere)) != null) { block.appendChild(text(Html5Entities.entityToString(m))); return true; } else { return false; } } // Parse a run of ordinary characters, or a single character with // a special meaning in markdown, as a plain string. boolean parseString(Node block) { String m; if ((m = this.match(reMain)) != null) { block.appendChild(text(m)); return true; } else { return false; } } // Parse a newline. If it was preceded by two spaces, return a hard // line break; otherwise a soft line break. boolean parseNewline(Node block) { this.pos += 1; // assume we're at a \n // check previous node for trailing spaces Node lastChild = block.getLastChild(); if (lastChild != null && lastChild instanceof Text) { Text text = (Text) lastChild; Matcher matcher = reFinalSpace.matcher(text.getLiteral()); int sps = matcher.find() ? matcher.end() - matcher.start() : 0; if (sps > 0) { text.setLiteral(matcher.replaceAll("")); } block.appendChild(sps >= 2 ? new HardLineBreak() : new SoftLineBreak()); } else { block.appendChild(new SoftLineBreak()); } this.match(reInitialSpace); // gobble leading spaces in next line return true; } // Attempt to parse a link reference, modifying refmap. int parseReference(String s) { this.subject = s; this.pos = 0; String rawlabel; String dest; String title; int matchChars; int startpos = this.pos; // label: matchChars = this.parseLinkLabel(); if (matchChars == 0) { return 0; } else { rawlabel = this.subject.substring(0, matchChars); } // colon: if (this.peek() == C_COLON) { this.pos++; } else { this.pos = startpos; return 0; } // link url this.spnl(); dest = this.parseLinkDestination(); if (dest == null || dest.length() == 0) { this.pos = startpos; return 0; } int beforetitle = this.pos; this.spnl(); title = this.parseLinkTitle(); if (title == null) { // rewind before spaces this.pos = beforetitle; } // make sure we're at line end: if (this.pos != this.subject.length() && this.match(reLineEnd) == null) { this.pos = startpos; return 0; } String normlabel = Escaping.normalizeReference(rawlabel); if (!referenceMap.containsKey(normlabel)) { Link link = new Link(dest, title); referenceMap.put(normlabel, link); } return this.pos - startpos; } private static Text text(String s) { Text node = new Text(); node.setLiteral(s); return node; } // Attempt to parse backticks, adding either a backtick code span or a // literal sequence of backticks. private boolean parseBackticks(Node block) { String ticks = this.match(reTicksHere); if (ticks == null) { return false; } int afterOpenTicks = this.pos; String matched; while ((matched = this.match(reTicks)) != null) { if (matched.equals(ticks)) { Code node = new Code(); String content = this.subject.substring(afterOpenTicks, this.pos - ticks.length()); String literal = reWhitespace.matcher(content.trim()).replaceAll(" "); node.setLiteral(literal); block.appendChild(node); return true; } } // If we got here, we didn't match a closing backtick sequence. this.pos = afterOpenTicks; block.appendChild(text(ticks)); return true; } // Parse the next inline element in subject, advancing subject position. // On success, add the result to block's children and return true. // On failure, return false. private boolean parseInline(Node block) { boolean res; char c = this.peek(); if (c == '\0') { return false; } switch (c) { case C_NEWLINE: res = this.parseNewline(block); break; case C_BACKSLASH: res = this.parseBackslash(block); break; case C_BACKTICK: res = this.parseBackticks(block); break; case C_ASTERISK: case C_UNDERSCORE: res = this.parseEmphasis(c, block); break; case C_OPEN_BRACKET: res = this.parseOpenBracket(block); break; case C_BANG: res = this.parseBang(block); break; case C_CLOSE_BRACKET: res = this.parseCloseBracket(block); break; case C_LESSTHAN: res = this.parseAutolink(block) || this.parseHtmlTag(block); break; case C_AMPERSAND: res = this.parseEntity(block); break; default: res = this.parseString(block); break; } if (!res) { this.pos += 1; Text text = new Text(); // When we get here, it's only for a single special character that turned out to not have a special meaning. // So we shouldn't have a single surrogate here, hence it should be ok to turn it into a String. text.setLiteral(String.valueOf(c)); block.appendChild(text); } return true; } }
package org.concord.energy3d.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.HierarchyBoundsAdapter; import java.awt.event.HierarchyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.concurrent.CancellationException; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerDateModel; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.concord.energy3d.model.Door; import org.concord.energy3d.model.Floor; import org.concord.energy3d.model.Foundation; import org.concord.energy3d.model.HousePart; import org.concord.energy3d.model.Roof; import org.concord.energy3d.model.Sensor; import org.concord.energy3d.model.SolarPanel; import org.concord.energy3d.model.Tree; import org.concord.energy3d.scene.Scene; import org.concord.energy3d.scene.SceneManager; import org.concord.energy3d.shapes.Heliodon; import org.concord.energy3d.simulation.CityData; import org.concord.energy3d.simulation.Cost; import org.concord.energy3d.simulation.HeatLoad; import org.concord.energy3d.simulation.SolarIrradiation; import org.concord.energy3d.util.Util; import com.ardor3d.math.ColorRGBA; import com.ardor3d.math.type.ReadOnlyColorRGBA; import com.ardor3d.math.type.ReadOnlyVector3; public class EnergyPanel extends JPanel { public static final ReadOnlyColorRGBA[] solarColors = { ColorRGBA.BLUE, ColorRGBA.GREEN, ColorRGBA.YELLOW, ColorRGBA.RED }; private static final long serialVersionUID = 1L; private static final EnergyPanel instance = new EnergyPanel(); private final DecimalFormat twoDecimals = new DecimalFormat(); private final DecimalFormat noDecimals = new DecimalFormat(); private static boolean keepHeatmapOn = false; public enum UpdateRadiation { ALWAYS, ONLY_IF_SLECTED_IN_GUI }; private final JComboBox<String> wallsComboBox; private final JComboBox<String> doorsComboBox; private final JComboBox<String> windowsComboBox; private final JComboBox<String> roofsComboBox; private final JComboBox<String> cityComboBox; private final JComboBox<String> solarPanelEfficiencyComboBox; private final JComboBox<String> windowSHGCComboBox; private final JTextField heatingTextField; private final JTextField coolingTextField; private final JTextField netEnergyTextField; private final JSpinner insideTemperatureSpinner; private final JSpinner outsideTemperatureSpinner; private final JLabel dateLabel; private final JLabel timeLabel; private final JSpinner dateSpinner; private final JSpinner timeSpinner; private final JLabel latitudeLabel; private final JSpinner latitudeSpinner; private final JPanel heatMapPanel; private final JSlider colorMapSlider; private final JProgressBar progressBar; private final ColorBar costBar; private final JPanel costPanel; private Thread thread; private boolean computeRequest; private boolean disableActions = false; private boolean alreadyRenderedHeatmap = false; private UpdateRadiation updateRadiation; private boolean computeEnabled = true; private final List<PropertyChangeListener> propertyChangeListeners = Collections.synchronizedList(new ArrayList<PropertyChangeListener>()); private JPanel partPanel; private JPanel buildingPanel; private JPanel geometryPanel; private JLabel lblPosition; private JTextField positionTextField; private JLabel lblArea; private JTextField areaTextField; private JLabel lblHeight; private JTextField heightTextField; private JLabel lblVolume; private JTextField volumnTextField; private JTextField windowTextField; private JTextField solarPanelTextField; private JPanel partPropertiesPanel; private JLabel partProperty1Label; private JLabel partProperty2Label; private JLabel partProperty3Label; private JLabel partProperty4Label; private JTextField partProperty1TextField; private JTextField partProperty2TextField; private JTextField partProperty3TextField; private JTextField partProperty4TextField; public static EnergyPanel getInstance() { return instance; } private EnergyPanel() { twoDecimals.setMaximumFractionDigits(2); noDecimals.setMaximumFractionDigits(0); setLayout(new BorderLayout()); final JPanel dataPanel = new JPanel(); dataPanel.setLayout(new BoxLayout(dataPanel, BoxLayout.Y_AXIS)); add(new JScrollPane(dataPanel), BorderLayout.CENTER); final JPanel timeAndLocationPanel = new JPanel(); timeAndLocationPanel.setToolTipText("<html>The outside temperature and the sun path<br>differ from time to time and from location to location.</html>"); timeAndLocationPanel.setBorder(new TitledBorder(null, "Time & Location", TitledBorder.LEADING, TitledBorder.TOP)); dataPanel.add(timeAndLocationPanel); final GridBagLayout gbl_panel_3 = new GridBagLayout(); timeAndLocationPanel.setLayout(gbl_panel_3); dateLabel = new JLabel("Date: "); final GridBagConstraints gbc_dateLabel = new GridBagConstraints(); gbc_dateLabel.gridx = 0; gbc_dateLabel.gridy = 0; timeAndLocationPanel.add(dateLabel, gbc_dateLabel); dateSpinner = new JSpinner(); dateSpinner.setModel(new SpinnerDateModel(new Date(1380427200000L), null, null, Calendar.MONTH)); dateSpinner.setEditor(new JSpinner.DateEditor(dateSpinner, "MMMM dd")); dateSpinner.addHierarchyBoundsListener(new HierarchyBoundsAdapter() { @Override public void ancestorResized(final HierarchyEvent e) { dateSpinner.setMinimumSize(dateSpinner.getPreferredSize()); dateSpinner.setPreferredSize(dateSpinner.getPreferredSize()); dateSpinner.removeHierarchyBoundsListener(this); } }); dateSpinner.addChangeListener(new ChangeListener() { boolean firstCall = true; @Override public void stateChanged(final ChangeEvent e) { if (firstCall) { firstCall = false; return; } if (disableActions) return; final Heliodon heliodon = Heliodon.getInstance(); if (heliodon != null) heliodon.setDate((Date) dateSpinner.getValue()); compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); Scene.getInstance().setEdited(true); Scene.getInstance().redrawAllNow(); // XIE: 4/11: This needs to be called for trees to have the right seasonal texture } }); final GridBagConstraints gbc_dateSpinner = new GridBagConstraints(); gbc_dateSpinner.insets = new Insets(0, 0, 1, 1); gbc_dateSpinner.gridx = 1; gbc_dateSpinner.gridy = 0; timeAndLocationPanel.add(dateSpinner, gbc_dateSpinner); cityComboBox = new JComboBox<String>(); cityComboBox.setModel(new DefaultComboBoxModel<String>(CityData.getInstance().getCities())); cityComboBox.setSelectedItem("Boston"); cityComboBox.setMaximumRowCount(15); cityComboBox.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent e) { if (cityComboBox.getSelectedItem().equals("")) compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); else { final Integer newLatitude = CityData.getInstance().getCityLatitutes().get(cityComboBox.getSelectedItem()); if (newLatitude.equals(latitudeSpinner.getValue())) compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); else latitudeSpinner.setValue(newLatitude); } Scene.getInstance().setEdited(true); } }); final GridBagConstraints gbc_cityComboBox = new GridBagConstraints(); gbc_cityComboBox.gridwidth = 2; gbc_cityComboBox.fill = GridBagConstraints.HORIZONTAL; gbc_cityComboBox.gridx = 2; gbc_cityComboBox.gridy = 0; timeAndLocationPanel.add(cityComboBox, gbc_cityComboBox); timeLabel = new JLabel("Time: "); final GridBagConstraints gbc_timeLabel = new GridBagConstraints(); gbc_timeLabel.gridx = 0; gbc_timeLabel.gridy = 1; timeAndLocationPanel.add(timeLabel, gbc_timeLabel); timeSpinner = new JSpinner(new SpinnerDateModel()); timeSpinner.setEditor(new JSpinner.DateEditor(timeSpinner, "H:mm")); timeSpinner.addChangeListener(new ChangeListener() { private boolean firstCall = true; @Override public void stateChanged(final ChangeEvent e) { // ignore the first event if (firstCall) { firstCall = false; return; } final Heliodon heliodon = Heliodon.getInstance(); if (heliodon != null) heliodon.setTime((Date) timeSpinner.getValue()); updateOutsideTemperature(); Scene.getInstance().setEdited(true); SceneManager.getInstance().changeSkyTexture(); } }); final GridBagConstraints gbc_timeSpinner = new GridBagConstraints(); gbc_timeSpinner.insets = new Insets(0, 0, 0, 1); gbc_timeSpinner.fill = GridBagConstraints.HORIZONTAL; gbc_timeSpinner.gridx = 1; gbc_timeSpinner.gridy = 1; timeAndLocationPanel.add(timeSpinner, gbc_timeSpinner); latitudeLabel = new JLabel("Latitude: "); final GridBagConstraints gbc_altitudeLabel = new GridBagConstraints(); gbc_altitudeLabel.insets = new Insets(0, 1, 0, 0); gbc_altitudeLabel.gridx = 2; gbc_altitudeLabel.gridy = 1; timeAndLocationPanel.add(latitudeLabel, gbc_altitudeLabel); latitudeSpinner = new JSpinner(); latitudeSpinner.setModel(new SpinnerNumberModel(Heliodon.DEFAULT_LATITUDE, -90, 90, 1)); latitudeSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { if (!cityComboBox.getSelectedItem().equals("") && !CityData.getInstance().getCityLatitutes().values().contains(latitudeSpinner.getValue())) cityComboBox.setSelectedItem(""); Heliodon.getInstance().setLatitude(((Integer) latitudeSpinner.getValue()) / 180.0 * Math.PI); compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); Scene.getInstance().setEdited(true); } }); final GridBagConstraints gbc_latitudeSpinner = new GridBagConstraints(); gbc_latitudeSpinner.fill = GridBagConstraints.HORIZONTAL; gbc_latitudeSpinner.gridx = 3; gbc_latitudeSpinner.gridy = 1; timeAndLocationPanel.add(latitudeSpinner, gbc_latitudeSpinner); timeAndLocationPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, timeAndLocationPanel.getPreferredSize().height)); final JPanel temperaturePanel = new JPanel(); temperaturePanel.setToolTipText("<html>Temperature difference drives heat transfer<br>between inside and outside.</html>"); temperaturePanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Temperature \u00B0C", TitledBorder.LEADING, TitledBorder.TOP)); dataPanel.add(temperaturePanel); final GridBagLayout gbl_temperaturePanel = new GridBagLayout(); temperaturePanel.setLayout(gbl_temperaturePanel); final JLabel insideTemperatureLabel = new JLabel("Inside: "); insideTemperatureLabel.setToolTipText(""); final GridBagConstraints gbc_insideTemperatureLabel = new GridBagConstraints(); gbc_insideTemperatureLabel.gridx = 1; gbc_insideTemperatureLabel.gridy = 0; temperaturePanel.add(insideTemperatureLabel, gbc_insideTemperatureLabel); insideTemperatureSpinner = new JSpinner(); insideTemperatureSpinner.setToolTipText("Thermostat temperature setting for the inside of the house"); insideTemperatureSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { if (disableActions) return; compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); } }); insideTemperatureSpinner.setModel(new SpinnerNumberModel(20, -70, 60, 1)); final GridBagConstraints gbc_insideTemperatureSpinner = new GridBagConstraints(); gbc_insideTemperatureSpinner.gridx = 2; gbc_insideTemperatureSpinner.gridy = 0; temperaturePanel.add(insideTemperatureSpinner, gbc_insideTemperatureSpinner); final JLabel outsideTemperatureLabel = new JLabel(" Outside: "); outsideTemperatureLabel.setToolTipText(""); final GridBagConstraints gbc_outsideTemperatureLabel = new GridBagConstraints(); gbc_outsideTemperatureLabel.gridx = 3; gbc_outsideTemperatureLabel.gridy = 0; temperaturePanel.add(outsideTemperatureLabel, gbc_outsideTemperatureLabel); temperaturePanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, temperaturePanel.getPreferredSize().height)); outsideTemperatureSpinner = new JSpinner(); outsideTemperatureSpinner.setToolTipText("Outside temperature at this time and day"); outsideTemperatureSpinner.setEnabled(false); outsideTemperatureSpinner.setModel(new SpinnerNumberModel(10, -70, 60, 1)); outsideTemperatureSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { if (disableActions) return; compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); } }); final GridBagConstraints gbc_outsideTemperatureSpinner = new GridBagConstraints(); gbc_outsideTemperatureSpinner.gridx = 4; gbc_outsideTemperatureSpinner.gridy = 0; temperaturePanel.add(outsideTemperatureSpinner, gbc_outsideTemperatureSpinner); final JPanel uFactorPanel = new JPanel(); uFactorPanel.setToolTipText("<html><b>U-factor</b><br>measures how well a building element conducts heat.</html>"); uFactorPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "U-Factor W/(m\u00B2.\u00B0C)", TitledBorder.LEADING, TitledBorder.TOP)); dataPanel.add(uFactorPanel); final GridBagLayout gbl_uFactorPanel = new GridBagLayout(); uFactorPanel.setLayout(gbl_uFactorPanel); final JLabel wallsLabel = new JLabel("Walls:"); final GridBagConstraints gbc_wallsLabel = new GridBagConstraints(); gbc_wallsLabel.anchor = GridBagConstraints.EAST; gbc_wallsLabel.insets = new Insets(0, 0, 5, 5); gbc_wallsLabel.gridx = 0; gbc_wallsLabel.gridy = 0; uFactorPanel.add(wallsLabel, gbc_wallsLabel); wallsComboBox = new WideComboBox(); wallsComboBox.setEditable(true); wallsComboBox.setModel(new DefaultComboBoxModel<String>(new String[] { "0.28 ", "0.67 (Concrete 8\")", "0.41 (Masonary Brick 8\")", "0.04 (Flat Metal 8\" Fiberglass Insulation)" })); wallsComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); updateCost(); } }); final GridBagConstraints gbc_wallsComboBox = new GridBagConstraints(); gbc_wallsComboBox.insets = new Insets(0, 0, 5, 5); gbc_wallsComboBox.gridx = 1; gbc_wallsComboBox.gridy = 0; uFactorPanel.add(wallsComboBox, gbc_wallsComboBox); final JLabel doorsLabel = new JLabel("Doors:"); final GridBagConstraints gbc_doorsLabel = new GridBagConstraints(); gbc_doorsLabel.anchor = GridBagConstraints.EAST; gbc_doorsLabel.insets = new Insets(0, 0, 5, 5); gbc_doorsLabel.gridx = 2; gbc_doorsLabel.gridy = 0; uFactorPanel.add(doorsLabel, gbc_doorsLabel); doorsComboBox = new WideComboBox(); doorsComboBox.setEditable(true); doorsComboBox.setModel(new DefaultComboBoxModel<String>(new String[] { "0.8 ", "1.2 (Steel)", "0.4 (Wood)" })); doorsComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); updateCost(); } }); final GridBagConstraints gbc_doorsComboBox = new GridBagConstraints(); gbc_doorsComboBox.insets = new Insets(0, 0, 5, 0); gbc_doorsComboBox.gridx = 3; gbc_doorsComboBox.gridy = 0; uFactorPanel.add(doorsComboBox, gbc_doorsComboBox); final JLabel windowsLabel = new JLabel("Windows:"); final GridBagConstraints gbc_windowsLabel = new GridBagConstraints(); gbc_windowsLabel.anchor = GridBagConstraints.EAST; gbc_windowsLabel.insets = new Insets(0, 0, 0, 5); gbc_windowsLabel.gridx = 0; gbc_windowsLabel.gridy = 1; uFactorPanel.add(windowsLabel, gbc_windowsLabel); windowsComboBox = new WideComboBox(); windowsComboBox.setEditable(true); windowsComboBox.setModel(new DefaultComboBoxModel<String>(new String[] { "1.0", "0.35 (Double Pane)", "0.15 (Triple Pane)" })); windowsComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); updateCost(); } }); final GridBagConstraints gbc_windowsComboBox = new GridBagConstraints(); gbc_windowsComboBox.insets = new Insets(0, 0, 0, 5); gbc_windowsComboBox.gridx = 1; gbc_windowsComboBox.gridy = 1; uFactorPanel.add(windowsComboBox, gbc_windowsComboBox); final JLabel roofsLabel = new JLabel("Roofs:"); final GridBagConstraints gbc_roofsLabel = new GridBagConstraints(); gbc_roofsLabel.anchor = GridBagConstraints.EAST; gbc_roofsLabel.insets = new Insets(0, 0, 0, 5); gbc_roofsLabel.gridx = 2; gbc_roofsLabel.gridy = 1; uFactorPanel.add(roofsLabel, gbc_roofsLabel); roofsComboBox = new WideComboBox(); roofsComboBox.setEditable(true); roofsComboBox.setModel(new DefaultComboBoxModel<String>(new String[] { "0.14 ", "0.23 (Concrete 3\")", "0.11 (Flat Metal 3\" Fiberglass Insulation)", "0.10 (Wood 3\" Fiberglass Insulation)" })); roofsComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); updateCost(); } }); final GridBagConstraints gbc_roofsComboBox = new GridBagConstraints(); gbc_roofsComboBox.gridx = 3; gbc_roofsComboBox.gridy = 1; uFactorPanel.add(roofsComboBox, gbc_roofsComboBox); uFactorPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, uFactorPanel.getPreferredSize().height)); final JPanel solarConversionPercentagePanel = new JPanel(); solarConversionPercentagePanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, solarConversionPercentagePanel.getPreferredSize().height)); solarConversionPercentagePanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Solar Conversion (%)", TitledBorder.LEADING, TitledBorder.TOP)); dataPanel.add(solarConversionPercentagePanel); final JLabel labelSHGC = new JLabel("Window (SHGC): "); labelSHGC.setToolTipText("<html><b>SHGC - Solar heat gain coefficient</b><br>measures the fraction of solar energy transmitted through a window.</html>"); solarConversionPercentagePanel.add(labelSHGC); windowSHGCComboBox = new WideComboBox(); windowSHGCComboBox.setEditable(true); windowSHGCComboBox.setModel(new DefaultComboBoxModel<String>(new String[] { "25", "50", "80" })); windowSHGCComboBox.setSelectedIndex(1); windowSHGCComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { // validate the input final String s = (String) windowSHGCComboBox.getSelectedItem(); double eff = 50; try { eff = Float.parseFloat(s); } catch (final NumberFormatException ex) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "Wrong format: must be 25-80.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (eff < 25 || eff > 80) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "Wrong range: must be 25-80.", "Error", JOptionPane.ERROR_MESSAGE); return; } Scene.getInstance().setWindowSolarHeatGainCoefficient(eff); updateCost(); } }); solarConversionPercentagePanel.add(windowSHGCComboBox); final JLabel labelPV = new JLabel("Solar Panel: "); labelPV.setToolTipText("<html><b>Solar photovoltaic efficiency</b><br>measures the fraction of solar energy converted into electricity by a solar panel.</html>"); solarConversionPercentagePanel.add(labelPV); solarPanelEfficiencyComboBox = new WideComboBox(); solarPanelEfficiencyComboBox.setEditable(true); solarPanelEfficiencyComboBox.setModel(new DefaultComboBoxModel<String>(new String[] { "10", "20", "30" })); solarPanelEfficiencyComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { // validate the input final String s = (String) solarPanelEfficiencyComboBox.getSelectedItem(); double eff = 10; try { eff = Float.parseFloat(s); } catch (final NumberFormatException ex) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "Wrong format: must be 10-50.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (eff < 10 || eff > 50) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "Wrong range: must be 10-50.", "Error", JOptionPane.ERROR_MESSAGE); return; } Scene.getInstance().setSolarPanelEfficiency(eff); updateCost(); } }); solarConversionPercentagePanel.add(solarPanelEfficiencyComboBox); heatMapPanel = new JPanel(new BorderLayout()); heatMapPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Heat Map Contrast", TitledBorder.LEADING, TitledBorder.TOP)); dataPanel.add(heatMapPanel); colorMapSlider = new MySlider(); colorMapSlider.setToolTipText("<html>Increase or decrease the color contrast of the heat map.</html>"); colorMapSlider.setMinimum(10); colorMapSlider.setMaximum(90); colorMapSlider.setMinimumSize(colorMapSlider.getPreferredSize()); colorMapSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { if (!colorMapSlider.getValueIsAdjusting()) { compute(SceneManager.getInstance().isSolarColorMap() ? UpdateRadiation.ALWAYS : UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); Scene.getInstance().setEdited(true, false); } } }); colorMapSlider.setSnapToTicks(true); colorMapSlider.setMinorTickSpacing(1); colorMapSlider.setMajorTickSpacing(5); heatMapPanel.add(colorMapSlider, BorderLayout.CENTER); heatMapPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, heatMapPanel.getPreferredSize().height)); partPanel = new JPanel(); partPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Part", TitledBorder.LEADING, TitledBorder.TOP)); dataPanel.add(partPanel); buildingPanel = new JPanel(); buildingPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Building", TitledBorder.LEADING, TitledBorder.TOP)); dataPanel.add(buildingPanel); buildingPanel.setLayout(new BoxLayout(buildingPanel, BoxLayout.Y_AXIS)); // geometry info for the selected building geometryPanel = new JPanel(); buildingPanel.add(geometryPanel); final GridBagLayout gbl_panel_2 = new GridBagLayout(); geometryPanel.setLayout(gbl_panel_2); lblPosition = new JLabel("Position:"); final GridBagConstraints gbc_lblPosition = new GridBagConstraints(); gbc_lblPosition.anchor = GridBagConstraints.EAST; gbc_lblPosition.insets = new Insets(0, 5, 5, 5); gbc_lblPosition.gridx = 0; gbc_lblPosition.gridy = 0; geometryPanel.add(lblPosition, gbc_lblPosition); positionTextField = new JTextField(); positionTextField.setEditable(false); final GridBagConstraints gbc_positionTextField = new GridBagConstraints(); gbc_positionTextField.weightx = 1.0; gbc_positionTextField.fill = GridBagConstraints.HORIZONTAL; gbc_positionTextField.anchor = GridBagConstraints.NORTH; gbc_positionTextField.insets = new Insets(0, 0, 5, 5); gbc_positionTextField.gridx = 1; gbc_positionTextField.gridy = 0; geometryPanel.add(positionTextField, gbc_positionTextField); positionTextField.setColumns(8); lblHeight = new JLabel("Height:"); final GridBagConstraints gbc_lblHeight = new GridBagConstraints(); gbc_lblHeight.anchor = GridBagConstraints.EAST; gbc_lblHeight.insets = new Insets(0, 0, 5, 5); gbc_lblHeight.gridx = 2; gbc_lblHeight.gridy = 0; geometryPanel.add(lblHeight, gbc_lblHeight); heightTextField = new JTextField(); heightTextField.setEditable(false); final GridBagConstraints gbc_heightTextField = new GridBagConstraints(); gbc_heightTextField.weightx = 1.0; gbc_heightTextField.fill = GridBagConstraints.HORIZONTAL; gbc_heightTextField.insets = new Insets(0, 0, 5, 0); gbc_heightTextField.anchor = GridBagConstraints.NORTH; gbc_heightTextField.gridx = 3; gbc_heightTextField.gridy = 0; geometryPanel.add(heightTextField, gbc_heightTextField); heightTextField.setColumns(5); lblArea = new JLabel("Area:"); final GridBagConstraints gbc_lblArea = new GridBagConstraints(); gbc_lblArea.anchor = GridBagConstraints.EAST; gbc_lblArea.insets = new Insets(0, 0, 10, 5); gbc_lblArea.gridx = 0; gbc_lblArea.gridy = 1; geometryPanel.add(lblArea, gbc_lblArea); areaTextField = new JTextField(); areaTextField.setEditable(false); final GridBagConstraints gbc_areaTextField = new GridBagConstraints(); gbc_areaTextField.fill = GridBagConstraints.HORIZONTAL; gbc_areaTextField.insets = new Insets(0, 0, 10, 5); gbc_areaTextField.gridx = 1; gbc_areaTextField.gridy = 1; geometryPanel.add(areaTextField, gbc_areaTextField); areaTextField.setColumns(5); lblVolume = new JLabel("Volume:"); final GridBagConstraints gbc_lblVolume = new GridBagConstraints(); gbc_lblVolume.anchor = GridBagConstraints.EAST; gbc_lblVolume.insets = new Insets(0, 0, 10, 5); gbc_lblVolume.gridx = 2; gbc_lblVolume.gridy = 1; geometryPanel.add(lblVolume, gbc_lblVolume); volumnTextField = new JTextField(); volumnTextField.setEditable(false); final GridBagConstraints gbc_volumnTextField = new GridBagConstraints(); gbc_volumnTextField.insets = new Insets(0, 0, 10, 0); gbc_volumnTextField.fill = GridBagConstraints.HORIZONTAL; gbc_volumnTextField.gridx = 3; gbc_volumnTextField.gridy = 1; geometryPanel.add(volumnTextField, gbc_volumnTextField); volumnTextField.setColumns(5); // cost for the selected building costPanel = new JPanel(new BorderLayout()); costPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Cost ($)", TitledBorder.LEADING, TitledBorder.TOP)); costPanel.setToolTipText("<html>The money needed if the selected building were to be constructed<br><b>Not to exceed the budget limit.</b></html>"); buildingPanel.add(costPanel); costBar = new ColorBar(Color.WHITE, Color.GRAY); costBar.setToolTipText(costPanel.getToolTipText()); costBar.setPreferredSize(new Dimension(200, 16)); costBar.setMaximum(Cost.getInstance().getBudget()); costBar.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { if (e.getClickCount() > 1) Cost.getInstance().showGraph(); } }); costPanel.add(costBar, BorderLayout.CENTER); final Component verticalGlue = Box.createVerticalGlue(); dataPanel.add(verticalGlue); progressBar = new JProgressBar(); add(progressBar, BorderLayout.SOUTH); JPanel target = buildingPanel; target.setMaximumSize(new Dimension(target.getMaximumSize().width, target.getPreferredSize().height)); final JPanel energyTodayPanel = new JPanel(); buildingPanel.add(energyTodayPanel); energyTodayPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Energy Today (kWh)", TitledBorder.LEADING, TitledBorder.TOP)); final GridBagLayout gbl_panel_1 = new GridBagLayout(); energyTodayPanel.setLayout(gbl_panel_1); final JLabel windowLabel = new JLabel("Windows"); windowLabel.setToolTipText("Renewable energy gained through windows"); windowLabel.setHorizontalAlignment(SwingConstants.CENTER); final GridBagConstraints gbc_windowLabel = new GridBagConstraints(); gbc_windowLabel.fill = GridBagConstraints.HORIZONTAL; gbc_windowLabel.insets = new Insets(0, 0, 5, 5); gbc_windowLabel.gridx = 0; gbc_windowLabel.gridy = 0; energyTodayPanel.add(windowLabel, gbc_windowLabel); final JLabel solarPanelLabel = new JLabel("Solar Panels"); solarPanelLabel.setToolTipText("Renewable energy harvested from solar panels"); solarPanelLabel.setHorizontalAlignment(SwingConstants.CENTER); final GridBagConstraints gbc_solarPanelLabel = new GridBagConstraints(); gbc_solarPanelLabel.fill = GridBagConstraints.HORIZONTAL; gbc_solarPanelLabel.insets = new Insets(0, 0, 5, 5); gbc_solarPanelLabel.gridx = 1; gbc_solarPanelLabel.gridy = 0; energyTodayPanel.add(solarPanelLabel, gbc_solarPanelLabel); final JLabel heatingLabel = new JLabel("Heater"); heatingLabel.setToolTipText("Nonrenewable energy for heating the building"); heatingLabel.setHorizontalAlignment(SwingConstants.CENTER); final GridBagConstraints gbc_heatingLabel = new GridBagConstraints(); gbc_heatingLabel.fill = GridBagConstraints.HORIZONTAL; gbc_heatingLabel.insets = new Insets(0, 0, 5, 5); gbc_heatingLabel.gridx = 2; gbc_heatingLabel.gridy = 0; energyTodayPanel.add(heatingLabel, gbc_heatingLabel); final JLabel coolingLabel = new JLabel("AC"); coolingLabel.setToolTipText("Nonrenewable energy for cooling the building"); coolingLabel.setHorizontalAlignment(SwingConstants.CENTER); final GridBagConstraints gbc_coolingLabel = new GridBagConstraints(); gbc_coolingLabel.fill = GridBagConstraints.HORIZONTAL; gbc_coolingLabel.insets = new Insets(0, 0, 5, 5); gbc_coolingLabel.gridx = 3; gbc_coolingLabel.gridy = 0; energyTodayPanel.add(coolingLabel, gbc_coolingLabel); final JLabel netEnergyLabel = new JLabel("Net"); netEnergyLabel.setToolTipText("<html><b>Net energy cost for this building</b><br>Negative if the energy it generates exceeds the energy it consumes.</html>"); netEnergyLabel.setHorizontalAlignment(SwingConstants.CENTER); final GridBagConstraints gbc_netEnergyLabel = new GridBagConstraints(); gbc_netEnergyLabel.fill = GridBagConstraints.HORIZONTAL; gbc_netEnergyLabel.insets = new Insets(0, 0, 5, 0); gbc_netEnergyLabel.gridx = 4; gbc_netEnergyLabel.gridy = 0; energyTodayPanel.add(netEnergyLabel, gbc_netEnergyLabel); windowTextField = new JTextField(); windowTextField.setToolTipText(windowLabel.getToolTipText()); final GridBagConstraints gbc_windowTextField = new GridBagConstraints(); gbc_windowTextField.weightx = 1.0; gbc_windowTextField.fill = GridBagConstraints.HORIZONTAL; gbc_windowTextField.insets = new Insets(0, 0, 0, 5); gbc_windowTextField.gridx = 0; gbc_windowTextField.gridy = 1; energyTodayPanel.add(windowTextField, gbc_windowTextField); windowTextField.setEditable(false); windowTextField.setColumns(5); solarPanelTextField = new JTextField(); solarPanelTextField.setToolTipText(solarPanelLabel.getToolTipText()); final GridBagConstraints gbc_solarPanelTextField = new GridBagConstraints(); gbc_solarPanelTextField.weightx = 1.0; gbc_solarPanelTextField.fill = GridBagConstraints.HORIZONTAL; gbc_solarPanelTextField.insets = new Insets(0, 0, 0, 5); gbc_solarPanelTextField.gridx = 1; gbc_solarPanelTextField.gridy = 1; energyTodayPanel.add(solarPanelTextField, gbc_solarPanelTextField); solarPanelTextField.setEditable(false); solarPanelTextField.setColumns(5); heatingTextField = new JTextField(); heatingTextField.setToolTipText(heatingLabel.getToolTipText()); heatingTextField.setEditable(false); final GridBagConstraints gbc_heatingTextField = new GridBagConstraints(); gbc_heatingTextField.weightx = 1.0; gbc_heatingTextField.insets = new Insets(0, 0, 0, 5); gbc_heatingTextField.fill = GridBagConstraints.HORIZONTAL; gbc_heatingTextField.gridx = 2; gbc_heatingTextField.gridy = 1; energyTodayPanel.add(heatingTextField, gbc_heatingTextField); heatingTextField.setColumns(5); coolingTextField = new JTextField(); coolingTextField.setToolTipText(coolingLabel.getToolTipText()); coolingTextField.setEditable(false); final GridBagConstraints gbc_coolingTextField = new GridBagConstraints(); gbc_coolingTextField.weightx = 1.0; gbc_coolingTextField.insets = new Insets(0, 0, 0, 5); gbc_coolingTextField.fill = GridBagConstraints.HORIZONTAL; gbc_coolingTextField.gridx = 3; gbc_coolingTextField.gridy = 1; energyTodayPanel.add(coolingTextField, gbc_coolingTextField); coolingTextField.setColumns(5); netEnergyTextField = new JTextField(); netEnergyTextField.setToolTipText(netEnergyLabel.getToolTipText()); netEnergyTextField.setEditable(false); final GridBagConstraints gbc_netEnergyTextField = new GridBagConstraints(); gbc_netEnergyTextField.weightx = 1.0; gbc_netEnergyTextField.fill = GridBagConstraints.HORIZONTAL; gbc_netEnergyTextField.gridx = 4; gbc_netEnergyTextField.gridy = 1; energyTodayPanel.add(netEnergyTextField, gbc_netEnergyTextField); netEnergyTextField.setColumns(5); energyTodayPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, energyTodayPanel.getPreferredSize().height)); final Dimension size = heatingLabel.getMinimumSize(); windowLabel.setMinimumSize(size); solarPanelLabel.setMinimumSize(size); coolingLabel.setMinimumSize(size); netEnergyLabel.setMinimumSize(size); target = partPanel; target.setMaximumSize(new Dimension(target.getMaximumSize().width, target.getPreferredSize().height)); partPanel.setLayout(new BoxLayout(partPanel, BoxLayout.Y_AXIS)); partPropertiesPanel = new JPanel(); partPanel.add(partPropertiesPanel); partProperty1Label = new JLabel("Width:"); partPropertiesPanel.add(partProperty1Label); partProperty1TextField = new JTextField(); partProperty1TextField.setEditable(false); partPropertiesPanel.add(partProperty1TextField); partProperty1TextField.setColumns(4); partProperty2Label = new JLabel("Height:"); partPropertiesPanel.add(partProperty2Label); partProperty2TextField = new JTextField(); partProperty2TextField.setEditable(false); partPropertiesPanel.add(partProperty2TextField); partProperty2TextField.setColumns(4); partProperty3Label = new JLabel("Insolation:"); partPropertiesPanel.add(partProperty3Label); partProperty3TextField = new JTextField(); partProperty3TextField.setEditable(false); partPropertiesPanel.add(partProperty3TextField); partProperty3TextField.setColumns(4); partProperty4Label = new JLabel(); partProperty4TextField = new JTextField(); partProperty4TextField.setEditable(false); partProperty4TextField.setColumns(4); } public void compute(final UpdateRadiation updateRadiation) { if (!computeEnabled) return; updateOutsideTemperature(); // TODO: There got to be a better way to do this this.updateRadiation = updateRadiation; if (thread != null && thread.isAlive()) computeRequest = true; else { thread = new Thread("Energy Computer") { @Override public void run() { do { computeRequest = false; // Scene.getInstance().updateAllTextures(); // clearAlreadyRendered(); /* since this thread can accept multiple computeRequest, cannot use updateRadiationColorMap parameter directly */ try { if (EnergyPanel.this.updateRadiation == UpdateRadiation.ALWAYS || (SceneManager.getInstance().isSolarColorMap() && (!alreadyRenderedHeatmap || keepHeatmapOn))) { alreadyRenderedHeatmap = true; computeNow(); } else { if (SceneManager.getInstance().isSolarColorMap()) MainPanel.getInstance().getSolarButton().setSelected(false); int numberOfHouses = 0; synchronized (Scene.getInstance().getParts()) { // XIE: This needs to be synchronized to avoid concurrent modification exceptions for (final HousePart part : Scene.getInstance().getParts()) { if (part instanceof Foundation && !part.getChildren().isEmpty() && !part.isFrozen()) numberOfHouses++; if (numberOfHouses >= 2) break; } for (final HousePart part : Scene.getInstance().getParts()) if (part instanceof Foundation) ((Foundation) part).setSolarLabelValue(numberOfHouses >= 2 && !part.getChildren().isEmpty() && !part.isFrozen() ? -1 : -2); } Scene.getInstance().redrawAll(); } SceneManager.getInstance().getSolarLand().setVisible(SceneManager.getInstance().isSolarColorMap()); } catch (final Throwable e) { e.printStackTrace(); Util.reportError(e); } try { Thread.sleep(500); } catch (final InterruptedException e) { e.printStackTrace(); } progressBar.setValue(0); progressBar.setStringPainted(false); } while (computeRequest); thread = null; } }; thread.start(); } } public void computeNow() { try { System.out.println("EnergyPanel.computeNow()"); progressBar.setValue(0); progressBar.setStringPainted(false); updateOutsideTemperature(); HeatLoad.getInstance().computeEnergyToday((Calendar) Heliodon.getInstance().getCalender().clone(), (Integer) insideTemperatureSpinner.getValue()); SolarIrradiation.getInstance().compute(); notifyPropertyChangeListeners(new PropertyChangeEvent(EnergyPanel.this, "Solar energy calculation completed", 0, 1)); updatePartEnergy(); // XIE: This needs to be called for trees to change texture when the month changes synchronized (Scene.getInstance().getParts()) { for (final HousePart p : Scene.getInstance().getParts()) if (p instanceof Tree) p.updateTextureAndColor(); } SceneManager.getInstance().refresh(); progressBar.setValue(100); } catch (final CancellationException e) { System.out.println("Energy compute cancelled."); } } // TODO: There should be a better way to do this. public void clearIrradiationHeatMap() { compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); } private void updateOutsideTemperature() { if (cityComboBox.getSelectedItem().equals("")) outsideTemperatureSpinner.setValue(15); else outsideTemperatureSpinner.setValue(Math.round(CityData.getInstance().computeOutsideTemperature(Heliodon.getInstance().getCalender()))); } public JSpinner getDateSpinner() { return dateSpinner; } public JSpinner getTimeSpinner() { return timeSpinner; } public void progress() { if (progressBar.getValue() < 100) { progressBar.setStringPainted(progressBar.getValue() > 0); progressBar.setValue(progressBar.getValue() + 1); } else { // progress() can be called once after it reaches 100% to reset progressBar.setStringPainted(false); progressBar.setValue(0); } } public void setLatitude(final int latitude) { latitudeSpinner.setValue(latitude); } public int getLatitude() { return (Integer) latitudeSpinner.getValue(); } public JSlider getColorMapSlider() { return colorMapSlider; } public void clearAlreadyRendered() { alreadyRenderedHeatmap = false; } public static void setKeepHeatmapOn(final boolean on) { keepHeatmapOn = on; } public void setComputeEnabled(final boolean computeEnabled) { this.computeEnabled = computeEnabled; } @Override public void addPropertyChangeListener(final PropertyChangeListener pcl) { propertyChangeListeners.add(pcl); } @Override public void removePropertyChangeListener(final PropertyChangeListener pcl) { propertyChangeListeners.remove(pcl); } private void notifyPropertyChangeListeners(final PropertyChangeEvent evt) { if (!propertyChangeListeners.isEmpty()) { synchronized (propertyChangeListeners) { for (final PropertyChangeListener x : propertyChangeListeners) { x.propertyChange(evt); } } } } public void updatePartEnergy() { final boolean iradiationEnabled = MainPanel.getInstance().getSolarButton().isSelected(); final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (selectedPart instanceof Foundation) { partProperty1Label.setText("Width:"); partProperty2Label.setText("Length:"); partProperty3Label.setText("Insolation:"); partPropertiesPanel.remove(partProperty4Label); partPropertiesPanel.remove(partProperty4TextField); } else if (selectedPart instanceof Sensor) { partProperty1Label.setText("X:"); partProperty2Label.setText("Y:"); partProperty3Label.setText("Z:"); partProperty4Label.setText("Data:"); partPropertiesPanel.add(partProperty4Label); partPropertiesPanel.add(partProperty4TextField); } else { partProperty1Label.setText("Width:"); partProperty2Label.setText("Height:"); partProperty3Label.setText("Insolation:"); partPropertiesPanel.remove(partProperty4Label); partPropertiesPanel.remove(partProperty4TextField); } partPropertiesPanel.revalidate(); ((TitledBorder) partPanel.getBorder()).setTitle("Part" + (selectedPart == null ? "" : (" - " + selectedPart.toString().substring(0, selectedPart.toString().indexOf(')') + 1)))); partPanel.repaint(); if (!iradiationEnabled || selectedPart == null || selectedPart instanceof Door || selectedPart instanceof Foundation) partProperty3TextField.setText(""); else { if (selectedPart instanceof Sensor) { final String light = twoDecimals.format(selectedPart.getSolarPotentialToday() / selectedPart.computeArea()); final String heatFlux = twoDecimals.format(selectedPart.getTotalHeatLoss() / selectedPart.computeArea()); partProperty4TextField.setText(light + ", " + heatFlux); partProperty4TextField.setToolTipText("Light sensor: " + light + ", heat flux sensor: " + heatFlux); } else partProperty3TextField.setText(twoDecimals.format(selectedPart.getSolarPotentialToday())); } if (selectedPart != null && !(selectedPart instanceof Roof || selectedPart instanceof Floor || selectedPart instanceof Tree)) { if (selectedPart instanceof SolarPanel) { partProperty1TextField.setText(twoDecimals.format(SolarPanel.WIDTH)); partProperty2TextField.setText(twoDecimals.format(SolarPanel.HEIGHT)); } else if (selectedPart instanceof Sensor) { final ReadOnlyVector3 v = ((Sensor) selectedPart).getAbsPoint(0); partProperty1TextField.setText(twoDecimals.format(v.getX() * Scene.getInstance().getAnnotationScale())); partProperty2TextField.setText(twoDecimals.format(v.getY() * Scene.getInstance().getAnnotationScale())); partProperty3TextField.setText(twoDecimals.format(v.getZ() * Scene.getInstance().getAnnotationScale())); } else { partProperty1TextField.setText(twoDecimals.format(selectedPart.getAbsPoint(0).distance(selectedPart.getAbsPoint(2)) * Scene.getInstance().getAnnotationScale())); partProperty2TextField.setText(twoDecimals.format(selectedPart.getAbsPoint(0).distance(selectedPart.getAbsPoint(1)) * Scene.getInstance().getAnnotationScale())); } } else { partProperty1TextField.setText(""); partProperty2TextField.setText(""); } final Foundation selectedBuilding; if (selectedPart == null) selectedBuilding = null; else if (selectedPart instanceof Foundation) selectedBuilding = (Foundation) selectedPart; else selectedBuilding = selectedPart.getTopContainer(); if (selectedBuilding != null) { if (iradiationEnabled) { windowTextField.setText(twoDecimals.format(selectedBuilding.getPassiveSolarToday())); solarPanelTextField.setText(twoDecimals.format(selectedBuilding.getPhotovoltaicToday())); heatingTextField.setText(twoDecimals.format(selectedBuilding.getHeatingToday())); coolingTextField.setText(twoDecimals.format(selectedBuilding.getCoolingToday())); netEnergyTextField.setText(twoDecimals.format(selectedBuilding.getTotalEnergyToday())); } else { windowTextField.setText(""); solarPanelTextField.setText(""); heatingTextField.setText(""); coolingTextField.setText(""); netEnergyTextField.setText(""); } final double[] buildingGeometry = selectedBuilding.getBuildingGeometry(); if (buildingGeometry != null) { positionTextField.setText("(" + twoDecimals.format(buildingGeometry[3]) + ", " + twoDecimals.format(buildingGeometry[4]) + ")"); heightTextField.setText(twoDecimals.format(buildingGeometry[0])); areaTextField.setText(twoDecimals.format(buildingGeometry[1])); volumnTextField.setText(twoDecimals.format(buildingGeometry[2])); } else { positionTextField.setText(""); heightTextField.setText(""); areaTextField.setText(""); volumnTextField.setText(""); } } else { windowTextField.setText(""); solarPanelTextField.setText(""); heatingTextField.setText(""); coolingTextField.setText(""); netEnergyTextField.setText(""); positionTextField.setText(""); heightTextField.setText(""); areaTextField.setText(""); volumnTextField.setText(""); } } public void updateCost() { final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); final Foundation selectedBuilding; if (selectedPart == null) selectedBuilding = null; else if (selectedPart instanceof Foundation) selectedBuilding = (Foundation) selectedPart; else selectedBuilding = selectedPart.getTopContainer(); int n = 0; if (selectedBuilding != null) n = Cost.getInstance().getBuildingCost(selectedBuilding); costBar.setValue(n); costBar.repaint(); } public void update() { updatePartEnergy(); updateCost(); } /** Currently this applies only to the date spinner when it is set programmatically (not by the user) */ public void disableActions(final boolean b) { disableActions = b; } public boolean isComputeRequest() { return computeRequest; } public JComboBox<String> getWallsComboBox() { return wallsComboBox; } public JComboBox<String> getDoorsComboBox() { return doorsComboBox; } public JComboBox<String> getWindowsComboBox() { return windowsComboBox; } public JComboBox<String> getRoofsComboBox() { return roofsComboBox; } public JComboBox<String> getCityComboBox() { return cityComboBox; } public JComboBox<String> getSolarPanelEfficiencyComboBox() { return solarPanelEfficiencyComboBox; } public JComboBox<String> getWindowSHGCComboBox() { return windowSHGCComboBox; } public void setBudget(final int budget) { costPanel.setBorder(BorderFactory.createTitledBorder(UIManager.getBorder("TitledBorder.border"), "Construction Cost (Maximum: $" + budget + ")", TitledBorder.LEADING, TitledBorder.TOP)); costBar.setMaximum(budget); costBar.repaint(); } }
//Title: TASSELMainFrame //Company: NCSU package net.maizegenetics.tassel; import net.maizegenetics.pal.alignment.Alignment; import net.maizegenetics.pal.alignment.PhenotypeUtils; import net.maizegenetics.pal.report.TableReportUtils; import net.maizegenetics.plugindef.DataSet; import net.maizegenetics.plugindef.Datum; import net.maizegenetics.prefs.TasselPrefs; import net.maizegenetics.gui.PrintTextArea; import javax.swing.*; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Event; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.*; import java.awt.image.ImageProducer; import java.io.*; import java.net.URL; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import net.maizegenetics.baseplugins.ExportPlugin; import net.maizegenetics.gui.PrintHeapAction; import net.maizegenetics.plugindef.PluginEvent; import net.maizegenetics.plugindef.ThreadedPluginListener; import net.maizegenetics.progress.ProgressPanel; import net.maizegenetics.util.Utils; import net.maizegenetics.wizard.Wizard; import net.maizegenetics.wizard.WizardPanelDescriptor; import net.maizegenetics.wizard.panels.TestPanel1Descriptor; import net.maizegenetics.wizard.panels.TestPanel2Descriptor; import net.maizegenetics.wizard.panels.TestPanel3Descriptor; import net.maizegenetics.wizard.panels.TestPanel4Descriptor; import org.apache.log4j.Logger; /** * TASSELMainFrame * */ public class TASSELMainFrame extends JFrame { private static final Logger myLogger = Logger.getLogger(TASSELMainFrame.class); public static final String version = "4.0.17"; public static final String versionDate = "April 26, 2012"; DataTreePanel theDataTreePanel; DataControlPanel theDataControlPanel; AnalysisControlPanel theAnalysisControlPanel; ResultControlPanel theResultControlPanel; private String tasselDataFile = "TasselDataFile"; //a variable to control when the progress bar was last updated private long lastProgressPaint = 0; private String dataTreeLoadFailed = "Unable to open the saved data tree. The file format of this version is " + "incompatible with other versions."; static final String GENOTYPE_DATA_NEEDED = "Please select genotypic data from the data tree."; static final String RESULTS_DATA_NEEDED = "Please select results data from the data tree."; JFileChooser filerSave = new JFileChooser(); JFileChooser filerOpen = new JFileChooser(); JPanel mainPanel = new JPanel(); JPanel dataTreePanelPanel = new JPanel(); JPanel reportPanel = new JPanel(); JPanel optionsPanel = new JPanel(); JPanel optionsPanelPanel = new JPanel(); JPanel modeSelectorsPanel = new JPanel(); JPanel buttonPanel = new JPanel(); GridLayout buttonPanelLayout = new GridLayout(); GridLayout optionsPanelLayout = new GridLayout(2, 1); JSplitPane dataTreeReportMainPanelsSplitPanel = new JSplitPane(); JSplitPane dataTreeReportPanelsSplitPanel = new JSplitPane(); JScrollPane reportPanelScrollPane = new JScrollPane(); JTextArea reportPanelTextArea = new JTextArea(); JScrollPane mainPanelScrollPane = new JScrollPane(); JPanel mainDisplayPanel = new JPanel(); //mainPanelTextArea corresponds to what is called Main Panel in the user documentation ThreadedJTextArea mainPanelTextArea = new ThreadedJTextArea(); JTextField statusBar = new JTextField(); JButton resultButton = new JButton(); JButton saveButton = new JButton(); JButton dataButton = new JButton(); JButton deleteButton = new JButton(); JButton printButton = new JButton(); JButton analysisButton = new JButton(); JPopupMenu mainPopupMenu = new JPopupMenu(); JMenuBar jMenuBar = new JMenuBar(); JMenu fileMenu = new JMenu(); JMenu toolsMenu = new JMenu(); JMenuItem saveMainMenuItem = new JMenuItem(); JCheckBoxMenuItem matchCheckBoxMenuItem = new JCheckBoxMenuItem(); JMenuItem openCompleteDataTreeMenuItem = new JMenuItem(); JMenuItem openDataMenuItem = new JMenuItem(); JMenuItem saveAsDataTreeMenuItem = new JMenuItem(); JMenuItem saveCompleteDataTreeMenuItem = new JMenuItem(); JMenuItem saveDataTreeAsMenuItem = new JMenuItem(); JMenuItem exitMenuItem = new JMenuItem(); JMenu helpMenu = new JMenu(); JMenuItem helpMenuItem = new JMenuItem(); JMenuItem preferencesMenuItem = new JMenuItem(); JMenuItem aboutMenuItem = new JMenuItem(); PreferencesDialog thePreferencesDialog; String UserComments = ""; private final ProgressPanel myProgressPanel = ProgressPanel.getInstance(); JButton wizardButton = new JButton(); ExportPlugin myExportPlugin = null; public TASSELMainFrame(boolean debug) { try { loadSettings(); addMenuBar(); theDataTreePanel = new DataTreePanel(this, true, debug); theDataTreePanel.setToolTipText("Data Tree Panel"); theDataControlPanel = new DataControlPanel(this, theDataTreePanel); theAnalysisControlPanel = new AnalysisControlPanel(this, theDataTreePanel); theResultControlPanel = new ResultControlPanel(this, theDataTreePanel); theResultControlPanel.setToolTipText("Report Panel"); initializeMyFrame(); setIcon(); initDataMode(); this.setTitle("TASSEL (Trait Analysis by aSSociation, Evolution, and Linkage) " + this.version); } catch (Exception e) { e.printStackTrace(); } } private void setIcon() { URL url = this.getClass().getResource("Logo_small.png"); if (url == null) { return; } Image img = null; try { img = createImage((ImageProducer) url.getContent()); } catch (Exception e) { } if (img != null) { setIconImage(img); } } private void initWizard() { Wizard wizard = new Wizard(theDataTreePanel); wizard.getDialog().setTitle("TASSEL Wizard (In development)"); WizardPanelDescriptor descriptor1 = new TestPanel1Descriptor(); wizard.registerWizardPanel(TestPanel1Descriptor.IDENTIFIER, descriptor1); WizardPanelDescriptor descriptor2 = new TestPanel2Descriptor(); wizard.registerWizardPanel(TestPanel2Descriptor.IDENTIFIER, descriptor2); WizardPanelDescriptor descriptor3 = new TestPanel3Descriptor(); wizard.registerWizardPanel(TestPanel3Descriptor.IDENTIFIER, descriptor3); WizardPanelDescriptor descriptor4 = new TestPanel4Descriptor(); wizard.registerWizardPanel(TestPanel4Descriptor.IDENTIFIER, descriptor4); wizard.setCurrentPanel(TestPanel1Descriptor.IDENTIFIER); wizard.getDialog().setLocationRelativeTo(this); int ret = wizard.showModalDialog(); // System.out.println("Dialog return code is (0=Finish,1=Cancel,2=Error): " + ret); // System.out.println("Second panel selection is: " + // (((TestPanel2)descriptor2.getPanelComponent()).getRadioButtonSelected())); // System.exit(0); } private JButton getHeapButton() { JButton heapButton = new JButton(PrintHeapAction.getInstance(this)); heapButton.setText("Show Memory"); heapButton.setToolTipText("Show Memory Usage"); return heapButton; } private void initDataMode() { buttonPanel.removeAll(); buttonPanel.add(theDataControlPanel, null); dataTreePanelPanel.removeAll(); dataTreePanelPanel.add(theDataTreePanel, BorderLayout.CENTER); this.validate(); repaint(); } private void initAnalysisMode() { buttonPanel.removeAll(); buttonPanel.add(theAnalysisControlPanel, null); dataTreePanelPanel.removeAll(); dataTreePanelPanel.add(theDataTreePanel, BorderLayout.CENTER); this.validate(); repaint(); } private void initResultMode() { buttonPanel.removeAll(); buttonPanel.add(theResultControlPanel, null); dataTreePanelPanel.removeAll(); dataTreePanelPanel.add(theDataTreePanel, BorderLayout.CENTER); this.validate(); repaint(); } //Component initialization private void initializeMyFrame() throws Exception { this.getContentPane().setLayout(new BorderLayout()); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // it is time for TASSEL to claim more (almost all) of the screen real estate for itself // this size was selected so as to encourage the user to resize to full screen, thereby // insuring that all parts of the frame are visible. this.setSize(new Dimension(screenSize.width * 19 / 20, screenSize.height * 19 / 20)); this.setTitle("TASSEL (Trait Analysis by aSSociation, Evolution, and Linkage)"); this.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(WindowEvent e) { this_windowClosing(e); } }); filerSave.setDialogType(JFileChooser.SAVE_DIALOG); mainPanel.setLayout(new BorderLayout()); dataTreeReportPanelsSplitPanel.setOrientation(JSplitPane.VERTICAL_SPLIT); optionsPanelPanel.setLayout(new BorderLayout()); dataTreePanelPanel.setLayout(new BorderLayout()); dataTreePanelPanel.setToolTipText("Data Tree Panel"); reportPanel.setLayout(new BorderLayout()); reportPanelTextArea.setEditable(false); reportPanelTextArea.setToolTipText("Report Panel"); mainPanelTextArea.setDoubleBuffered(true); mainPanelTextArea.setEditable(false); mainPanelTextArea.setFont(new java.awt.Font("Monospaced", 0, 12)); mainPanelTextArea.setToolTipText("Main Panel"); mainPanelTextArea.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(MouseEvent e) { mainTextArea_mouseClicked(e); } }); statusBar.setBackground(Color.lightGray); statusBar.setBorder(null); statusBar.setText("Program Status"); modeSelectorsPanel.setLayout(new GridBagLayout()); modeSelectorsPanel.setMinimumSize(new Dimension(380, 32)); modeSelectorsPanel.setPreferredSize(new Dimension(700, 32)); URL imageURL = TASSELMainFrame.class.getResource("images/help1.gif"); ImageIcon helpIcon = null; if (imageURL != null) { helpIcon = new ImageIcon(imageURL); } JButton helpButton = new JButton(); helpButton.setIcon(helpIcon); helpButton.setMargin(new Insets(0, 0, 0, 0)); helpButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { helpButton_actionPerformed(e); } }); helpButton.setBackground(Color.white); helpButton.setMinimumSize(new Dimension(20, 20)); helpButton.setToolTipText("Help me!!"); resultButton.setText("Results"); resultButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { resultButton_actionPerformed(e); } }); resultButton.setMargin(new Insets(2, 2, 2, 2)); imageURL = TASSELMainFrame.class.getResource("images/Results.gif"); ImageIcon resultsIcon = null; if (imageURL != null) { resultsIcon = new ImageIcon(imageURL); } if (resultsIcon != null) { resultButton.setIcon(resultsIcon); } resultButton.setPreferredSize(new Dimension(90, 25)); resultButton.setMinimumSize(new Dimension(87, 25)); resultButton.setMaximumSize(new Dimension(90, 25)); resultButton.setBackground(Color.white); wizardButton.setText("Wizard"); wizardButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { wizardButton_actionPerformed(e); } }); wizardButton.setMargin(new Insets(2, 2, 2, 2)); wizardButton.setPreferredSize(new Dimension(90, 25)); wizardButton.setMinimumSize(new Dimension(87, 25)); wizardButton.setMaximumSize(new Dimension(90, 25)); wizardButton.setBackground(Color.white); saveButton.setMargin(new Insets(0, 0, 0, 0)); saveButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { saveButton_actionPerformed(e); } }); saveButton.setBackground(Color.white); saveButton.setMinimumSize(new Dimension(20, 20)); saveButton.setToolTipText("Save selected data to text file"); imageURL = TASSELMainFrame.class.getResource("images/save1.gif"); ImageIcon saveIcon = null; if (imageURL != null) { saveIcon = new ImageIcon(imageURL); } if (saveIcon != null) { saveButton.setIcon(saveIcon); } dataButton.setBackground(Color.white); dataButton.setMaximumSize(new Dimension(90, 25)); dataButton.setMinimumSize(new Dimension(87, 25)); dataButton.setPreferredSize(new Dimension(90, 25)); imageURL = TASSELMainFrame.class.getResource("images/DataSeq.gif"); ImageIcon dataSeqIcon = null; if (imageURL != null) { dataSeqIcon = new ImageIcon(imageURL); } if (dataSeqIcon != null) { dataButton.setIcon(dataSeqIcon); } dataButton.setMargin(new Insets(2, 2, 2, 2)); dataButton.setText("Data"); dataButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { dataButton_actionPerformed(e); } }); printButton.setBackground(Color.white); printButton.setToolTipText("Print selected datum"); imageURL = TASSELMainFrame.class.getResource("images/print1.gif"); ImageIcon printIcon = null; if (imageURL != null) { printIcon = new ImageIcon(imageURL); } if (printIcon != null) { printButton.setIcon(printIcon); } printButton.setMargin(new Insets(0, 0, 0, 0)); printButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { printButton_actionPerformed(e); } }); analysisButton.setText("Analysis"); analysisButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { analysisButton_actionPerformed(e); } }); analysisButton.setMargin(new Insets(2, 2, 2, 2)); imageURL = TASSELMainFrame.class.getResource("images/Analysis.gif"); ImageIcon analysisIcon = null; if (imageURL != null) { analysisIcon = new ImageIcon(imageURL); } if (analysisIcon != null) { analysisButton.setIcon(analysisIcon); } analysisButton.setPreferredSize(new Dimension(90, 25)); analysisButton.setMinimumSize(new Dimension(87, 25)); analysisButton.setMaximumSize(new Dimension(90, 25)); analysisButton.setBackground(Color.white); // delete button added moved from data panel by yogesh. deleteButton.setOpaque(true); deleteButton.setForeground(Color.RED); deleteButton.setText("Delete"); deleteButton.setFont(new java.awt.Font("Dialog", 1, 12)); deleteButton.setToolTipText("Delete Dataset"); deleteButton.setMargin(new Insets(2, 2, 2, 2)); deleteButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { theDataTreePanel.deleteSelectedNodes(); } }); optionsPanel.setLayout(optionsPanelLayout); buttonPanel.setLayout(buttonPanelLayout); buttonPanel.setMinimumSize(new Dimension(300, 34)); buttonPanel.setPreferredSize(new Dimension(300, 34)); buttonPanelLayout.setHgap(0); buttonPanelLayout.setVgap(0); optionsPanel.setToolTipText("Options Panel"); optionsPanelLayout.setVgap(0); mainPopupMenu.setInvoker(this); saveMainMenuItem.setText("Save"); matchCheckBoxMenuItem.setText("Match"); matchCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { matchCheckBoxMenuItem_actionPerformed(e); } }); fileMenu.setText("File"); toolsMenu.setText("Tools"); saveCompleteDataTreeMenuItem.setText("Save Data Tree"); saveCompleteDataTreeMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveCompleteDataTreeMenuItem_actionPerformed(e); } }); saveDataTreeAsMenuItem.setText("Save Data Tree As ..."); saveDataTreeAsMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { saveDataTreeMenuItem_actionPerformed(e); } }); openCompleteDataTreeMenuItem.setText("Open Data Tree"); openCompleteDataTreeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { openCompleteDataTreeMenuItem_actionPerformed(e); } }); openDataMenuItem.setText("Open Data Tree..."); openDataMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { openDataMenuItem_actionPerformed(e); } }); saveAsDataTreeMenuItem.setText("Save Selected As..."); saveAsDataTreeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { ExportPlugin plugin = getExportPlugin(); PluginEvent event = new PluginEvent(theDataTreePanel.getSelectedTasselDataSet()); ProgressPanel progressPanel = getProgressPanel(); ThreadedPluginListener thread = new ThreadedPluginListener(plugin, event); thread.start(); progressPanel.addPlugin(plugin); } }); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { exitMenuItem_actionPerformed(e); } }); helpMenu.setText("Help"); helpMenuItem.setText("Help Manual"); helpMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { helpButton_actionPerformed(e); } }); preferencesMenuItem.setText("Set Preferences"); preferencesMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { preferencesMenuItem_actionPerformed(e); } }); aboutMenuItem.setText("About"); aboutMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { helpAbout_actionPerformed(e); } }); this.getContentPane().add(dataTreeReportMainPanelsSplitPanel, BorderLayout.CENTER); dataTreeReportMainPanelsSplitPanel.add(optionsPanelPanel, JSplitPane.TOP); optionsPanelPanel.add(dataTreeReportPanelsSplitPanel, BorderLayout.CENTER); dataTreeReportPanelsSplitPanel.add(dataTreePanelPanel, JSplitPane.TOP); dataTreePanelPanel.add(theDataTreePanel, BorderLayout.CENTER); JSplitPane reportProgress = new JSplitPane(JSplitPane.VERTICAL_SPLIT); reportProgress.add(reportPanel, JSplitPane.TOP); reportPanel.add(reportPanelScrollPane, BorderLayout.CENTER); reportPanelScrollPane.getViewport().add(reportPanelTextArea, null); reportProgress.add(new JScrollPane(myProgressPanel), JSplitPane.BOTTOM); dataTreeReportPanelsSplitPanel.add(reportProgress, JSplitPane.BOTTOM); dataTreeReportMainPanelsSplitPanel.add(mainPanel, JSplitPane.BOTTOM); /** * Provides a save filer that remembers the last location something was saved to */ public File getSaveFile() { File saveFile = null; int returnVal = filerSave.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { saveFile = filerSave.getSelectedFile(); TasselPrefs.putSaveDir(filerSave.getCurrentDirectory().getPath()); } return saveFile; } /** * Provides a open filer that remember the last location something was opened from */ public File getOpenFile() { File openFile = null; int returnVal = filerOpen.showOpenDialog(this); System.out.println("returnVal = " + returnVal); System.out.println("JFileChooser.OPEN_DIALOG " + JFileChooser.OPEN_DIALOG); if (returnVal == JFileChooser.OPEN_DIALOG || returnVal == JFileChooser.APPROVE_OPTION) { openFile = filerOpen.getSelectedFile(); System.out.println("openFile = " + openFile); TasselPrefs.putOpenDir(filerOpen.getCurrentDirectory().getPath()); } return openFile; } void this_windowClosing(WindowEvent e) { exitMenuItem_actionPerformed(null); } public void addDataSet(DataSet theDataSet, String defaultNode) { theDataTreePanel.addDataSet(theDataSet, defaultNode); } private void saveDataTree(String file) { Map dataToSerialize = new LinkedHashMap(); Map dataFromTree = theDataTreePanel.getDataList(); StringBuilder builder = new StringBuilder(); Iterator itr = dataFromTree.keySet().iterator(); while (itr.hasNext()) { Datum currentDatum = (Datum) itr.next(); String currentNode = (String) dataFromTree.get(currentDatum); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(currentDatum); oos.close(); if (out.toByteArray().length > 0) { dataToSerialize.put(currentDatum, currentNode); } } catch (Exception e) { myLogger.warn("saveDataTree: object: " + currentDatum.getName() + " type: " + currentDatum.getData().getClass().getName() + " does not serialize."); myLogger.warn("saveDataTree: message: " + e.getMessage()); if (builder.length() == 0) { builder.append("Due to error, these data sets could not\n"); builder.append("included in the saved file..."); } builder.append("Data set: "); builder.append(currentDatum.getName()); builder.append(" type: "); builder.append(currentDatum.getData().getClass().getName()); builder.append("\n"); } } try { File theFile = new File(Utils.addSuffixIfNeeded(file, ".zip")); FileOutputStream fos = new FileOutputStream(theFile); java.util.zip.ZipOutputStream zos = new ZipOutputStream(fos); Map data = theDataTreePanel.getDataList(); ZipEntry thisEntry = new ZipEntry("DATA"); zos.putNextEntry(thisEntry); ObjectOutputStream oos = new ObjectOutputStream(zos); oos.writeObject(dataToSerialize); oos.flush(); zos.closeEntry(); fos.close(); sendMessage("Data saved to " + theFile.getAbsolutePath()); } catch (Exception ee) { sendErrorMessage("Data could not be saved: " + ee); ee.printStackTrace(); } if (builder.length() != 0) { JOptionPane.showMessageDialog(this, builder.toString(), "These data sets not saved...", JOptionPane.INFORMATION_MESSAGE); } } private boolean readDataTree(String file) { boolean loadedDataTreePanel = false; try { FileInputStream fis = null; ObjectInputStream ois = null; if (file.endsWith("zip")) { fis = new FileInputStream(file); java.util.zip.ZipInputStream zis = new java.util.zip.ZipInputStream(fis); zis.getNextEntry(); ois = new ObjectInputStream(zis); } else { fis = new FileInputStream(file); ois = new ObjectInputStream(fis); } try { Map data = (Map) ois.readObject(); Iterator itr = data.keySet().iterator(); while (itr.hasNext()) { Datum currentDatum = (Datum) itr.next(); String currentNode = (String) data.get(currentDatum); theDataTreePanel.addDatum(currentNode, currentDatum); } loadedDataTreePanel = true; } catch (InvalidClassException ice) { JOptionPane.showMessageDialog(this, dataTreeLoadFailed, "Incompatible File Format", JOptionPane.INFORMATION_MESSAGE); } finally { fis.close(); } if (loadedDataTreePanel) { sendMessage("Data loaded."); } } catch (FileNotFoundException fnfe) { JOptionPane.showMessageDialog(this, "File not found: " + file, "File not found", JOptionPane.INFORMATION_MESSAGE); sendErrorMessage("Data tree could not be loaded."); return false; } catch (Exception ee) { JOptionPane.showMessageDialog(this, dataTreeLoadFailed + ee, "Incompatible File Format", JOptionPane.INFORMATION_MESSAGE); sendErrorMessage("Data tree could not be loaded."); return false; } return loadedDataTreePanel; } private void wizardButton_actionPerformed(ActionEvent e) { initWizard(); } private void dataButton_actionPerformed(ActionEvent e) { initDataMode(); } private void analysisButton_actionPerformed(ActionEvent e) { initAnalysisMode(); } private void resultButton_actionPerformed(ActionEvent e) { initResultMode(); } private void saveButton_actionPerformed(ActionEvent e) { File theFile = getSaveFile(); if (theFile == null) { return; } DataSet ds = theDataTreePanel.getSelectedTasselDataSet(); try { FileWriter fw = new FileWriter(theFile); PrintWriter pw = new PrintWriter(fw); for (int i = 0; i < ds.getSize(); i++) { if (ds.getData(i).getData() instanceof Alignment) { pw.println(ds.getData(i).getData().toString()); } else if (ds.getData(i).getData() instanceof net.maizegenetics.pal.alignment.Phenotype) { PhenotypeUtils.saveAs((net.maizegenetics.pal.alignment.Phenotype) ds.getData(i).getData(), pw); } else if (ds.getData(i).getData() instanceof net.maizegenetics.pal.report.TableReport) { // TableReportUtils tbu=new TableReportUtils((net.maizegenetics.pal.report.TableReport)data[i]); pw.println(TableReportUtils.toDelimitedString((net.maizegenetics.pal.report.TableReport) ds.getData(i).getData(), "\t")); } else { pw.println(ds.getData(i).getData().toString()); } pw.println(""); } fw.flush(); fw.close(); } catch (Exception ee) { System.err.println("saveButton_actionPerformed:" + ee); } this.statusBar.setText("Datasets were saved to " + theFile.getName()); } private void printButton_actionPerformed(ActionEvent e) { DataSet ds = theDataTreePanel.getSelectedTasselDataSet(); try { for (int i = 0; i < ds.getSize(); i++) { PrintTextArea pta = new PrintTextArea(this); pta.printThis(ds.getData(i).getData().toString()); } } catch (Exception ee) { System.err.println("printButton_actionPerformed:" + ee); } this.statusBar.setText("Datasets were sent to the printer"); } private void helpButton_actionPerformed(ActionEvent e) { HelpDialog theHelpDialog = new HelpDialog(this); theHelpDialog.setLocationRelativeTo(this); theHelpDialog.setVisible(true); } private void mainTextArea_mouseClicked(MouseEvent e) { // For this example event, we are checking for right-mouse click. if (e.getModifiers() == Event.META_MASK) { mainPanelTextArea.add(mainPopupMenu); // JPopupMenu must be added to the component whose event is chosen. // Make the jPopupMenu visible relative to the current mouse position in the container. mainPopupMenu.show(mainPanelTextArea, e.getX(), e.getY()); } } private void matchCheckBoxMenuItem_actionPerformed(ActionEvent e) { //theSettings.matchChar = matchCheckBoxMenuItem.isSelected(); } private void openCompleteDataTreeMenuItem_actionPerformed(ActionEvent e) { String dataFileName = this.tasselDataFile + ".zip"; File dataFile = new File(dataFileName); if (dataFile.exists()) { readDataTree(dataFileName); } else if (new File("QPGADataFile").exists()) { // this exists to maintain backward compatibility with previous versions (pre-v0.99) readDataTree("QPGADataFile"); } else { JOptionPane.showMessageDialog(this, "File: " + dataFile.getAbsolutePath() + " does not exist.\n" + "Try using File/Open Data Tree..."); } } private void openDataMenuItem_actionPerformed(ActionEvent e) { File f = getOpenFile(); if (f != null) { readDataTree(f.getAbsolutePath()); } } private void saveDataTreeMenuItem_actionPerformed(ActionEvent e) { File f = getSaveFile(); if (f != null) { saveDataTree(f.getAbsolutePath()); } } private void saveCompleteDataTreeMenuItem_actionPerformed(ActionEvent e) { saveDataTree(this.tasselDataFile + ".zip"); } private void exitMenuItem_actionPerformed(ActionEvent e) { System.exit(0); } private void preferencesMenuItem_actionPerformed(ActionEvent e) { if (thePreferencesDialog == null) { thePreferencesDialog = new PreferencesDialog(); thePreferencesDialog.pack(); } thePreferencesDialog.setLocationRelativeTo(this); thePreferencesDialog.setVisible(true); } public void updateMainDisplayPanel(JPanel panel) { mainDisplayPanel.removeAll(); mainDisplayPanel.add(panel, BorderLayout.CENTER); mainDisplayPanel.repaint(); mainDisplayPanel.validate(); } public void addMenu(JMenu menu) { jMenuBar.add(menu); } public DataTreePanel getDataTreePanel() { return theDataTreePanel; } public ProgressPanel getProgressPanel() { return myProgressPanel; } }
package org.cryptable.asn1.runtime.ber; import org.cryptable.asn1.runtime.exception.ASN1Exception; import java.math.BigInteger; public class Utils { /** * get the TAG from the byteArray * * @param value bytae array containing the TAG Length Value * @return return Integer value of the TAG * @throws ASN1Exception when unsupported ASN1 TAG (greater then 31) */ public static int getTAG(byte[] value) throws ASN1Exception { if ((int)value[0] > 31) throw new ASN1Exception("Not yet supported TAGs [" + (int)value[0] + "]"); return value[0]; } /** * Calculate the TAG length for the bytes * * @param tag TAG parameter * @return byte length to allocate for the TAG */ public static int calculateTAGByteLength(long tag) { if (tag >= 31) return 2; else return 1; } /** * Calculate the Length length for the bytes * * @param length The length of the value in bytes * @return the byte length to allocate for the Length * @throws ASN1Exception */ public static int calculateLengthByteLength(int length) throws ASN1Exception { if (length < 0) throw new ASN1Exception("Invalid length (NEGATIVE)"); if (length <= 127) { return 1; } else { return (BigInteger.valueOf(length).toByteArray().length + 1); } } /** * Get the Length as bytes to be filled in the BER value * * @param length Length value as an integer * @return bytes containing the Length value * @throws ASN1Exception */ public static byte[] getLengthInBytes(int length) throws ASN1Exception { if (length < 0) throw new ASN1Exception("Invalid length (NEGATIVE)"); if (length <= 127) { return BigInteger.valueOf(length).toByteArray(); } else { byte[] value = BigInteger.valueOf(length).toByteArray(); byte[] result = new byte[value.length+1]; byte byteLength = (byte) (0x80 | (byte)value.length); result[0] = byteLength; System.arraycopy(value, 0, result, 1, value.length); return result; } } }